我有两个 api View (django rest 框架):
class ApiView1(APIView):
...
throttle_classes = (UserRateThrottle, )
和 API 2:
class ApiView2(APIView):
...
throttle_classes = (UserRateThrottle, )
和我的设置:
REST_FRAMEWORK = {
...,
'DEFAULT_THROTTLE_RATES': {
'user': '5/minute'
}
}
当请求 ApiView1 五次时,一切正常,但之后当请求 ApiView2 时,我得到一个 http 429 状态代码:
Request was throttled. Expected available in 45 seconds.
问题:我可以针对每个用户和每个 View 使用限制吗?如果是,如何实现?
最佳答案
因为它是django-rest-framework 的特征.
The ScopedRateThrottle class can be used to restrict access to specific parts of the API. This throttle will only be applied if the view that is being accessed includes a .throttle_scope property. The unique throttle key will then be formed by concatenating the "scope" of the request with the unique user id or IP address.
The allowed request rate is determined by the DEFAULT_THROTTLE_RATES setting using a key from the request "scope".
由于您没有为任何 View 设置 throttle_scope,ApiView1
和 ApiView2
使用相同的 throttle 范围 scope
。所以他们共享相同的限制。如果一个 View 被过度访问,另一个 View 也将不被接受。
在您的场景中,您应该在 apiview 中设置不同的 throttle_scope 并将范围添加到 REST_FRAMEWORK.DEFAULT_THROTTLE_RATES
。
如果你有很多 throttle 范围并且不想在 settings.py
中添加太多范围,你应该创建你自己的 Throttle
类并覆盖 get_cache_key
函数。
class MyThrottle(UserRateThrottle):
def get_cache_key(self, request, view):
return "throttle_{viewid}_{indent}".format(
viewid=id(view),
indent=self.get_indent(request)
)
这个 ThrottleClass 可以自动为不同的 View 设置不同的范围。
关于python - 每个用户和每个 View 的 django rest 框架限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50255005/