我现在要使用的方法使用HttpResponse的子类:
from django.template import loaderfrom 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 prepoint in request handling if self.status_pre == 200: print('HttpResponse successful: %s' % self.status_pre)# this would be the view definitiondef logging_view(request): response = LogSuccessResponse('Hello World', mimetype='text/plain') return response通过阅读Django代码,我非常相信HttpResponse.close()是将代码注入到请求处理中的最新点。与上述情况相比,我不确定是否真的有这种方法可以更好地处理错误情况,因此我暂时不提问题。
与lazerscience的答案中提到的其他方法相比,我更喜欢这种方法的原因是,它可以仅在视图中设置,并且不需要安装中间件。另一方面,使用request_finished信号将不允许我访问响应对象。



