什么是中间件?中间件应用场景?和装饰器区别?
中间件
对于所有批量的请求用中间件合适,而对于某些请求个数少用装饰器合适
- 中间件是什么?
- 是一个类
- 方法名必须是process_request/process_response,否则无效
- 返回值注意:
# 无返回值:继续执行后续中间件和视图函数
# 有返回值:执行自己的process_response和上面的response
- 做过什么:
- 用户登录验证 - csrf
- session
- 权限管理***
----------------------------------------------
asd.a.py
from django.conf import settings
from django.shortcuts import redirect
class MiddlewareMixin(object):
def __init__(self, get_response=None):
self.get_response = get_response
super(MiddlewareMixin, self).__init__()
def __call__(self, request):
response = None
if hasattr(self, 'process_request'):
response = self.process_request(request)
if not response:
response = self.get_response(request)
if hasattr(self, 'process_response'):
response = self.process_response(request, response)
return response
class M1(MiddlewareMixin):
def process_request(self,request):
# 无返回值:继续执行后续中间件和视图函数
# 有返回值:执行自己的process_response和上面的response
# request.xxxx= 888
# request.path_info # /login/
if request.path_info == "/login/":
# if request.path == "/login/":
print(request.path)
return None
user_info = request.session.get(settings.SESS)
if not user_info:
return redirect('/login/')
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
--------------------------------------------------
settings.py
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',
'asd.a.M1',
'asd.a.M2',
]
注意:必须在最后面加自定义的中间件