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

如何在DRF viewsets中仅为create动作配置throttling节流策略?

实现方案

你可以通过重写ModelViewSet的get_throttles方法,针对不同动作返回对应的限流类即可,这是DRF官方推荐的按动作配置类属性的标准实现方式。

方案1:重写get_throttles方法(推荐)

from rest_framework import viewsets

class UserViewSet(viewsets.ModelViewSet):
    # 删掉原本全动作生效的限流类配置
    # throttle_classes = [SomeThrottle] 

    def get_throttles(self):
        # 仅create动作应用指定限流策略
        if self.action == 'create':
            return [SomeThrottle()]
        # 其他动作使用父类默认的限流规则(未配置全局限流的情况下相当于不限流)
        return super().get_throttles()

注意点:

  • 这里返回的是限流类的实例对象,不是类本身,所以要加()
  • 如果其他动作需要保留通用限流配置,也可以把通用限流放在类属性中,仅给create动作叠加额外限流:
class UserViewSet(viewsets.ModelViewSet):
    # 其他动作通用的限流配置(不需要可留空)
    throttle_classes = [OtherCommonThrottle]

    def get_throttles(self):
        if self.action == 'create':
            # create动作同时应用通用限流+专属限流
            return super().get_throttles() + [SomeThrottle()]
        return super().get_throttles()

方案2:action装饰器配置(仅适用于自定义动作,补充说明)

如果是你自己定义的额外动作,可以直接在@action装饰器中指定throttle_classes参数,但内置的create、retrieve、update等默认动作没有用action装饰器声明,不适用这个方案。

内容的提问来源于stack exchange,提问作者A.Mohammadi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 14:39:03