Django

Code

root/django/branches/magic-removal/docs/transactions.txt

Revision 2793, 5.3 kB (checked in by adrian, 2 years ago)

magic-removal: Proofread docs/transactions.txt

Line 
1 ==============================
2 Managing database transactions
3 ==============================
4
5 Django gives you a few ways to control how database transactions are managed.
6
7 Django's default transaction behavior
8 =====================================
9
10 Django's default behavior is to commit automatically when any built-in,
11 data-altering model function is called. For example, if you call
12 ``model.save()`` or ``model.delete()``, the change will be committed
13 immediately.
14
15 This is much like the auto-commit setting for most databases. As soon as you
16 perform an action that needs to write to the database, Django produces the
17 ``INSERT``/``UPDATE``/``DELETE`` statements and then does the ``COMMIT``.
18 There's no implicit ``ROLLBACK``.
19
20 Tying transactions to HTTP requests
21 ===================================
22
23 The recommended way to handle transactions in Web requests is to tie them to
24 the request and response phases via Django's ``TransactionMiddleware``.
25
26 It works like this: When a request starts, Django starts a transaction. If the
27 response is produced without problems, Django commits any pending transactions.
28 If the view function produces an exception, Django rolls back any pending
29 transactions.
30
31 To activate this feature, just add the ``TransactionMiddleware`` middleware to
32 your ``MIDDLEWARE_CLASSES`` setting::
33
34     MIDDLEWARE_CLASSES = (
35         "django.contrib.sessions.middleware.SessionMiddleware",
36         "django.middleware.common.CommonMiddleware",
37         "django.middleware.cache.CacheMiddleware",
38         "django.middleware.transaction.TransactionMiddleware",
39     )
40
41 The order is quite important. The transaction middleware applies not only to
42 view functions, but also for all middleware modules that come after it. So if
43 you use the session middleware after the transaction middleware, session
44 creation will be part of the transaction.
45
46 An exception is ``CacheMiddleware``, which is never affected. The cache
47 middleware uses its own database cursor (which is mapped to its own database
48 connection internally).
49
50 Controlling transaction management in views
51 ===========================================
52
53 For most people, implicit request-based transactions work wonderfully. However,
54 if you need more fine-grained control over how transactions are managed, you
55 can use Python decorators to change the way transactions are handled by a
56 particular view function.
57
58 .. note::
59
60     Although the examples below use view functions as examples, these
61     decorators can be applied to non-view functions as well.
62
63 ``django.db.transaction.autocommit``
64 ------------------------------------
65
66 Use the ``autocommit`` decorator to switch a view function to Django's default
67 commit behavior, regardless of the global transaction setting.
68
69 Example::
70
71     from django.db import transaction
72
73     @transaction.autocommit
74     def viewfunc(request):
75         ....
76
77 Within ``viewfunc()``, transactions will be committed as soon as you call
78 ``model.save()``, ``model.delete()``, or any other function that writes to the
79 database.
80
81 ``django.db.transaction.commit_on_success``
82 -------------------------------------------
83
84 Use the ``commit_on_success`` decorator to use a single transaction for
85 all the work done in a function::
86
87     from django.db import transaction
88
89     @transaction.commit_on_success
90     def viewfunc(request):
91         ....
92
93 If the function returns successfully, then Django will commit all work done
94 within the function at that point. If the function raises an exception, though,
95 Django will roll back the transaction.
96
97 ``django.db.transaction.commit_manually``
98 -----------------------------------------
99
100 Use the ``commit_manually`` decorator if you need full control over
101 transactions. It tells Django you'll be managing the transaction on your own.
102
103 If your view changes data and doesn't ``commit()`` or ``rollback()``, Django
104 will raise a ``TransactionManagementError`` exception.
105
106 Manual transaction management looks like this::
107
108     from django.db import transaction
109
110     @transaction.commit_manually
111     def viewfunc(request):
112         ...
113         # You can commit/rollback however and whenever you want
114         transaction.commit()
115         ...
116
117         # But you've got to remember to do it yourself!
118         try:
119             ...
120         except:
121             transaction.rollback()
122         else:
123             transaction.commit()
124
125 ..admonition:: An important note to users of earlier Django releases:
126
127     The database ``connection.commit()`` and ``connection.rollback()`` methods
128     (called ``db.commit()`` and ``db.rollback()`` in 0.91 and earlier) no longer
129     exist. They've been replaced by ``transaction.commit()`` and
130     ``transaction.rollback()``.
131
132 How to globally deactivate transaction management
133 =================================================
134
135 Control freaks can totally disable all transaction management by setting
136 ``DISABLE_TRANSACTION_MANAGEMENT`` to ``True`` in the Django settings file.
137
138 If you do this, Django won't provide any automatic transaction management
139 whatsoever. Middleware will no longer implicitly commit transactions, and
140 you'll need to roll management yourself. This even requires you to commit
141 changes done by middleware somewhere else.
142
143 Thus, this is best used in situations where you want to run your own
144 transaction-controlling middleware or do something really strange. In almost
145 all situations, you'll be better off using the default behavior, or the
146 transaction middleware, and only modify selected functions as needed.
Note: See TracBrowser for help on using the browser.