"""Connection to DB.""" from contextlib import contextmanager from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from images import config # please don't use the following private variables directly; # use db_session _db_engine = create_engine( config.AR_CONNECTION_URL, poolclass=config.POOL_CLASS) _db_session = sessionmaker(bind=_db_engine) @contextmanager def db_session(): """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 db_session() as session: session.execute(query) """ session = _db_session() try: yield session session.commit() except: session.rollback() raise finally: session.close()