问题描述
from rest_framework.throttling import UserRateThrottle
class OncePerDayUserThrottle(UserRateThrottle):
rate = '1/day'
我在类api视图中使用此油门,例如:
class PostHitCount(APIView):
throttle_classes = [OncePerDayUserThrottle]
def post(self,request,hitcount_pk,format=None):
# my post method
与此视图相对应的网址是
path('add-hitcount/<int:hitcount_pk>/',PostHitCount.as_view())
如果我是第一次通过URL add-count / 1 / 访问此视图,则可以。 如果以后再发布到相同的URL,则不允许我这样做(没关系!)。
现在,如果我发布到URL add-count / 2 / ,该请求将被拒绝,因为用户已经访问了该视图!
我如何允许使用其他详细网址的请求?
还可以将节流率设置为 1 / year 或什至 1 / lifetime 吗?怎么样?
解决方法
最好的方法是覆盖“get_cache_key”方法。
from rest_framework.throttling import UserRateThrottle
class OncePerDayUserThrottle(UserRateThrottle):
rate = '1/day'
cache_format = 'throttle_%(scope)s_%(ident)s_%(detail)s'
def get_cache_key(self,request,view):
"""
Limits the rate of API calls that may be made by a given user.
The user id will be used as a unique cache key if the user is
authenticated. For anonymous requests,the IP address of the request will
be used.
"""
scope = 'user'
def get_cache_key(self,view):
if request.user.is_authenticated:
ident = request.user.pk
else:
ident = self.get_ident(request)
return self.cache_format % {
'scope': self.scope,'ident': ident,'detail': view.kwargs.get("hitcount_pk")
}
,
您看到了吗? https://www.django-rest-framework.org/api-guide/throttling/#userratethrottle
您需要使用“范围”:
class BurstRateThrottle(UserRateThrottle):
scope = 'burst'
class SustainedRateThrottle(UserRateThrottle):
scope = 'sustained'
并在settings.py中定义范围:
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': [
'example.throttles.BurstRateThrottle','example.throttles.SustainedRateThrottle'
],'DEFAULT_THROTTLE_RATES': {
'burst': '60/min','sustained': '1000/day'
}
}