from contextlib import contextmanager from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from masters_registry import config # please don't use the following private variables directly; # use mr_session_scope _masters_registry_engine = create_engine( config.AR_DB_URL, poolclass=config.POOLCLASS) _masters_registry_session = sessionmaker(bind=_masters_registry_engine) @contextmanager def mr_session_scope(): """Provide a transactional scope around a series of operations. Taken from http://docs.sqlalchemy.org/en/latest/orm/session_basics.html. This handles rollback and closing of session, so there is no need to do that throughout the code. Usage: with mr_session_scope() as session: session.execute(query) """ session = _masters_registry_session() try: yield session session.commit() except: # noqa: E722 session.rollback() raise finally: session.close() _bulk_statuses_engine = create_engine( config.BULK_STATUSES_DB_URL, poolclass=config.POOLCLASS) _bulk_statuses_session = sessionmaker(bind=_bulk_statuses_engine) @contextmanager def bulk_statuses_session_scope(): """Provide a transactional scope around a series of operations. Taken from http://docs.sqlalchemy.org/en/latest/orm/session_basics.html. This handles rollback and closing of session, so there is no need to do that throughout the code. Usage: with bulk_statuses_session_scope() as session: session.execute(query) """ session = _bulk_statuses_session() try: yield session session.commit() except: # noqa: E722 session.rollback() raise finally: session.close()