我正在使用Django REST框架(DRF)构建一个API,并且我面临着速率限制的问题.具体来说,我需要为不同类型的用户设置不同的速率限制:
Staff members: 1000 requests per day
Normal users: 100 requests per day
Anonymous users: 10 requests per day
我try 了几种方法,但到目前为止还没有成功.谁能提供关于如何使用DRF实现基于用户类型的动态速率限制的指导?
我一直在try 根据用户类型在Django REST框架(DRF)中设置动态速率限制.具体地说,我使用内置的DRF限制类创建了四个限制类:PublicThrottle、PrivateAnonThrottle、PrivateFree UserThrottle和PrivatePaidUserThrottle.我已经将PublicThrottle类的限制率定义为1000/天,并将其他每个类的Scope属性设置为唯一的值.
对于PrivatePaidUserThrottle类,我重写了ALLOW_REQUEST方法,以判断发出请求的用户是否为工作人员.如果是,我想使用PRIVATE_PAYED_USER作用域,否则我想使用PRIVATE_FREE_USER作用域.
我所期待的:
我预计将根据用户类型强制实施速率限制.具体地说,我预计工作人员的速率限制为1000/天,普通用户的速率限制为100/天,匿名用户的速率限制为10/天.然而,速率限制似乎并没有像预期的那样起作用,我一直无法找到有关此主题的有用文档.
from rest_framework.throttling import ScopedRateThrottle, UserRateThrottle, AnonRateThrottle
from rest_framework import throttling
class PublicThrottle(ScopedRateThrottle):
THROTTLE_RATES = {
'public': '1000/day' # Define the throttle rate for public APIs
}
class PrivateAnonThrottle(AnonRateThrottle):
scope = "private_anon"
class PrivateFreeUserThrottle(UserRateThrottle):
scope = "private_free_user"
class PrivatPaidUserThrottle(UserRateThrottle):
scope = "private_paid_user"
def allow_request(self, request, view):
if request.user.is_staff:
self.scope = "private_paid_user"
else:
self.scope = "private_free_user"
return super().allow_request(request, view)
settings.py
为了更容易测试,我降低了
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
# token authentication is used for the API
'rest_framework.authentication.TokenAuthentication',
# session authentication is used for the admin
'rest_framework.authentication.SessionAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
],
# for rate limiting
'DEFAULT_THROTTLE_CLASSES': [
'rest_framework.throttling.AnonRateThrottle',
'rest_framework.throttling.UserRateThrottle',
],
'DEFAULT_THROTTLE_RATES': {
'anon': '10/day',
"user": "50/day",
"private_anon": "3/day",
"private_free_user": "7/day",
"private_paid_user": "10/day",
},
}
在5次请求后,即使是员工帐户,它仍会提供
{'detail': 'Request was throttled. Expected available in 86398 seconds.'}
有没有人可以建议我可能做错了什么,或者提供关于如何使用DRF根据用户类型实现动态速率限制的指导?