Skip to content

Instantly share code, notes, and snippets.

@Dakad
Created November 9, 2019 09:33
Show Gist options
  • Save Dakad/20db5c0ec062c618f5c0b58521493f0c to your computer and use it in GitHub Desktop.
Save Dakad/20db5c0ec062c618f5c0b58521493f0c to your computer and use it in GitHub Desktop.
from functools import wraps
def transaction(fn):
'''Decorator that encloses the decorated function in a DB transaction.
The decorated function does not need to session.commit(). Usage::
@transaction
def my_function(): # (...)
If any exception is raised from this function, the session is rewinded.
But if you pass ``persist=None`` when calling your decorated function,
the session is neither committed nor rewinded. This is great for tests
because you are still in the transaction when asserting the result.
If you pass ``persist=False``, the session is always rewinded.
The default is ``persist=True``, meaning yes, commit the transaction.
'''
@wraps(fn)
def wrapper(*a, **kw):
persist = kw.pop('persist', True)
try:
fn(*a, **kw)
except:
db.session.rollback()
raise
else:
if persist is False:
db.session.rollback()
elif persist is True:
db.session.commit()
return wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment