Created
November 9, 2019 09:33
-
-
Save Dakad/20db5c0ec062c618f5c0b58521493f0c to your computer and use it in GitHub Desktop.
Decorators to handle transactional sessions : http://dev.nando.audio/2014/04/01/large_apps_with_sqlalchemy__architecture.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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