目录
一、介绍
二、自定义中间件
一、介绍
django的中间件(middleware),在django中,中间件其实就是一个类,在请求到来和结束后,django会根据自己的规则在合适的时机执行中间件中相应的方法。
在django项目的settings模块中,有一个MIDDLEWARE_CLASSES变量,其中每一个元素就是一个中间件
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‘, ‘wupeiqi.middleware.auth.Authentication‘, ]
与manage.py在一个目录下的文件夹wupeiqi/middleware下的auth.py文件中的Authentication类
中间件中可以定义四个方法,分别是:
process_request(self,request) process_view(self,request,callback,callback_args,callback_kwargs) process_template_response(self,reuqest,response) process_exception(self,request,exception) process_response(self,request,response)
以上的方法的房绘制可以是None和HttpResonse对象,如果是None,则继续按照django定义的规则向下执行,如果是HttpResonse对象,则直接将该对象返回给用户
二、自定义中间件
1.创建中间件
#!/usr/bin/env python # _*_ coding:utf-8 _*_ # Author: JiaChen from django.utils.deprecation import MiddlewareMixin from django.shortcuts import HttpResponse class Row1(MiddlewareMixin): def process_request(self, request): print("王森") def process_view(self, request, view_func, view_func_args, view_func_kwargs): print("张欣彤") def process_response(self, request, response): print("张扬") return response class Row2(MiddlewareMixin): def process_request(self, request): print("程义强") def process_view(self, request, view_func, view_func_args, view_func_kwargs): print("张旭耀") def process_response(self, request, response): print("侯亚凡") return response class Row3(MiddlewareMixin): def process_request(self, request): print("刘东") def process_view(self, request, view_func, view_func_args, view_func_kwargs): print("邵林") def process_response(self, request, response): print("廉志雷") return response def process_exception(self, request, exception): if isinstance(exception, ValueError): return HttpResponse("出现异常了...") def process_template_response(self, request, response): # 如果Views中的函数返回的对象中,具有render方法 print("-----------------") return response
2.注册中间件
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.m1.Row1‘, ‘Middle.m1.Row2‘, ‘Middle.m1.Row3‘, ]
时间: 2024-10-15 17:50:56