"""DB Connector. Manages interactions with Relational Database (MySQL and SQLite). """ from contextlib import contextmanager from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from backend import config db_engine = create_engine( config.DB_URL, poolclass=config.POOL_CLASS) # please don't use _db_session directly; # instead use db_session _db_session = sessionmaker(bind=db_engine) BaseModel = declarative_base() @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()