赞
踩
中间件是全局使用
middleware.py
- # 工厂函数的中间件
- def simple_middleware(get_response):
- def middleware(request):
- print("在视图函数处理之前执行、、、、、")
- response = get_response(request)
- print("在视图函数处理之后执行。。。。。")
- return response
- return middleware
setings.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',
- 'the_15.middleware.simple_middleware',
- ]
- # 类定义中间件
- from django.utils.deprecation import MiddlewareMixin
-
-
- class Mwi(MiddlewareMixin):
- def process_request(self, request):
- """
- 如果没有返回值或者返回值为 None 就会继续执行视图函数
- 如果有返回值就不会执行视图函数中的内容,直接返回值,
- """
- print("process_request 在视图函数之前执行、、、、、")
- pass
-
- def process_View(self, request, view_func, view_args, view_kwargs):
- print('process_View 正在执行中')
- pass
-
- def process_response(self, request, response):
- """
- 一定要有返回值
- """
- print("process_response 在视图函数之后执行、、、、、")
- return response
setings.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',
- # 'the_15.middleware.simple_middleware',
- 'the_15.middleware.Mwi',
- ]
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。