I'm really unclear how atomic requests are set in Django. When ATOMIC_REQUESTS is set to True in the DB settings does that mean that all views now run in a transaction? What if I want only want only certain views to be run in a transaction? Do I then need to explicitly define all the others that are not run in a transaction with a @transaction.non_atomic_requests
decorator?
Tying transactions to HTTP requestsSet ATOMIC_REQUESTS to True in the configuration of each database for which you want to enable this behavior. It works like this. Before calling a view function, Django starts a transaction. If the response is produced without problems, Django commits the transaction.
When you run multiple workers of your Django application, you will run into concurrency issues when the same queryset is updated by different processes at the same time. To prevent this, use select_for_update inside a transaction block to fetch your queryset so that it is locked until the transaction is completed.
You can't execute queries until the end of the 'atomic' block." is raised when you try to used a database connection after a database exception even those autocommit was set to false from the start. It should be up to the user how to handle the database exception and the transaction as autocommit was set to false.
What is a transaction DBMS? Transactions refer to a set of operations that are used for performing a set of logical work. Usually, a transaction means the data present in the DB has changed. Protecting the user data from system failures is one of the primary uses of DBMS.
When ATOMIC_REQUESTS
is set to True
in the DB settings does that mean that all views now run in a transaction?
Yes. From the docs:
Before calling a view function, Django starts a transaction. If the response is produced without problems, Django commits the transaction. If the view produces an exception, Django rolls back the transaction.
Do I then need to explicitly define all the others that are not run in a transaction with a @transaction.non_atomic_requests
decorator?
Yes.
When
ATOMIC_REQUESTS
is enabled, it’s still possible to prevent views from running in a transaction. [Thenon_atomic_requests
] decorator will negate the effect ofATOMIC_REQUESTS
for a given view.
Once you're at the point of deciding on a case-by-case basis where transactions should be used, though, I prefer to not use ATOMIC_REQUESTS
and just use transaction.atomic
(whether as a decorator or a context manager) where appropriate. Here's an example from the documentation:
@transaction.atomic
def viewfunc(request):
# This code executes inside a transaction.
do_stuff()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With