据我所知,django原子性开箱即用,只有在抛出异常时才会回滚事务。但是,我在我的脚本中捕获了几个异常,对于这些异常,我生成了一个很好的HTTPresponse,为用户提供了一些有意义的响应内容-但我总是确保在这种情况下发送的HTTPresponse带有适当的4xx或5xxHTTP状态代码。当这样的HTTPresponse发生时,我希望django回滚到目前为止它可能执行的所有数据库查询。但是,django原子性似乎不是基于发出的HTTP状态代码执行的,它只根据抛给用户的异常执行。有什么建议可以用python 2.7上的django 1.8解决这个问题吗?
发布于 2016-02-29 07:28:14
尝试创建一个将执行此操作的自定义中间件。以下是一个based on the old TransactionMiddleware的示例(这是未经测试的):
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中:
MIDDLEWARE_CLASSES = (
"myapp.middleware.StatusCodeTransactionMiddleware",
# Other middleware...
)https://stackoverflow.com/questions/35689183
复制相似问题