DRF之频率组件

几种drf的频率组件使用总结

一 

 - 定义一个频率类

class RateThrottle():
    def allow_request(request, self):
        if 没有超过限制(伪代码):
            return True
        else:
            return False
    def wait(self): # 必写
        return 10

- 指定频率类

class BookView(APIView):
    throttle_classes = [RateThrottle]

二  控制用户访问频率 (局部)

 - 导入

from rest_framework.thortting import SimpleRateThrottle

 - 定义并继承simpleRateThrottle

class RateThrottle(SimpleRateThrottle):
    # 指定访问频率
    rate = '5/m'
                    
    # 指定通过什么方式来区分用户
    def get_cache_key(self, request, view):
        return self.get_ident(request)

 - 同样要指定频率类

class BookView(APIView):
    throttle_classes = [RateThrottle]

三  控制用户访问频率(全局)

- 继承类

class RateThrottle(SimpleRateThrottle):
    # 指定访问频率
    scope = 'visit_rate'
                    
    # 指定通过什么方式来区分用户
    def get_cache_key(self, request, view):
        return self.get_ident(request)

- 在settings里面指定频率类和访问频率

- 在settings里面指定频率类和访问频率
                REST_FRAMEWORK = {
                    "DEFAULT_THROTTLE_CLASSES": ('serializer.utils.app_throttles.RateThrottle',), # 路径
                    "DEFAULT_THROTTLE_RATES": {
                        "visit_rate": "5/m"  # 对应继承类
                    }
                }

猜你喜欢

转载自www.cnblogs.com/lzmdbk/p/10103028.html