如果视图代码抛出异常,则所有django transaction stuff都会回滚事务。如果我返回一个带有错误状态码的HttpResponse,比如4xx或5xx,我如何让它回滚?
发布于 2012-11-29 02:20:56
好吧,我根本没有测试过它,我也不知道它是否正确,但是像这样的东西可能会起作用。如有反馈,我将不胜感激!
from functools import wraps
from django.utils.decorators import available_attrs
from django.db import transaction
from django.http import HttpResponse
def commit_on_http_success(function=None, using=None, successStatuses=[200]):
"""Like commit_on_success, but rolls back the commit if we return an HttpResponse
with a status that isn't 200 (by default).
Args:
using: The database to use. Uses the default if None.
successStatuses: The HTTP statuses for which we will commit the transaction.
Raises:
It can raise an exception that overrides the view's exception if commit() or
rollback() fails.
"""
def decorator(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
try:
transaction.enter_transaction_management(using=using)
transaction.managed(True, using=using)
exc = None
commit = False
try:
response = view_func(request, *args, **kwargs)
if isinstance(response, HttpResponse) and response.status in successStatuses:
commit = True
except Exception, exc:
pass
if transaction.is_dirty(using=using):
if commit:
try:
transaction.commit(using=using)
except:
transaction.rollback(using=using)
raise
else:
transaction.rollback(using=using)
finally:
transaction.leave_transaction_management(using=using)
if exc is not None:
raise exc
return response
return _wrapped_view
if function:
return decorator(function)
return decoratorhttps://stackoverflow.com/questions/13610515
复制相似问题