Django异常处理取消非原子事务模式 [英] Django exception handling cancels non-atomic transaction mode
问题描述
考虑以下代码( Django 1.9 )
查看:
@ 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)
在其他模块中查看
def json_error_msg(error_message):
返回JsonResponse(json.dumps(error_message ,ensure_ascii = False),status = 500,safe = False)
Django似乎通过一个例外客户端,但这里的问题是,modelA实例被保存,虽然我设置了 @ transaction.non_atomic_requests
。看起来我做错了异常处理语法错误。
任何人都可以指出,我应该纠正这一点,以使Django通过自定义的异常消息给客户端,同时将整个视图视为不正确的终止,以便事务被回滚?
使用 transaction.atomic
装饰器,而不是 transaction.non_atomic_requests
- 使用 transaction.non_atomic_requests
你告诉Django,这个请求不应该被包装在事务中每个更改都会自动提交给数据库)
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 ?
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)
这篇关于Django异常处理取消非原子事务模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!