diff --git a/src/cnaas_nms/db/session.py b/src/cnaas_nms/db/session.py index 5a115368..2e02c70f 100644 --- a/src/cnaas_nms/db/session.py +++ b/src/cnaas_nms/db/session.py @@ -7,6 +7,7 @@ from sqlalchemy.pool import NullPool from redis import StrictRedis +_sessionmaker = None def get_dbdata(config='/etc/cnaas-nms/db_config.yml'): with open(config, 'r') as db_file: @@ -31,16 +32,19 @@ def get_sqlalchemy_conn_str(**kwargs) -> str: f"{db_data['hostname']}:{db_data['port']}/{db_data['database']}" ) - -conn_str = get_sqlalchemy_conn_str() -engine = create_engine(conn_str, pool_size=50, max_overflow=50) -connection = engine.connect() -Session = sessionmaker(bind=engine) +def _get_session(): + global _sessionmaker + if _sessionmaker is None: + conn_str = get_sqlalchemy_conn_str() + engine = create_engine(conn_str, pool_size=50, max_overflow=50) + engine.connect() + _sessionmaker = sessionmaker(bind=engine) + return _sessionmaker() @contextmanager def sqla_session(**kwargs): - session = Session() + session = _get_session() try: yield session session.commit()