当前位置 博文首页 > 文章内容

    自定义频率类

    作者: 栏目:未分类 时间:2020-07-11 16:01:21

    本站于2023年9月4日。收到“大连君*****咨询有限公司”通知
    说我们IIS7站长博客,有一篇博文用了他们的图片。
    要求我们给他们一张图片6000元。要不然法院告我们

    为避免不必要的麻烦,IIS7站长博客,全站内容图片下架、并积极应诉
    博文内容全部不再显示,请需要相关资讯的站长朋友到必应搜索。谢谢!

    另祝:版权碰瓷诈骗团伙,早日弃暗投明。

    相关新闻:借版权之名、行诈骗之实,周某因犯诈骗罪被判处有期徒刑十一年六个月

    叹!百花齐放的时代,渐行渐远!



    自定义频率组件

    from rest_framework.throttling import BaseThrottle
    class MyThrottles(BaseThrottle):
        # 由ip跟时间列表组成的字典
        VISIT_RECORD = {}
    
        def __init__(self):
            # 用来记录已经访问过的ip的时间列表
            self.history = None
    
        # 重写allow_request方法
        def allow_request(self, request, view):
            # 获取ip
            ip = request.META.get('REMOTE_ADDR')
            print(ip)
            # 获取当前时间作为ip第一次访问时间
            ctime = time.time()
            # ip不在字典中就添加,并返回通过
            if ip not in self.VISIT_RECORD:
                self.VISIT_RECORD[ip] = [ctime, ]
                return True
            # 获取ip对应的时间列表赋值给history
            self.history = self.VISIT_RECORD.get(ip)
            # 循环时间列表,将列表中时间大于1分钟的全部剔除,保证self.history中的访问时间是1分钟内的
            while self.history and ctime - self.history[-1] > 60:
                self.history.pop()
            # 判断时间列表的长度,限制同一个ip1分钟内的访问次数
            if len(self.history) < 5:
                self.history.insert(0, ctime)
                return True
            return False
    
        # ip被限制后的等待时间
        def wait(self):
            nonw_time = time.time()
            wait_time = 60 - (nonw_time - self.history[-1])
            return wait_time
    

    自定义频率组件使用

    局部使用

    # 在视图类中设置
    throttle_classes = [MyThrottles, ]
    

    全局使用

    # 在settings.py文件中设置如下代码,可以设置多个
    REST_FRAMEWORK = {
          'DEFAULT_THROTTLE_CLASSES': ('work.user_auth.MyThrottles',)
    }