Edgar Navasardyan Edgar Navasardyan - 15 days ago 8
Python Question

Django exception handling cancels non-atomic transaction mode

Best described by example.
Consider the following code (Django 1.9)

View:

@transaction.non_atomic_requests
def error_generating_view(request):
modelA = ModelA(...)
modelA.save()
if (some_bad_condition)
return json_error_msg ('Some custom message')
return HttpResponse(True)


View in other module

def json_error_msg(error_message):
return JsonResponse(json.dumps(error_message, ensure_ascii=False), status = 500, safe = False)


Django seems to through an exception to client-side, but the problem here is that modelA instance is saved, although I set up
@transaction.non_atomic_requests
. It looks like I am doing something wrong with exception handling syntax.

Could anyone point to what exactly I should rectify here to make Django through customized exception message to client and simultaneously treat the entire view as terminated incorrectly so that the transaction is rolled back ?

Answer

Use transaction.atomic decorator, not transaction.non_atomic_requests - by using transaction.non_atomic_requests you're telling Django, that this request should NOT be wrapped in transaction (every change is auto-commited to the database)