DRF频率使用

一、频率简介:

  限制用户一段时间内的访问次数

二、怎么使用

  • 配置setting.py文件:

  

  • 新建一个mythrottle.py 文件,在文件中新建一个频率类,继承SimpleRateThrottle
  • 重写get_cache_key, 返回self.get_ident(request),
  • 记住scope是一个字符串
class Throttle(SimpleRateThrottle):
    scope = 'lxx'
    def get_cache_key(self, request, view):
        # return request.META.get('REMOTE_ADDR')
        #返回什么值,就以什么做过滤,返回用户id,就以用户id做过滤
        return self.get_ident(request)
  • 视图层
class Books(APIView):
 
    throttle_classes=[MyThrottle,]
    def get(self,request):
        return Response('')

三、如何自定义一个频率认证函数

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

    def allow_request(self, request, view):
        # 先取出访问者的IP
        ip = request.META.get('REMOTE_ADDR')
        import time
        # 拿到访问时间
        ctime = time.time()
        # 判断当前的IP是否在字典里,添加进去,并且直接返回True表示第一次访问
        if ip not in self.VISIT_RECORD:
            self.VISIT_RECORD[ip] = [ctime, ]
            return True
        # 获取当前时间的列表[第一次访问时间,]
        self.history = self.VISIT_RECORD.get(ip)
        # 循环判断当前的IP的列表,有值,并且当前时间减去列表的最后一个时间,如果大于60s就pop掉,这样列表里面都是60s内的时间
        while self.history and ctime - self.history[-1] > 60:
            self.history.pop()
        # 如果访问次数小于3 ,插入最新一次的访问时间
        if len(self.history) < 3:
            self.history.insert(0, ctime)
            return True
        return False


    def wait(self):
        import time
        ctime = time.time()
        return 60-(ctime-self.history)
原文地址:https://www.cnblogs.com/king-home/p/11138469.html