七、频率控制


返回

7.1 定义频率控制类

  • utils/throttle.py:定义频率控制类的allow_requestwait方法

    from rest_framework.throttling import BaseThrottle
    import time
    
    VISIT_RECORD = {}
    
    
    class MyThrottle(BaseThrottle):
    
        def __init__(self):
            self.history = None
    
        def allow_request(self, request, view):
            """
            示例:以IP限流
            访问列表 {IP: [time1, time2, time3]}
            """
            # 1 获取请求的IP地址
            ip = request.META.get("REMOTE_ADDR")
            # 2 判断IP地址是否在访问列表
            now = time.time()
            if ip not in VISIT_RECORD:
                VISIT_RECORD[ip] = [now, ]
                return True
            history = VISIT_RECORD[ip]
            history.insert(0, now)
            # 3 确保列表里最新访问时间以及最老的访问时间差 是1分钟
            while history and history[0] - history[-1] > 60:
                history.pop()
            self.history = history
            # 4 得到列表长度,判断是否是允许的次数
            if len(history) > 3:
                return False
            else:
                return True
    
        def wait(self):
            """ 需要等待时间 """
            time = 60 - (self.history[0] - self.history[-1])
            return time
    
    

7.2 应用局部频率控制

  • views.py

    from rest_framework.views import APIView
    from utils.auth import MyAuth
    from utils.permission import MyPermission
    
    
    class TestView(APIView):
        authentication_classes = [MyAuth, ]  # 局部认证
        permission_classes = [MyPermission, ]  # 局部权限
        throttle_classes = [MyThrottle, ]  # 频率控制
    
        def get(self, request):
            pass
       
    

7.3 利用框架

  • 提供了四种频率控制类

    from rest_framework.throttling import AnonRateThrottle
    from rest_framework.throttling import UserRateThrottle
    from rest_framework.throttling import ScopedRateThrottle
    from rest_framework.throttling import SimpleRateThrottle
    
返回