django_Rest_framework 的文档指出:
Multiple throttles can also be used if you want to impose both burst throttling rates, and sustained throttling rates. For example, you might want to limit a user to a maximum of 60 requests per minute, and 1000 requests per day.
但是,没有解释如何实现这样的情况。
我尝试过类似的方法,但没有成功
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': (
'rest_framework.throttling.AnonRateThrottle',
'rest_framework.throttling.UserRateThrottle'
),
'DEFAULT_THROTTLE_RATES': {
'anon': '100/day',
'user': ['30/minute', '1000/day']
}
}
最佳答案
这是可能的,但有必要定义多个限制,每个时间单位一个。
- 首先,您可以在设置中定义所需的所有限制,例如每分钟不超过 30 个,每天不超过 1000 个。
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': (
'rest_framework.throttling.AnonRateThrottle',
'rest_framework.throttling.UserRateThrottle'
),
'DEFAULT_THROTTLE_RATES': {
'anon': '100/day',
'user_min': '30/minute',
'user_day': '1000/day',
}
}
- 您可以将 Throttling 类添加为
UserRateThrottle
的子类,并具有您定义的范围:
from rest_framework.throttling import UserRateThrottle
class UserMinThrottle(UserRateThrottle):
scope = 'user_min'
- 最后,在 APIView 上,您将具有您在上一步中定义的限制的类设置为throttle_classes。
class YourAPIView(APIView):
throttle_classes = [
UserMinThrottle,
UserDayThrottle
]
关于django-rest-framework - 如何在 django Rest 框架中定义多个 throttle ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56128915/