1.在app目录下的middleware.py里面增加中间件类
from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin
# 中间件类
class BlockedIPSMiddleware(MiddlewareMixin):
EXCLUDE_IPS = ['127.0.0.1']
# 中间件函数
def process_view(self, request, view_func, *view_args, **view_kwargs):
'''视图函数调用之前调用这个'''
userIp = request.META['REMOTE_ADDR']
print(userIp)
# 禁止某些IP访问
if userIp in BlockedIPSMiddleware.EXCLUDE_IPS:
return HttpResponse("Forbidden
")
class TestMiddleware(MiddlewareMixin):
def __init__(self,get_response=None):
self.get_response = get_response
print("init")
def process_request(self,request):
'''产生request对象之后,url匹配之前调用'''
print('process_request')
def process_view(self,request,view_func,*view_args,**view_kwargs):
'''url匹配之后,视图函数调用之前'''
print("process_view")
def process_response(self,request,response):
'''调用视图函数之后,内容返回之前'''
print('process_response')
return response
class ExceptionTestMiddleware(MiddlewareMixin):
def process_exception(self,request,exception):
'''视图函数发生异常时调用'''
print('process_exception1')
class ExceptionTest2Middleware(MiddlewareMixin):
def process_exception(self, request, exception):
'''视图函数发生异常时调用'''
print('process_exception2')
2.注销掉BlockedIPSMiddleware,添加注册新的中间件
# 'booktest.middleware.BlockedIPSMiddleware',#注册中间件类
'booktest.middleware.TestMiddleware',#注册中间件类
'booktest.middleware.ExceptionTestMiddleware',#注册中间件类
'booktest.middleware.ExceptionTest2Middleware',#注册中间件类
3.访问http://127.0.0.1:8000/test_middleware两次,显示信息如下,init只在启动服务器后第一次访问时会执行
4.修改中间件方法process_request,返回HttpResponse,则会产生熔断,显示的信息如下
def process_request(self,request):
'''产生request对象之后,url匹配之前调用'''
print('process_request')
return HttpResponse('process_request')
5.在test_middleware视图函数中增加下面的代码,测试错误
num='a'+1