自定义频率类

自定义频率组件

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',)
}
原文地址:https://www.cnblogs.com/guanxiying/p/13283978.html