DRF可以对接口访问的频次进行限制,以减轻服务器的压力。
1 在配置文件中,使用DEFAULT_THROTTLE_CLASSES和DEFAULT_THROTTLE_RATES进行配置。
1.1 可选限流类
DEFAULT_THROTTLE_CLASSES参数用于设置可选限流类,主要有三类
AnonRateThrottle:限制所有匿名未认证用户,使用IP区分用户。即每个IP的访问频次
UserRateThrottle:限制认证用户,使用user_id来区分
ScopedRateThrottle:限制用户对于每个接口的访问频次,使用IP或user_id来区分用户,使用接口关键字来区分接口。
1.2 限流频次设置
DEFAULT_THROTTLE_RATES可以使用second、minute、hour、day来指明周期。
指定周期的关键是是有规定的。
如果选取了AnonRateThrottle,则必须设置anon关键字的周期;
如果选择了UserRateThrottle,则必须设置user关键字的周期。
如果选择了ScopedRateThrottle,则必须指定接口关键字来设置周期。
2 匿名用户和默认用户限流
因为是针对user_id或IP限流,所以,只需要设置后,就可以直接限流了。
REST_FRAMEWORK = {
# 限流
'DEFAULT_THROTTLE_CLASSES': (
'rest_framework.throttling.AnonRateThrottle', # 限制所有匿名未认证用户
'rest_framework.throttling.UserRateThrottle', # 限制所有用户
),
'DEFAULT_THROTTLE_RATES': {
'anon': '1/minute', # 限制匿名未认证用户的访问频次,即未注册用户
'user': '1/minute' # 限制用户对所有接口访问频次,即注册用户
}
}
3 浏览器访问
第一次访问能看到数据,但再刷新时则会出现以下提示。而且针对工程中所有接口都会限制。

4 限制用户对每个接口的访问频次
4.1 修改配置文件
REST_FRAMEWORK = {
# 限流
'DEFAULT_THROTTLE_CLASSES': (
# 'rest_framework.throttling.AnonRateThrottle', # 限制所有匿名未认证用户
# 'rest_framework.throttling.UserRateThrottle', # 限制所有用户
'rest_framework.throttling.ScopedRateThrottle', # 限制用户对每个视图的访问频次
),
'DEFAULT_THROTTLE_RATES': {
# 'anon': '1/minute',
# 'user': '1/minute' # 限制用户对所有接口访问频次
'org_home':'1/minute' # 限制匿名用户或注册用户对接口的访问频次
}
}
4.2 接口频次验证
打开Applications/Organizations/views/ExpHome.py文件。
导入包:from rest_framework.throttling import UserRateThrottle
引入限流:throttle_scope = 'org_home'
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from GeneralTools.Authentication import GetAuthentication
class ExpHome(APIView):
authentication_classes = (GetAuthentication,)
permission_classes = [IsAuthenticated]
throttle_scope = 'org_home'
@classmethod
def get(cls, request):
# request.session['token'] = TOKEN
"""
【功能描述】主要用于示例展示</br>
【返回参数】返回用户请求的网页</br>
"""
return render(request, 'exp-home.html')
5 浏览器访问:http://127.0.0.1:8000/authorizations接口时,则不会出现限流,而访问http://127.0.0.1:8000/Examples/ExpHome/?token=XXX时,则会限流。
浙公网安备 33010602011771号