django中间件
from django.utils.deprecation import MiddlewareMixin class m1(MiddlewareMixin): def process_request(self, request): print('m1.process_request') def process_response(self, request, response): print('m1.process_response') return response class m2(MiddlewareMixin): def process_request(self, request): print('m2.process_request') def process_response(self, request, response): print('m2.process_response') return response
m1.process_request
m2.process_request
in views
m2.process_response
m1.process_response
from django.utils.deprecation import MiddlewareMixin class m1(MiddlewareMixin): def process_request(self, request): print('m1.process_request') def process_response(self, request, response): print('m1.process_response') return response def process_view(self,request,callback,callback_args,callback_kwargs): response = callback(request) print('m1.process_view') return response class m2(MiddlewareMixin): def process_request(self, request): print('m2.process_request') def process_response(self, request, response): print('m2.process_response') return response def process_view(self,request,callback,callback_args,callback_kwargs): response = callback(request) print('m2.process_view')
m1.process_request
m2.process_request
in views
m1.process_view
process_view函数如果有返回值,则后面的process_view 函数就不会执行,也不会再进入视图函数了,而是直接 到中间件的 process_response函数开始往回执行。这其实也就意味着提前在中间件中执行视图函数并返回response
m2.process_response
m1.process_response
以上是django中间件(类)函数的执行顺序。
1.当只有process_request和process_response函数时,先执行完全部中间件的process_request函数,然后进入视图函数,
再往回执行全部中间件的process_response函数。
注意:process_request函数不可以有return值。
2.当中间件中除了以上两个函数之外,还有process_view函数(其它的待后续补充)时,会在执行完process_request函数后再从头开始执行全部的
process_view函数,如果process_view函数没有返回值,则按顺序执行,并且会进入到视图函数。如果有返回值,则执行完此个函数后不再执行后面的函数,
直接跳到process_response函数,不进入视图函数。
增加另外两个函数:
1. process_exception 视图函数存在异常时才会在执行完视图函数后执行,而且如果异常在某一个中间件已经被处理了,那么后面中间件的该函数就不再执行了。
def process_exception(self,request,exception): print('m1.process_exception') print(exception) #输入异常的信息
2.process_template_response 只有当视图函数返回的对象包含render函数时,才会执行
def process_template_response(self,request,response): print('m1.process_template_response') return response
#视图函数
class Foo:
def __init__(self,request):
self.request = request
def render(self):
return HttpResponse('this is render')
def test(request):
print('in views')
obj = Foo(request)
return obj
(有点绕,但还是容易记)