中间件
中间件的定义
- 请求响应
- 全局改变django的输入输出(request,response)
中间件理解
编写
返回None与HttpResponse
应用
注册中间件
class VisitLimit(MiddlewareMixin):
visittime={}
#类变量在内存中当需要重新访问时需要重启runserver
def process_request(self,request):
ip=request.META["REMOTE_ADDR"]
path_url=request.path_info
if not re.match("^/test",path_url):
return
times=self.visittime.get(ip,0)
print("ip",ip,‘已访问‘,times)
self.visittime[ip]=times+1
if times<5:
return
return HttpResponse("您已经访问过"+str(times)+‘次‘+‘被禁止访问‘)
后台显示
Django version 2.2.12, using settings ‘mymiddleware.se
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
ip 127.0.0.1 已访问 0
test-----my view in---
[05/Sep/2021 14:25:45] "GET /test_mw HTTP/1.1" 200 2
ip 127.0.0.1 已访问 1
test-----my view in---
[05/Sep/2021 14:25:50] "GET /test_mw HTTP/1.1" 200 2
ip 127.0.0.1 已访问 2
test-----my view in---
[05/Sep/2021 14:25:53] "GET /test_mw HTTP/1.1" 200 2
ip 127.0.0.1 已访问 3
test-----my view in---
[05/Sep/2021 14:25:54] "GET /test_mw HTTP/1.1" 200 2
ip 127.0.0.1 已访问 4
test-----my view in---