zoukankan      html  css  js  c++  java
  • django-中间件

    中间件

    中间件的定义

    • 请求响应
    • 全局改变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---
    
  • 相关阅读:
    PHP 原型模式
    PHP 观察者模式
    PHP 策略模式
    PHP 适配器模式
    PHP static静态属性和静态方法
    PHP中this,self,parent三个关键字
    PHP 单例模式
    git修改账号密码-命令行
    微信开发SDK推荐
    Java并发编程:线程池的使用
  • 原文地址:https://www.cnblogs.com/yescarf/p/15217319.html
Copyright © 2011-2022 走看看