Django APIView.throttle_scope 属性似乎不起作用

问题描述 投票:0回答:1

问题

我试图按照 django Rest Framework guide 来实现节流。由于我不需要创建另一个节流阀类,因此我尝试使用 .throttle_scope 属性。所以,我是这样实现的:

class MyView(APIView):
    throttle_scope = 'my_scope'

    def post(self, request) -> Response:
        # do something
        return Response(status=status.HTTP_200_OK)

在设置中我写了这样的东西:

REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_RATES': {
        'my_scope': '1/minute',
    }
}

我尝试了什么

我尝试使用邮递员每分钟向该端点发出超过 1 个请求,但我从未收到过 429 代码。我尝试创建一个新的节流阀类并使用 .throttle_classes 属性,如下所示:

class MyView(APIView):
    throttle_classes = [MyThrottle]

    def post(self, request) -> Response:
        # do something
        return Response(status=status.HTTP_200_OK)
class MyThrottle(UserRateThrottle):
    scope = 'my_scope'

我保持设置不变,它按预期工作。


可能原因

所以现在我想知道,是否 throttting_scope 属性仅在用户是匿名的情况下才有效?

我做这个假设是因为我试图让 MyThrottle 继承

AnonRateThrottle
而不是
UserRateThrottle
但它不起作用。顺便说一句,所有有权访问此端点的用户都经过身份验证,因此我认为
ScopedRateThrottle
更像是
AnonRateThrottle

python django django-rest-framework throttling
1个回答
0
投票

这个问题很微不足道,我通过在里面添加

ScopedRateThrottle
解决了它:

REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_CLASSES': [
        ...
        'rest_framework.throttling.ScopedRateThrottle'
    ],
    ...
}

我再次测试,问题解决了。

© www.soinside.com 2019 - 2024. All rights reserved.