This decorator is to make it's decorated function to commit the transaction on success (rollback otherwise) unless the transactions are being already managed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | try:
from functools import wraps
except ImportError:
from django.utils.functional import wraps # Python 2.3, 2.4 fallback.
from django.db import transaction
def commit_on_success_unless_managed(func):
"""
If the decorated function runs successfully, a commit is made, unless the
transactions are being managed; if the function produces an exception,
a rollback is made, again unless transactions are being managed somewhere
else.
"""
def _commit_on_success_unless_managed(*args, **kw):
try:
if transaction.is_managed():
forced_managed = False
else:
transaction.enter_transaction_management()
forced_managed = True
try:
res = func(*args, **kw)
except:
# All exceptions must be handled here (even string ones).
if transaction.is_dirty():
if forced_managed:
transaction.rollback()
else:
transaction.rollback_unless_managed()
raise
else:
if transaction.is_dirty():
if forced_managed:
transaction.commit()
else:
transaction.commit_unless_managed()
return res
finally:
if forced_managed:
transaction.leave_transaction_management()
return wraps(func)(_commit_on_success_unless_managed)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.