Last active
October 19, 2018 11:31
-
-
Save xkal36/d6f00f8249ce48c5c4c867696ebc92fd to your computer and use it in GitHub Desktop.
This file contains hidden or 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
def db_transaction(flush=False): | |
""" | |
Takes care of rolling back, committing and closing | |
session for decorated function. | |
""" | |
def wrap(f): | |
def wrapped_f(*args, **kwargs): | |
session = kwargs.get('session') | |
try: | |
result = f(*args, **kwargs) | |
except Exception: | |
session.rollback() | |
raise | |
finally: | |
if flush: | |
session.flush() | |
session.commit() | |
session.close() | |
return result | |
return wrapped_f | |
return wrap | |
@db_transaction(flush=True) | |
def add_model(model, session=Session()): | |
session.add(model) | |
return model |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment