首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在4xx或5xx HTTP状态码上使django模型原子性回滚

问如何在4xx或5xx HTTP状态码上使django模型原子性回滚
EN

Stack Overflow用户
提问于 2016-02-29 06:37:38
回答 1查看 182关注 0票数 2

据我所知,django原子性开箱即用,只有在抛出异常时才会回滚事务。但是,我在我的脚本中捕获了几个异常,对于这些异常,我生成了一个很好的HTTPresponse,为用户提供了一些有意义的响应内容-但我总是确保在这种情况下发送的HTTPresponse带有适当的4xx或5xxHTTP状态代码。当这样的HTTPresponse发生时,我希望django回滚到目前为止它可能执行的所有数据库查询。但是,django原子性似乎不是基于发出的HTTP状态代码执行的,它只根据抛给用户的异常执行。有什么建议可以用python 2.7上的django 1.8解决这个问题吗?

EN

回答 1

Stack Overflow用户

发布于 2016-02-29 07:28:14

尝试创建一个将执行此操作的自定义中间件。以下是一个based on the old TransactionMiddleware的示例(这是未经测试的):

代码语言:javascript
复制
from django.db import transaction

class StatusCodeTransactionMiddleware(object):
    """
    Rolls back the current transaction for all responses with 4xx or 5xx status
    codes.
    """

    def process_request(self, request):
        """Enters transaction management"""
        transaction.enter_transaction_management()

    def process_response(self, request, response):
        """Commits and leaves transaction management."""
        if response.status_code >= 400:
            if transaction.is_dirty():
                # This rollback might fail because of network failure for
                # example. If rollback isn't possible it is impossible to
                # clean the connection's state. So leave the connection in
                # dirty state and let request_finished signal deal with
                # cleaning the connection.
                transaction.rollback()
            transaction.leave_transaction_management()
        else:
            if not transaction.get_autocommit():
                if transaction.is_dirty():
                    # Note: it is possible that the commit fails. If the
                    # reason is closed connection or some similar reason,
                    # then there is little hope to proceed nicely.
                    # However, in some cases ( deferred foreign key checks
                    # for example) it is still possible to rollback().
                    try:
                        transaction.commit()
                    except Exception:
                        # If the rollback fails, the transaction state will
                        # be messed up. It doesn't matter, the connection
                        # will be set to clean state after the request
                        # finishes. And, we can't clean the state here
                        # properly even if we wanted to, the connection is
                        # in transaction but we can't rollback...
                        transaction.rollback()
                        transaction.leave_transaction_management()
                        raise
                transaction.leave_transaction_management()
        return response

像这样把它放到你的MIDDLEWARE_CLASSES中:

代码语言:javascript
复制
MIDDLEWARE_CLASSES = (
    "myapp.middleware.StatusCodeTransactionMiddleware",
    # Other middleware...
)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35689183

复制
相关文章

相似问题

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