[英]django rest framework throttling per user and per view
我有两个 api 视图(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.
问题:我可以对每个用户和每个视图使用限制吗? 如果是,怎么做?
是的你可以。
对于基于类的视图:
class YourView(APIView):
throttle_classes = (UserRateThrottle, )
def get(self, request, format=None):
content = { ... Your response here ... }
return Response(content)
对于基于函数的视图,您可以使用装饰器: @throttle_classes([UserRateThrottle])
_参考: https ://www.django-rest-framework.org/api-guide/throttling/
因为这是django-rest-framework 的特性。
ScopedRateThrottle 类可用于限制对 API 特定部分的访问。 仅当正在访问的视图包含 .throttle_scope 属性时才会应用此限制。 然后将通过将请求的“范围”与唯一的用户 ID 或 IP 地址连接起来形成唯一的节流键。
允许的请求速率由 DEFAULT_THROTTLE_RATES 设置使用请求“范围”中的键确定。
由于您没有在任何视图中设置油门范围,因此ApiView1
和ApiView2
使用相同的油门作用域scope
。 所以他们共享相同的限制。 如果一个视图被过度访问,另一个视图也将是不可接受的。
在您的场景中,您应该在 apiview 中设置不同的 Throttle_scope 并将范围添加到REST_FRAMEWORK.DEFAULT_THROTTLE_RATES
。
如果您有很多油门作用域并且不想在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 可以为不同的视图自动设置不同的范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.