中间件顾名思义,是介于request与response处理之间的一道处理过程,相对比较轻量级,并且在全局上改变django的输入与输出。因为改变的是全局,所以需要谨慎实用,用不好会影响到性能。
如果你想修改请求,例如被传送到view中的HttpRequest对象。 或者你想修改view返回的HttpResponse对象,这些都可以通过中间件来实现。
可能你还想在view执行之前做一些操作,这种情况就可以用 middleware来实现。
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', ]
中间件中一共有四个方法:
process_request
process_view
process_exception
process_response
process_request和process_response
my_middlewares.py
from django.utils.deprecation import MiddlewareMixin from django.shortcuts import HttpResponse class CustomerMiddleware(MiddlewareMixin): def process_request(self, request): print('CustomerMiddleware1 process_request.... ') # 只要一发送http请求就会执行这句话 # return HttpResponse('forbidden') # # 如果给request加返回值,那它会直接把返回值交给自己的response返回给浏览器,就不让往下走了,所以request不能有返回值 def process_response(self, request, response): print('CustomerMiddleware1 process_response') # return 'hello edward' # 不要瞎换返回值,这样会把自己打的返回值返回给浏览器,而得不到想要的结果 return response # 必须要有返回值,因为它要一层层往回传 class CustomerMiddleware2(MiddlewareMixin): def process_request(self, request): print('CustomerMiddleware2 process_request2.... ') def process_response(self, request, response): print('CustomerMiddleware2 process_response2') return response # 必须要有返回值,因为它要一层层往回传
views.py
def index(request): print('index') # 先执行中间件 return HttpResponse('index')
结果
CustomerMiddleware1 process_request....
CustomerMiddleware2 process_request2....
index
CustomerMiddleware2 process_response2
CustomerMiddleware1 process_response
process_view
Mymiddlewares.py修改如下
from django.utils.deprecation import MiddlewareMixin from django.shortcuts import HttpResponse class CustomerMiddleware(MiddlewareMixin): def process_request(self, request): print('CustomerMiddleware1 process_request.... ') # 只要一发送http请求就会执行这句话 # return HttpResponse('forbidden') # # 如果给request加返回值,那它会直接把返回值交给自己的response返回给浏览器,就不让往下走了,所以request不能有返回值 def process_response(self, request, response): print('CustomerMiddleware1 process_response') # return 'hello edward' # 不要瞎换返回值,这样会把自己打的返回值返回给浏览器,而得不到想要的结果 return response # 必须要有返回值,因为它要一层层往回传 def process_view(self, request, callback, callback_args, callback_kwargs): print("CustomerMiddleware1 process_view1") class CustomerMiddleware2(MiddlewareMixin): def process_request(self, request): print('CustomerMiddleware2 process_request2.... ') def process_response(self, request, response): print('CustomerMiddleware2 process_response2') return response # 必须要有返回值,因为它要一层层往回传 def process_view(self, request, callback, callback_args, callback_kwargs): # print('=======>', callback(callback_args)) # callback就是视图函数 <HttpResponse status_code=200, "text/html; charset=utf-8"> print("CustomerMiddleware2 process_view2") # ret = callback(callback_args) # 等于response还没返回给浏览器呢,就执行了视图里的index函数 # return ret
结果如下
CustomerMiddleware1 process_request....
CustomerMiddleware2 process_request2....
CustomerMiddleware1 process_view1
CustomerMiddleware2 process_view2
index
CustomerMiddleware2 process_response2
CustomerMiddleware1 process_response
流程图
注意:process_view如果有返回值,会越过其他的process_view以及视图函数,但是所有的process_response都还会执行。
实例:用process_view计算函数执行时间
import time from django.utils.deprecation import MiddlewareMixin from django.urls import reverse class CustomerMiddleware(MiddlewareMixin): def process_view(self, request, func, *args, **kwargs): if request.path != reverse('index'): return None start = time.time() response = func(request) costed_time = time.time() - start print('process view:{:.2f}s'.format(costed_time)) return response
注意:如果返回None,Django会帮你执行view函数,从而得到最终的response
from django.utils.deprecation import MiddlewareMixin from django.shortcuts import HttpResponse class CustomerMiddleware(MiddlewareMixin): def process_request(self, request): print('CustomerMiddleware1 process_request.... ') # 只要一发送http请求就会执行这句话 # return HttpResponse('forbidden') # # 如果给request加返回值,那它会直接把返回值交给自己的response返回给浏览器,就不让往下走了,所以request不能有返回值 def process_response(self, request, response): print('CustomerMiddleware1 process_response') # return 'hello edward' # 不要瞎换返回值,这样会把自己打的返回值返回给浏览器,而得不到想要的结果 return response # 必须要有返回值,因为它要一层层往回传 def process_view(self, request, callback, callback_args, callback_kwargs): print("CustomerMiddleware1 process_view1") def process_exception(self, request, exception): print('CustomerMiddleware1 process_exception1') return HttpResponse(exception) # 2没有返回值,就找1 class CustomerMiddleware2(MiddlewareMixin): def process_request(self, request): print('CustomerMiddleware2 process_request2.... ') def process_response(self, request, response): print('CustomerMiddleware2 process_response2') return response # 必须要有返回值,因为它要一层层往回传 def process_view(self, request, callback, callback_args, callback_kwargs): # print('=======>', callback(callback_args)) # callback就是视图函数 <HttpResponse status_code=200, "text/html; charset=utf-8"> print("CustomerMiddleware2 process_view2") # ret = callback(callback_args) # 等于response还没返回给浏览器呢,就执行了视图里的index函数 # return ret def process_exception(self, request, exception): print('CustomerMiddleware2 process_exception2') # return HttpResponse(exception) # exception参数是错误信息,浏览器只显示错误信息,没有其他乱七八糟的东西
当views出现错误时:
中间件的应用
如果视图函数有很多,而且很多都需要加上login认证的话,那么用装饰器也很麻烦,这时候就可以用中间件来解决,还用auth模块的这个demo来演示
my_middlewares
from django.utils.deprecation import MiddlewareMixin from django.shortcuts import HttpResponse, redirect from auth_demo import settings class AuthMiddleware(MiddlewareMixin): def process_request(self, request): white_list = settings.WHITE_LIST # 白名单 if request.path in white_list: return None else: if not request.user.is_authenticated: return redirect('/login/')
settings.py
WHITE_LIST = ['/login/', '/reg/', '/logout/']
views.py
def index(request): return render(request, 'index.html')
注意:中间件是双刃剑,要谨慎使用,因为它是全局变量,不合理的使用会降低效率。如果20个需要校验,80个不需要校验,这时候就不应该使用中间件。