Django exception handling cancels non-atomic transaction mode

浪尽此生 提交于 2019-12-12 01:56:35

问题


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 ?


回答1:


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)



来源:https://stackoverflow.com/questions/40790388/django-exception-handling-cancels-non-atomic-transaction-mode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!