通过对api接口进行访问频次限流,限流的方式有2种分别是【全局限流】【局部限流】。
DRF中限制对API的调用频率的限流有3个插拔式的限流类,分别是AnonRateThrottle, UserRateThrottle和ScopeRateThrottle类。
- AnonRateThrottle 用于限制未认证用户的请求频率,主要根据用户的 IP地址来确定用户身份。
- UserRateThrottle 用于限定认证用户的请求频率,可对不同类型的用户实施不同的限流政策。
- ScopeRateThrottle可用于限制对 API 特定部分的访问。只有当正在访问的视图包含 throttle_scope 属性时才会应用此限制。这个与UserRateThrottle类的区别在于一个针对用户限流,一个针对API接口限流。注意:只能在APIView类使用
全局使用限流类
在settings.py中进行全局配置,如下所示。一是要设置需要使用的限流类,二是要设置限流范围(scope)及其限流频率。限流时常分别有 day hour min
REST_FRAMEWORK = {
# 限流全局配置
'DEFAULT_THROTTLE_CLASSES': [
'rest_framework.throttling.AnonRateThrottle', # 匿名用户限流
'rest_framework.throttling.UserRateThrottle', # 登录用户限流
'rest_framework.throttling.ScopedRateThrottle', # 针对某一个接口限流(只能在APIView类使用)
],
# 限制访问频次
'DEFAULT_THROTTLE_RATES': {
'anon': '2/min', # 匿名用户频次
'user': '5/min', # 登录用户频次
'detail': '2/min', #继承APIView类的自定义限流
},
}
局部限流方式
针对某一个API接口限流,【ScopedRateThrottle类】在APIView类中使用方法需要在 类视图中添加throttle_scope = 'detail’属性(detail自定义),如下:
class Goods(APIView):
throttle_scope = 'detail' # 注意这一行
def get(self, request):
return response
如何自定义复杂的限流类
有时你还需要自定义限流类。这时你需要继承BaseThrottle类、SimpleRateThrottle或者UserRateThrottle类,然后重写allow_request(self, request, view)或者get_rate(self, request=none)方法。
DRF给的示例方法如下所示,该限流类10个请求中只允许一个通过。
import random
class RandomRateThrottle(throttling.BaseThrottle):
def allow_request(self, request, view):
return random.randint(1, 10) != 1