首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >HTTP错误响应上的Django事务回滚

HTTP错误响应上的Django事务回滚
EN

Stack Overflow用户
提问于 2012-11-29 01:03:50
回答 1查看 367关注 0票数 1

如果视图代码抛出异常,则所有django transaction stuff都会回滚事务。如果我返回一个带有错误状态码的HttpResponse,比如4xx或5xx,我如何让它回滚?

EN

回答 1

Stack Overflow用户

发布于 2012-11-29 02:20:56

好吧,我根本没有测试过它,我也不知道它是否正确,但是像这样的东西可能会起作用。如有反馈,我将不胜感激!

代码语言:javascript
复制
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 decorator
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13610515

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档