我现在要使用的方法使用HttpResponse的子类:
from django.template import loader
from django.http import HttpResponse
# use custom response class to override HttpResponse.close()
class LogSuccessResponse(HttpResponse):
def close(self):
super(LogSuccessResponse, self).close()
# do whatever you want, this is the last codepoint in request handling
if self.status_code == 200:
print('HttpResponse successful: %s' % self.status_code)
# this would be the view definition
def logging_view(request):
response = LogSuccessResponse('Hello World', mimetype='text/plain')
return response
通过阅读Django代码,我非常确信HttpResponse.close()是将代码注入请求处理的最新点.我不确定是否确实存在使用此方法比上面提到的方法处理得更好的错误情况,所以我暂时不考虑这个问题.
与lazerScience的答案中提到的其他方法相比,我更喜欢这种方法的原因是,它可以单独在视图中设置,并且不需要安装中间件.另一方面,使用REQUEST_FINISHED信号不允许我访问响应对象.