rest_framework学习(七)频率组件

 频率组件

频率组件是为了控制用户访问的频率、节流。

rest_framework运行的权限组件的时间和认证组件相同,在rest_framework学习(四)认证组件已经提到了,不再赘述。

当执行了self.check_throttles(request)方法,即执行该视图函数所有的权限组件

    def check_throttles(self, request):
        """
        Check if request should be throttled.
        Raises an appropriate exception if the request is throttled.
        """
        for throttle in self.get_throttles():
            if not throttle.allow_request(request, self):
                self.throttled(request, throttle.wait())

常用的rest_framework自带的频率组件

  • AnonRateThrottle
  • UserRateThrottle
  • ScopedRateThrottle

自定义频率组件

实现自定义权限组件必须要继承rest_framework.throttling.BaseThrottle

class MyThrottle():
    visitor_dic = {}

    def __init__(self):
        self.history = None

    def allow_request(self, request, view):
        '''
            {'ip1':[时间1 ,时间2],
            'ip2':[时间1, ],
            }
           #(1)取出访问者ip
            # (2)判断当前ip不在访问字典里,添加进去,并且直接返回True,表示第一次访问,在字典里,继续往下走
            # (3)循环判断当前ip的列表,有值,并且当前时间减去列表的最后一个时间大于60s,把这种数据pop掉,这样列表中只有60s以内的访问时间,
            # (4)判断,当列表小于3,说明一分钟以内访问不足三次,把当前时间插入到列表第一个位置,返回True,顺利通过
            # (5)当大于等于3,说明一分钟内访问超过三次,返回False验证失败
        '''

        # Meta:请求所有的东西的字典
        # 拿出ip地址
        ip = request.META.get('REMOTE_ADDR')
        # 不在字典中,说明是第一次访问
        ctime = time.time()
        if ip not in self.visitor_dic:
            self.visitor_dic[ip] = [ctime, ]
            return True
        # 根据当前访问者ip,取出访问的时间列表
        history = self.visitor_dic[ip]
        self.history = history
        while history and ctime - history[-1] > 60:
            history.pop()

        if len(history) < 3:
            # 把当前时间放到第0个位置上
            history.insert(0, ctime)
            return True

        return False

    def wait(self):
        # 剩余时间
        ctime = time.time()
        return 60 - (ctime - self.history[-1])

局部使用:
    -在视图类中写
    throttle_classes = [MyThrottle,]
全局使用:
    -在setting中写
    'DEFAULT_THROTTLE_CLASSES':['app01.MyAuth.MyThrottle',],

-局部禁用:
    -在视图类中写
    throttle_classes = []

posted @ 2019-07-31 18:18  Wuliwawa  阅读(114)  评论(0编辑  收藏  举报