首页 > 其他 > 详细

django-中间件

时间:2021-09-06 02:30:58      阅读:23      评论:0      收藏:0      [点我收藏+]

中间件

中间件的定义

  • 请求响应
  • 全局改变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---

django-中间件

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!