访问 :8000/midtest/ ,可在控制台得到这样的输出,验证了之前关于中间件执行顺序的理论
MyMiddleware1 processing request... MyMiddleware2 processing request... MyMiddleware1 processing view... MyMiddleware2 processing view... in mid_test view MyMiddleware2 processing response... MyMiddleware1 processing response... [08/Jun/2020 17:32:54] "GET /midtest/ HTTP/1.1" 200 2 中间件的中断如果process_request返回了一个HttpResponse对象
class MyMiddleware1(MiddlewareMixin): def __str__(self): return "MyMiddleware1" def process_request(self, request): print(self, " processing request...") return HttpResponse("break")下层中间件将不会被执行,response会按原路返回
MyMiddleware1 processing request... MyMiddleware1 processing response... [08/Jun/2020 18:08:21] "GET /midtest/ HTTP/1.1" 200 5如果process_view返回了一个HttpResponse对象,同样
class MyMiddleware1(MiddlewareMixin): def __str__(self): return "MyMiddleware1" def process_request(self, request): print(self, " processing request...") return HttpResponse("break") MyMiddleware1 processing request... MyMiddleware2 processing request... MyMiddleware1 processing view... MyMiddleware2 processing response... MyMiddleware1 processing response... [08/Jun/2020 18:11:00] "GET /midtest/ HTTP/1.1" 200 5 视图异常如果视图引发了异常,如
from django.http import HttpResponse def mid_test(request): print('in mid_test view') 1/0 return HttpResponse('ok')则Django会逆序调用中间件的process_exception方法,紧接着逆序调用process_response方法
MyMiddleware1 processing request... MyMiddleware2 processing request... MyMiddleware1 processing view... MyMiddleware2 processing view... in mid_test view MyMiddleware2 processing exception... MyMiddleware1 processing exception... Internal Server Error: /midtest/ Traceback (most recent call last): File "/home/demo/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/demo/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/demo/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/demo/views.py", line 6, in mid_test 1/0 ZeroDivisionError: division by zero MyMiddleware2 processing response... MyMiddleware1 processing response...如果process_exception返回了一个HttpResponse对象
class MyMiddleware2(MiddlewareMixin): def process_exception(self, request, exception): print(self, " processing exception...") return HttpResponse('not ok')页面会显示process_exception返回的内容,而不再使用默认异常处理。并且,此中间件之上的中间件类的process_exception方法不会被调用。但是process_response方法仍然会被逆序调用
MyMiddleware1 processing request... MyMiddleware2 processing request... MyMiddleware1 processing view... MyMiddleware2 processing view... in mid_test view MyMiddleware2 processing exception... MyMiddleware2 processing response... MyMiddleware1 processing response... 参考资料Django中间件 --刘江