Skip to content

Instantly share code, notes, and snippets.

@pwistrand
Created April 14, 2016 13:24
Show Gist options
  • Save pwistrand/c11f5ed5d8601f26381339e3552aadb8 to your computer and use it in GitHub Desktop.
Save pwistrand/c11f5ed5d8601f26381339e3552aadb8 to your computer and use it in GitHub Desktop.
Python decorator that can accept an SQLAlchemy engine and make the function context transactional and automatically rollback. Great for integration tests.
from functools import wraps
def rollback(engine):
def rollback_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
with engine.connect() as connection:
with connection.begin() as tx:
try:
kwargs['connection'] = connection
func(*args, **kwargs)
finally:
tx.rollback()
return wrapper
return rollback_decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment