python - 每个用户和每个 View 的 django rest 框架限制

标签 python django-rest-framework throttling

我有两个 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,ApiView1ApiView2 使用相同的 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/

相关文章:

Django Rest Framework 对缓存请求的 throttle 率

python - 从多个线程获取结果的更好方法

Python IOError : [Errno 90] Message too long, 将长列表传递给 SPI 函数

python - 将默认参数传递给python中的装饰器

python - 如果键存在,则按键对字典进行排序,如果不将其放在列表末尾

python - 如何正确使用 djangorestframworkjwt

web-services - API throttle 最佳实践

python - 调用嵌套 Serializer 的 .update() 方法

django - Django Rest Framework 中的多 token 认证

java - 如何限制或减慢 Grails 的速度?