Created
April 14, 2016 13:24
-
-
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.
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
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