Skip to content

Instantly share code, notes, and snippets.

@sfelde
Forked from honzajavorek/gist:1853867
Created February 17, 2012 14:54
Show Gist options
  • Save sfelde/1853908 to your computer and use it in GitHub Desktop.
Save sfelde/1853908 to your computer and use it in GitHub Desktop.
A readable way how to work with Flask-SQLAlchemy
class Transaction(object):
def __init__(self, db):
self.db = db
def __enter__(self):
return self.db.session
def __exit__(self, type, value, traceback):
if not value:
self.db.session.commit()
# now we can do this:
with Transaction(db) as session:
admin = User('admin', 'admin@example.com')
session.add(admin) # session is available for adding etc.
# automatic commit performed when exiting 'with' section
with Transaction(db):
admin.email = 'root@example.com'
# automatic commit performed when exiting 'with' section
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment