"""MySQL connector.""" from contextlib import contextmanager from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import scoped_session from sqlalchemy.orm import sessionmaker from label_copy_export import config BaseModel = declarative_base() _label_copy_export_history_engine = create_engine( config.LCE_DB_CONNECTION_STRING, poolclass=config.DB_POOLCLASS, connect_args=config.DB_CONNECT_ARGS) _label_copy_export_history_factory = sessionmaker( bind=_label_copy_export_history_engine, expire_on_commit=False) Session = scoped_session(_label_copy_export_history_factory) @contextmanager def label_copy_export_history_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 label_copy_export_history_session_scope() as session: session.execute(query) """ session = Session() try: yield session session.commit() except: session.rollback() raise finally: session.close() _ar_db_engine = create_engine( config.AR_DB_CONNECTION_STRING, poolclass=config.DB_POOLCLASS, connect_args=config.DB_CONNECT_ARGS) _ar_db_factory = sessionmaker( bind=_ar_db_engine, expire_on_commit=False) ArSession = scoped_session(_ar_db_factory) @contextmanager def ar_db_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 label_copy_export_history_session_scope() as session: session.execute(query) """ session = ArSession() try: yield session session.commit() except: session.rollback() raise finally: session.close()