You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django APIView.throttle_scope属性不生效,疑仅支持匿名用户?

Django REST Framework throttle_scope 不生效问题

我按照DRF官方指南实现限流功能,不想新建限流类,尝试直接使用APIView的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',
    }
}

测试情况

用Postman测试时,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'

配置保持不变,此时限流功能正常生效。

疑问猜想

我怀疑throttle_scope属性是不是仅对匿名用户生效?之前试过让自定义限流类继承AnonRateThrottle也没生效,而这个接口的访问用户都是已认证用户,所以猜测ScopedRateThrottle的逻辑类似AnonRateThrottle,只针对匿名用户生效?

内容的提问来源于stack exchange,提问作者aldisti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 02:45:02