Chapter 12.4.4. Encapsulating Transactions Using a Decorator

Lucky for us, there is a solution. Instead of performing your domain actions through a wrapper function such as do_in_transaction, you can use a decorator instead. The syntax is sweet, and your intention is clear. The only downside is that decorators appeared in Python 2.4. The transaction decorator is similar to do_in_transaction; it sets the sqlhub.threadConnection attribute, intercepts exceptions, calls your function, and commits, or rolls back, if an exception occured. Finally, it restores the original sqlhub connection:

 def transaction(): def decorate(func): def decorated(*args, **kwargs): exception_raised = False conn = sqlhub.getConnection() t = sqlhub.threadConnection = conn.transaction() ...

Get Rapid Web Applications with TurboGears: Using Python to Create Ajax-Powered Sites now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.