Login

Commit on success unless managed decorator

Author:
Kronuz
Posted:
September 13, 2009
Language:
Python
Version:
1.1
Tags:
decorator transaction
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. Nested commit_on_success by rfk 6 years, 1 month ago
  2. nested transactions context manager and decorator by demanzano 3 years, 7 months ago
  3. Queryset Foreach by kcarnold 6 years ago
  4. dumpdata/loaddata with MySQL and ForeignKeys, as django command by brondsem 5 years, 11 months ago
  5. Adding data in a transaction by hughdbrown 5 years, 8 months ago

Comments

Please login first before commenting.