在django rest框架中限制细节视图
我有一个定制油门:在django rest框架中限制细节视图,django,django-rest-framework,django-views,throttling,Django,Django Rest Framework,Django Views,Throttling,我有一个定制油门: from rest_framework.throttling import UserRateThrottle class OncePerDayUserThrottle(UserRateThrottle): rate = '1/day' 我在类api视图中使用此节流阀: class PostHitCount(APIView): throttle_classes = [OncePerDayUserThrottle] def post(self, reque
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
与此视图对应的url为
path('add-hitcount/<int:hitcount_pk>/', PostHitCount.as_view())
path('add-hitcount/',PostHitCount.as_view())
如果我第一次通过url add count/1/访问此视图,我是被允许的。
如果我以后发布到同一个url,我是不被允许的(这没关系!)
现在,如果我发布到url add count/2/,请求将被拒绝,因为用户已经访问了该视图
如何允许使用其他详细url的请求
此外,是否可以将油门设定为1/年或甚至1/寿命?怎么看?你看到了吗?
您需要使用“范围”:
并在settings.py中定义范围:
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': [
'example.throttles.BurstRateThrottle',
'example.throttles.SustainedRateThrottle'
],
'DEFAULT_THROTTLE_RATES': {
'burst': '60/min',
'sustained': '1000/day'
}
}
最好的方法是重写“get\u cache\u key”方法
为什么我得不到任何帮助?我下面的解决方案应该可以解决您的问题。
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': [
'example.throttles.BurstRateThrottle',
'example.throttles.SustainedRateThrottle'
],
'DEFAULT_THROTTLE_RATES': {
'burst': '60/min',
'sustained': '1000/day'
}
}
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, request, 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")
}