zoukankan      html  css  js  c++  java
  • 中间件:一个用户1分钟访问不能超过3次


    #导入模块
    from django.utils.deprecation import MiddlewareMixin

    # 定义一个 访问记录的大字典
    VISIT_RECORD = {}
     
    # 自定义一个访问频率限制的中间件
    class Throttle(MiddlewareMixin):
     
        def process_request(self, request):
            # 1. 拿到用户请求的IP
            # print(request.META)
            ip = request.META.get("REMOTE_ADDR")
            
            # 2. 当前请求的时间
            now = time.time()
            
            # 3. 记录访问的历史
            if ip not in VISIT_RECORD:
                VISIT_RECORD[ip] = []
     
            history = VISIT_RECORD[ip]
            # [11:07:20, 10:07:11, 10:07:06, 10:07:01]
     
            #当本次访问与之前的访问超过60s,则清除之前的访问记录
            while history and now - history[-1] > 10:
                history.pop()
           
             # 判断用户在一分钟的时间间隔内是否访问超过3次
            if len(history) >= 3:
                return HttpResponse("访问过于频繁...")
            
      #把新的访问记录添加在列表的第一个
            history.insert(0, now)
  • 相关阅读:
    python中使用到lxml模块时,py2exe打包方法
    python random
    pip install lxml出错解决
    Windows上Python2和3如何兼容
    python 2.4 与 python 3.0 的比较
    java综合(三)springmvc与spring上下文关系
    java综合(二)springmvc与spring整合
    PHP7 新增加的两种运算符
    PHP trait 特性
    PHP 字符串拆分函数
  • 原文地址:https://www.cnblogs.com/nzd123456/p/9459537.html
Copyright © 2011-2022 走看看