"""
# 在请求到来时执行,如果有response则立即返回结果,不继续执行。没有则先执行完所有的process_request()
1.process_request(self,request)
# 进入视图之前执行的操作,如果有response则立即返回结果,不继续执行。没有则先执行完所有的process_view()
2.process_view(self, request, callback, callback_args, callback_kwargs)
# 返回值中有render()方法就执行,没有则不执行
# views 业务逻辑处理(视图函数)
3.process_template_response(self,request,response)
# 执行过程中出现异常则进行异常处理,没有则不执行
4.process_exception(self, request, exception)
# 响应相关,不管上面4步从哪一步返回,都会携带对应的process_response()给用户
5.process_response(self, request, response)
"""
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse
class M1(MiddlewareMixin):
def process_request(self,request):
"""
根据settings列表的配置,决定执行顺序
:param request:
:return:
"""
print('m1.process_request')
def process_view(self, request, callback, callback_args, callback_kwargs):
"""
如果视图出现批量需要处理的业务,则可以进行分压、分逻辑处理
:param request:
:param callback:
:param callback_args:
:param callback_kwargs:
:return:
"""
print('m1.process_view')
# response = callback(request,*callback_args,**callback_kwargs)
# return response
def process_response(self,request,response):
"""
不管是何执行结果,都会返回相应的HttpResonse对象
:param request:
:param response:
:return:
"""
print('m1.process_response')
return response
def process_exception(self, request, exception):
"""
出现异常才会被调用进行异常处理
:param request:
:param exception:
:return:
"""
print('m1.process_exception')
def process_template_response(self,request,response):
"""
视图函数的返回值中,如果有render方法,才被调用
:param request:
:param response:
:return:
"""
print('m1.process_template_response')
return response
class M2(MiddlewareMixin):
"""
在此处可以包含多个中间件的处理方法
"""
def process_request(self,request):
print('m2.process_request')
def process_view(self, request, callback, callback_args, callback_kwargs):
print('m2.process_view')
def process_response(self,request,response):
print('m2.process_response')
return response
def process_exception(self, request, exception):
print('m2.process_exception')
return HttpResponse('错误了...')