drf框架中的Throttle频率组件

05-03 频率组件

1.系统自带的频率类:

"""
系统自带:
1) AnonRateThrottle:对同一IP游客的
2) UserRateThrottle:对同一IP登陆用户的限制
3) 以上两个方法可去源码查看限制规则

必须在settings.py中配置
REST_FRAMEWORK = {
	'DEFAULT_THROTTLE_RATES': {
		'user': '10/min',  # 登陆的用户一分钟可以访问10次
		'anon': '3/min',  # 游客一分钟可以访问10次
}
}
在视图中使用(添加类属性throllte_classes):
class MyAPIView(APIView):
	throttle_classes = [AnonRateThrottle, UserRateThrottle]
	...
"""

2.自定义频率类:

"""
自定频率类:基于auth的Group与Permission表
1) 自定义频率类,继承SimpleRateThrottle,重写get_cache_key,设置scope
2) scope本质是一个认证字符串,在setings在配置文件中配置scope字符串对应的频率色设置
3) get_cache_key的返回值是字符串,该字符串是缓存访问次数的缓存key
4) 官方get_cache_key写法:
	拿到限制信息 ident --> request中获取
	没有限制信息 返回None --> 不限制
	有限制信息 返回限制信息字符串 --> 限制

"""

自定义频率类示例:限制同一手机号一分钟只能访问一次

# utils.throttles.py
from rest_framework.throttling import SimpleRateThrottle

class OneMinRateThrottle(SimpleRateThrottle):
    # 限制条件去settings中配置对应的名字
    scpoe = 'sms'
    # 重写get_cache_key方法
	def get_cache_key(self, request, view):
        # 获取前端传送过来的手机号(验证条件)
        ident = request.data.get('phone')
        # 如果没有手机号就返回None,不做限制】
        if not ident:
            return None
        # 返回限制信息字符串
        return self.cache_format % {
            # 限制条件
            'scope': self.scope,
            # 限制的手机号
            'ident': ident
        }

settings.py中配置:

'REST_FRAMEWORK' = {
    'DEFAULT_THROTTLE_RATES': {
        'sms': '1/min',
    }
}
posted @ 2019-11-30 15:47  17vv  阅读(414)  评论(0编辑  收藏  举报