Skip to content

Instantly share code, notes, and snippets.

@rm-you
Created September 18, 2015 17:57
Show Gist options
  • Save rm-you/1450b1267d636ecb4dac to your computer and use it in GitHub Desktop.
Save rm-you/1450b1267d636ecb4dac to your computer and use it in GitHub Desktop.
DB_ENGINE = <have your engine available here>
@contextmanager
def get_session():
"""Provide a transactional scope around a series of operations."""
session = sqlalchemy.orm.sessionmaker(bind=DB_ENGINE)()
try:
yield session
session.commit()
except:
session.rollback()
raise
finally:
session.close()
with get_session() as db_session:
# Do some DB stuff in you nice fancy db_session
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment