spacepaste

  1.  
  2. from sqlalchemy import create_engine
  3. from sqlalchemy.orm import sessionmaker
  4. class DB(object):
  5. def __init__(self, address, debug=False):
  6. self.engine = engine = create_engine(address, echo=debug)
  7. self.sessionmaker = sessionmaker(engine)
  8. def __enter__(self):
  9. self.session = session = self.sessionmaker()
  10. return session
  11. def __exit__(self, exc_type, exc_value, traceback):
  12. session = self.session
  13. try:
  14. if exc_type is None and session.is_active:
  15. session.commit()
  16. finally:
  17. session.close()
  18.