频率组件throttle

频率组件

throttle

"""
系统:
1)AnonRateThrottle:对同一IP游客的限制
2)UserRateThrottle:对同一IP登录用户的限制
必须在settings.py中
'DEFAULT_THROTTLE_RATES': {
    'user': '10/min',  # 登录的用户一分钟可以访问10次
    'anon': '3/min',  # 游客一分钟可以访问3次
}
在视图类中:
class TempAPIView(APIView):
    ...
    throttle_classes = [AnonRateThrottle, UserRateThrottle]
    
    

自定义:基于auth的Group与Permission表
1)自定义频率类,继承SimpleRateThrottle,重写get_cache_key,明确scope
    SimpleRateThrottle已经帮我们实现了 allow_request、wait
2)scope与settings.py的DEFAULT_THROTTLE_RATES配合使用
3)get_cache_key中完成
    拿到限制信息 ident <= request中获取
    没有限制信息 返回None => 不限制
    有限制信息 返回限制信息字符串 => 有限制
"""

自定义频率类:一分钟一个手机号只允许访问一次接口

from rest_framework.throttling import SimpleRateThrottle

class ThreeMinRateThrottle(SimpleRateThrottle):
    scope = 'sms'
    def get_cache_key(self, request, view):
        # 对手机号频率限制
        ident = request.data.get('mobile')
        if not ident:  # 为发现限制条件,返回None代表不进行频率限制
            return None
        return self.cache_format % {
            'scope': self.scope,
            'ident': ident
        }
# settings.py
'DEFAULT_THROTTLE_RATES': {
    'user': '10/min',  # 登录的用户一分钟可以访问10次
    'anon': '3/min',  # 游客一分钟可以访问3次
    'sms': '1/min',
}

猜你喜欢

转载自www.cnblogs.com/SkyOceanchen/p/11923011.html