DRF:源码剖析 - 频率组件

局部限制访问频率 (SimpleRateThrottle)

一、定义频率类

做接耦,在utils包中定义该类

# app / utils / app_throttles.py

from rest_framework.throttling import SimpleRateThrottle

class RateThrottle(SimpleRateThrottle):     # 类名可以自定义

    rate = "5/m"       # 限制每分钟最多访问5次,指定用户访问的频率

    def get_cache_key(self, request, view):     # 方法名是固定的,指定通过什么方式来区分用户
        return self.get_ident(request)

 

二、视图类中指定频率类

from .utils import app_throttles   # 引入频率类的模块

class BookView(ModelViewSet):

    # authentication_classes = [UserAuth]   # 指定认证的类,变量名必须是 authentication_classes
    # permission_classes = [UserPerm]   # 指定权限类,变量名必须是 permission_classes
    throttle_classes = [app_throttles.RateThrottle]   # 指定定频率类,到具体的类名

    queryset = Book.objects.all()
    serializer_class = BookSerializer

全局限制访问频率 (SimpleRateThrottle)

全局的局部的区别在于,限制的次数,在setting中设置,其余的一样

一、定义频率类

# app / utils / app_throttles.py

class RateThrottle(SimpleRateThrottle):
    #指定访问频率
    scope = "visit_rate"        # 在settings中设置visit_rate,scope是固定的变量名

    #指定通过什么方式来区分用户
    def get_cache_key(self, request, view):
        return self.get_ident(request)

settings.py

REST_FRAMEWORK = {
    "DEFAULT_THROTTLE_CLASSES": ('throttler.utils.app_throttles.RateThrottle',),  #频率类的路径
    "DEFAULT_THROTTLE_RATES": {
        "visit_rate": "5/m"
    }
}

 

 


 

 

源码中确定settings中的变量名:

class SimpleRateThrottle(BaseThrottle):
    scope = None
    THROTTLE_RATES = api_settings.DEFAULT_THROTTLE_RATES

 

posted @ 2018-12-11 21:14  葡萄想柠檬  Views(91)  Comments(0)    收藏  举报
目录代码