"""MySQL Connector. Manages interactions with MySQL. """ from contextlib import contextmanager from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from product_film import config # please don't use the following private variables directly; # use db_session _db_engine = create_engine( config.DB_URL, poolclass=config.POOL_CLASS, encoding=config.DB_ENGINE_ENCODING, pool_recycle=config.DB_CONNECTION_POOL_RECYCLE_TIMEOUT) _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()