标签:path callback 用户 turn 步骤 不同 inf 中间键 执行流程
process_request
process_view
process_template_response
process_response
process_exception
中间件执行流程示意图
1、在项目目录下创建文件夹utils
, 内部创建my_middleware.py
文件,文件名称和类名称自定义;
from django.utils.deprecation import MiddlewareMixin
class Md1(MiddlewareMixin):
def process_request(self, reqeust):
print('md1_process_request')
def process_response(self, requst, response):
print('md1_process_response')
return response # 必须带返回值
def process_view(self, request, callback, callback_args, callback_kwargs):
print("中间件1view")
class Md2(MiddlewareMixin):
def process_request(self, request):
print('md2_process_request')
def process_response(self, request, response):
print('md2_process_response')
return response # 必须带返回值
def process_view(self, request, callback, callback_args, callback_kwargs):
print("中间件2view")
2、在配置文件中加入加上的中间件:
MIDDLEWARE = [
'utils.my_middleware.Md1',
'utils.my_middleware.Md2',
]
3、此时django所有的请求和相应都会依次经过process_request()
和process_response
函数.
md1_process_request
md2_process_request
md2_process_response
md1_process_response
return None
return
from django.shortcuts import HttpResponse
from django.utils.deprecation import MiddlewareMixin
class Md1(MiddlewareMixin):
def process_request(self, request):
print('md1_process_request')
return HttpResponse('<h1>你好</h1>')
# 打印结果
md1_process_request
md1_process_response
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
# my_middleware.py
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import render
class Md1(MiddlewareMixin):
def process_request(self, request):
print('md1_process_request')
# 若本次请求是login页面, 则当前中间件不做任何操作
if request.path == '/login.html':
return None
# 若未取不到对应的信息,则跳转至登录页面,此处直接render
if not request.session.get('user_info'):
return render(request, 'login.html')
def process_response(self, request, response):
print('md1_process_response')
return response # 必须带返回值
process_view
方法process_view
函数默认return None
process_view
都不会执行,直接跳转到尾部执行process_response
, 返回值为process_view
的返回值标签:path callback 用户 turn 步骤 不同 inf 中间键 执行流程
原文地址:https://www.cnblogs.com/fqh202/p/9448048.html