zoukankan      html  css  js  c++  java
  • Django中间件限制用户访问频率

    原:https://blog.csdn.net/weixin_38748717/article/details/79095399

    一、定义限制访问频率的中间件

    • common/middleware.py
    import time
    
    from django.utils.deprecation import MiddlewareMixin
    
    MAX_REQUEST_PER_SECOND=2 #每秒访问次数
    
    class RequestBlockingMiddleware(MiddlewareMixin):
    
        def process_request(self,request):
            now=time.time()
            request_queue = request.session.get('request_queue',[])
            if len(request_queue) < MAX_REQUEST_PER_SECOND:
                request_queue.append(now)
                request.session['request_queue']=request_queue
            else:
                time0=request_queue[0]
                if (now-time0)<1:
                    time.sleep(5)
    
                request_queue.append(time.time())
                request.session['request_queue']=request_queue[1:]

    二、将中间件加入配置文件

    • setting.py
    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'common.middleware.RequestBlockingMiddleware', #在sessions之后,auth之前
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ]
  • 相关阅读:
    MongoDB Shell
    mongo 日记
    java 堆栈 静态
    面向对象(2)
    面向对象(1)
    mongo 学习笔记
    深入浅出学Spring Data JPA
    java记录
    mongodb 2.6 window 安装启动服务
    CF1012F Passports
  • 原文地址:https://www.cnblogs.com/guoyunlong666/p/9612970.html
Copyright © 2011-2022 走看看