django中间件
请求到达views之前,会通过settings.py配置中的中间件,中间件通过后才会到达views函数
中间件中可以定义四个方法,分别是:
- process_request(self,request)
- process_view(self, request, callback, callback_args, callback_kwargs)
- process_template_response(self,request,response)
- process_exception(self, request, exception) views函数出现异常时实行
- process_response(self, request, response)
以上方法的返回值可以是None和HttpResonse对象,如果是None,则继续按照django定义的规则向下执行,如果是HttpResonse对象,则直接将该对象返回给用户。
自定义中间件,可以做一下请求到达业务函数之前的数据处理,向一些公共校验,黑名单过滤等等操作
# !/usr/bin/env python # -*- coding: utf-8 -*- from django.utils.deprecation import MiddlewareMixin from django.shortcuts import HttpResponse __author__ = 'lidian' class Row1(MiddlewareMixin): def process_request(self,request): print("row1") def process_view(self, request, view_func, view_func_args, view_func_kwargs): #在请求到达路由匹配后,再折回来执行process_view print("row1的peocess_view") def process_response(self,request,response): print("row1返回") return response class Row2(MiddlewareMixin): def process_request(self,request): print("row2") # return HttpResponse("不行,回去吧") def process_view(self, request, view_func, view_func_args, view_func_kwargs): # 在请求到达路由匹配后,再折回来执行process_view print("row2的peocess_view") def process_response(self, request, response): print("row2返回") return response class Row3(MiddlewareMixin): def process_request(self,request): print("row3") def process_view(self, request, view_func, view_func_args, view_func_kwargs): # 在请求到达路由匹配后,再折回来执行process_view print("row3的peocess_view") def process_response(self, request, response): print("row3返回") return response def process_exception(self, request, exception): if isinstance(exception,ValueError): print("views函数出现异常时执行") return HttpResponse("出错") def process_template_response(self, request, response): #默认情况下不执行 #如果views函数的方法返回对象中,具有render方法,则这个方法会执行 print("--------------") return response