Skip to content

Instantly share code, notes, and snippets.

@xkal36
Last active October 19, 2018 11:31
Show Gist options
  • Save xkal36/d6f00f8249ce48c5c4c867696ebc92fd to your computer and use it in GitHub Desktop.
Save xkal36/d6f00f8249ce48c5c4c867696ebc92fd to your computer and use it in GitHub Desktop.
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