问题描述
想问是否有人知道如何在基于函数的视图中为不同的请求方法设置不同的限制范围。
例如
@api_view(['GET','POST'])
def someFunction(request):
if request.method == 'GET':
# set scope for get requests
elif request.method == 'POST':
# set scope for post requests
我尝试环顾四周,但所有答案仅适用于基于类的视图。非常感谢您的帮助。
解决方法
您可以通过首先创建所有自定义限制类来解决此问题。注意:只有节流阀在类中,而视图是函数。
class PostAnononymousRateThrottle(throttling.AnonRateThrottle):
scope = 'post_anon'
def allow_request(self,request,view):
if request.method == "GET":
return True
return super().allow_request(request,view)
class GetAnononymousRateThrottle(throttling.AnonRateThrottle):
scope = 'get_anon'
def allow_request(self,view):
if request.method == "POST":
return True
return super().allow_request(request,view)
class PostUserRateThrottle(throttling.UserRateThrottle):
scope = 'post_user'
def allow_request(self,view)
class GetUserRateThrottle(throttling.UserRateThrottle):
scope = 'get_user'
def allow_request(self,view)
如果您不查找身份验证或方法类型,则可以选择消除这些类。
然后您需要导入
from rest_framework.decorators import api_view,throttle_classes
然后,您可以使用具有创建的所有权限的油门_类装饰器包装函数视图
@api_view(['GET','POST'])
@throttle_classes([PostAnononymousRateThrottle,GetAnononymousRateThrottle,PostUserRateThrottle,GetUserRateThrottle])
def someFunction(request):
if request.method == 'POST':
return Response({"message": "Got some data!","data": request.data})
elif request.method == 'GET':
return Response({"message": "Hello,world!"})
别忘了在settings.py
中提到油门速度REST_FRAMEWORK = {
'DEFAULT_THROTTLE_RATES': {
'post_anon': '3/minute','get_anon': '1/minute','post_user': '2/minute','get_user': '2/minute'
}
}
,
我终于找到了基于函数的视图的解决方法。 这是我的实现方式。
如先前答案中所述,我们需要根据需要扩展UserRateThrottle类或AnonRateThrottle类。
就我而言,我对限制用户的请求更感兴趣。
from rest_framework.throttling import UserRateThrottle
class CustomThrottle(UserRateThrottle):
scope = 'my_custom_scope'
def allow_request(self,view):
if request.method == 'GET':
self.scope = 'get_scope'
self.rate = '2/hour'
return True
return super().allow_request(request,view)
在设置中:
'DEFAULT_THROTTLE_RATES': {
'my_custom_scope': '3/day'
}
默认情况下,此类将根据设置文件中设置的速率限制POST请求。我在这里添加的内容是在请求方法为GET的情况下更改范围和速率。如果没有这种更改,由于DRF Throttler使用的默认缓存,可能会出现一些问题。我们需要在CustomThrottle类本身内部设置速率和范围,否则与POST方法关联的范围将同时应用于GET和POST。
最后,我们在基于函数的视图中添加装饰器。
from rest_framework import api_view,throttle_classes
import CustomThrottle
@api_view(['GET','POST'])
@throttle_classes([CustomThrottle])
def someFunction(request):
if request.method == 'GET':
# set scope for get requests
elif request.method == 'POST':
# set scope for post requests
就这样:D