Login

Commit on success unless managed decorator

Author:
Kronuz
Posted:
September 13, 2009
Language:
Python
Version:
1.1
Score:
0 (after 0 ratings)

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

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.