Skip to content

Commit

Permalink
Merge pull request #227 from Uninett/uninett.fix_session_sideeffect
Browse files Browse the repository at this point in the history
Put sessionmaker code in a function
  • Loading branch information
indy-independence authored Jan 12, 2022
2 parents 1516524 + 8c8f90e commit 51adce6
Showing 1 changed file with 10 additions and 6 deletions.
16 changes: 10 additions & 6 deletions src/cnaas_nms/db/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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()
Expand Down

0 comments on commit 51adce6

Please sign in to comment.