django-中间件

时间:2021-09-06 02:30:58   收藏:0   阅读:12

中间件

中间件的定义

中间件理解

技术分享图片

编写

返回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---

原文:https://www.cnblogs.com/yescarf/p/15217319.html

评论(0)
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!