1.django中间件的5个方法
process_request(self,request)
process_view(self, request, callback, callback_args, callback_kwargs) process_template_response(self,request,response) process_exception(self, request, exception) process_response(self, request, response)以上方法的返回值可以是HttpResponse对象和None值,如果是None则按照规则继续执行,如果为HttpResponse对象则直接将对象返回
2.django中间件的执行流程
(1)首先执行process_request函数,中间如果出现异常,则跳转到当前中间件的response函数中执行并返回。
(2)如果process_request执行结束,则会执行process_view函数,view的功能是与处理函数view执行了一次路由映射 (3)通过response返回给客户端 (4)process_exception是进行异常捕捉,如果视图函数view中运行错误,则调用此函数进行捕捉 (5)运行视图函数时,会进行异常捕捉,没有捕捉到异常则报错,捕捉到异常则会进行跳转最底层的response中返回 (6)process_template_response(self,request,response)->了解一下即可3.自定义中间件
创建目录Middle,创建middleware.py文件from django.utils.deprecation import MiddlewareMininclass row1(MiddlewareMinin): def process_request(self,request): print("request-1") def process_response(self,request,response): print("response-1)" return response def process_view(self, request, callback, callback_args, callback_kwargs): print("view-1") class row2(MiddlewareMinin): def process_request(self,request): print("request-2") def process_response(self,request,response): print("response-2)" return response def process_view(self, request, callback, callback_args, callback_kwargs): print("view-2")class row3(MiddlewareMinin): def process_request(self,request): print("request-3") def process_response(self,request,response): print("response-3)" return response def process_view(self, request, callback, callback_args, callback_kwargs): print("view-3")
4.中间件注册
MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'Middle.middleware.Row1',#自定义中间的注册 'Middle.middleware.Row2', 'Middle.middleware.Row3',]
注意,中间件的执行顺序按照配置自上向下