Skip to content

Instantly share code, notes, and snippets.

@honzajavorek
Created February 17, 2012 14:43
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save honzajavorek/1853867 to your computer and use it in GitHub Desktop.
Save honzajavorek/1853867 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
# Apparently, this is reinventing the wheel, you can do almost the same with pure SQLAlchemy,
# see http://docs.sqlalchemy.org/en/latest/orm/session.html#autocommit-mode, following should
# work (not tested):
with db.session.begin():
admin = User('admin')
db.session.add(admin)
@8749236
Copy link

8749236 commented Oct 14, 2020

This is great, except begin(), it appears flask sqlalchemy seems always have a session available, calling begin() will cause it to complain that a session already exists.
I prefer Transaction class approach. With minor addition that on exception, it will auto rollback any changes.

@honzajavorek
Copy link
Author

I haven't used this for years, it's probably quite outdated :) The gist is 9 years old.

@8749236
Copy link

8749236 commented Oct 2, 2021

Sorry for the late reply. It still works fine and greatly improved readability =D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment