django middleware
图片来自网络
process_request --> url ---> process_view --> view ---> process_response
测试
自定义middleware
app01.middlewaretest.py 包含5个方法可以定制
#!/usr/bin/env python3 # -*- coding:utf-8 -*- from django.utils.deprecation import MiddlewareMixin class Mid2(MiddlewareMixin): def process_request(self,request): print('process_requst 2') pass def process_view(self, request, callback, callback_args, callback_kwargs): print('process_view 2') pass def process_template_response(self, request, response): print('process_template 2') pass def process_exception(self, request, exception): print('process_except 2') pass def process_response(self, request, response): print('process_response 2') return response class Mid3(MiddlewareMixin): def process_request(self,request): print('process_requst 3') pass def process_view(self, request, callback, callback_args, callback_kwargs): print('process_view 3') pass def process_template_response(self, request, response): print('process_template 3') pass def process_exception(self, request, exception): print('process_except 3') pass def process_response(self, request, response): print('process_response 3') return response
setting中顺序
MIDDLEWARE = [ ...... 默认略 ...... 'app01.middlewaretest.Mid2', 'app01.middlewaretest.Mid3', ]
view
def index2(request): # print(request.id) print("in view of fbv...") return HttpResponse('a')
日志,正常访问未触发到process_template_response与process_exception
[31/Aug/2018 15:46:56] "GET /index2/ HTTP/1.1" 200 1 process_requst 2 process_requst 3 process_view 2 process_view 3 in view of fbv... process_response 3 process_response 2