每个用户和每个vi的Django rest框架限制

2024-09-24 06:23:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个api视图(django rest framework):

class ApiView1(APIView):
    ...
    throttle_classes = (UserRateThrottle, )

以及api 2:

^{pr2}$

以及我的设置:

REST_FRAMEWORK = {
    ...,
    'DEFAULT_THROTTLE_RATES': {
        'user': '5/minute'
    }
}

当请求apiew1五次时,一切正常,但是之后当请求apiew2时,我得到一个http 429状态码:

Request was throttled. Expected available in 45 seconds.

问题:我可以对每个用户和每个视图使用限制吗?如果是,怎么做?在


Tags: django视图restapidefaultframeworkclassclasses
2条回答

因为这是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".

由于没有在any视图中设置限制范围,因此ApiView1和{}都使用相同的限制范围{}。所以他们有相同的限制。如果一个视图被过度访问,另一个视图也将是不可接受的。在

在您的场景中,您应该在apieview中设置不同的throttle_作用域,并将该范围添加到REST_FRAMEWORK.DEFAULT_THROTTLE_RATES。在

是的,你可以。在

对于基于类的视图:

class YourView(APIView):
    throttle_classes = (UserRateThrottle, )

    def get(self, request, format=None):
        content = { ... Your response here ... }
        return Response(content)

对于基于函数的视图,可以使用修饰符:@throttle_classes([UserRateThrottle])

参考:http://www.django-rest-framework.org/api-guide/throttling/

相关问题 更多 >