Django Transactions ATOMIC_REQUESTS
Asked Answered
J

2

7

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 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?

Jenelljenelle answered 30/7, 2015 at 21:23 Comment(0)
W
10

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. [The non_atomic_requests] decorator will negate the effect of ATOMIC_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()
Warrin answered 30/7, 2015 at 23:28 Comment(3)
so if I use transaction.atomic on a view without ATOMIC_REQUESTS enabled and it will use an atomic transaction on that view? Sorry for explicitly asking, but for me the docs don't give a clear answer to these questions.Jenelljenelle
@ip.: Yes, that's true for any function or block of code, including a view.Warrin
If needs be, see my answer to rollback from inside an atomic block.Thermoluminescence
A
1

Yes, if 'ATOMIC_REQUESTS': True is set in settings.py, all views run in a transaction.

Yes, if @transaction.non_atomic_requests decorator is set to a view, the view doesn't run in a transaction even if 'ATOMIC_REQUESTS': True is set in settings.py.

In addition, Django admin is run in a transaction by default whether or not 'ATOMIC_REQUESTS': True is set in settings.py.

Astonishment answered 19/10, 2022 at 14:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.