ATOMIC_REQUEST and Transactions in Django 1.6

Given the following code:

from django.db import transaction @transaction.atomic def viewfunc(request): # This code executes inside a transaction. do_stuff() 

From my understanding of transactions in Django 1.6, if do_stuff throws an exception, say IntegrityError, then the transaction will be rejected to the right. But since Django itself calls the view, nothing will stop IntegrityError from raising the call stack and cause an HTTP 500 error, huh? Suppose that it’s not what we want, because we want to gracefully handle this error, but still get the rollback functionality.

So, I think the obvious thought is good, do not do this, use transaction.atomic as the context manager wrapped in try, except for the block, for example, here:

 try: with transaction.atomic(): generate_relationships() except IntegrityError: handle_exception() 

Fine But then, if you want to use the Transaction for HTTP Request function by setting ATOMIC_REQUEST = True to the db configuration, this means that django will actually just add the transaction.atomic decoration to your view, which will not catch any exceptions. How is ATOMIC_REQUEST even useful? Why do you want your database errors to spread to the user?

So my question.

  • What am I missing here, or is my understanding correct?
  • If I understand correctly, what is used to use ATOMIC_REQUEST? Do I have to write urls.hadler500 or do I need to implement some middleware to catch errors?
+7
python django transactions
source share
1 answer

Your understanding is correct. What you are missing is that an exception from your view code (which is very different from "distribute all the way to the user") is a completely normal task in Django.

You can customize this behavior by creating a 500.html template , redefining handler500, or by creating your own middleware. In all of these standard cases, using ATOMIC_REQUESTS will do what you want.

If you want to catch exceptions in your view code and handle them specifically, you can do this, you just need to specify how to handle transactions manually. Using ATOMIC_REQUESTS is just a way to save some template pattern for a normal case, allowing you to customize behavior in an unusual case.

+4
source share

All Articles