from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker class DB(object): def __init__(self, address, debug=False): self.engine = engine = create_engine(address, echo=debug) self.sessionmaker = sessionmaker(engine) def __enter__(self): self.session = session = self.sessionmaker() return session def __exit__(self, exc_type, exc_value, traceback): session = self.session try: if exc_type is None and session.is_active: session.commit() finally: session.close()