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

如何仅对ExampleView中的POST方法进行限流?

实现仅对POST方法应用限流的方案

针对你的需求,我们可以通过两种常用方式实现仅对post方法应用限流,get方法跳过限流:

方式一:使用方法装饰器(推荐)

移除类级别的全局限流配置,仅在需要限流的post方法上通过@throttle_classes装饰器指定限流规则:

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.throttling import UserRateThrottle
from rest_framework.decorators import throttle_classes

class ExampleView(APIView):
    def get(self, request, format=None):
        content = {
            'status': 'request was permitted'
        }
        return Response(content)

    @throttle_classes([UserRateThrottle])
    def post(self, request, format=None):
        content = {
            'status': 'request was permitted'
        }
        return Response(content)

这种方式代码可读性强,能直观看到哪个方法启用了限流,符合DRF的最佳实践。

方式二:在方法内覆盖限流类

保留类级别的限流配置,在get方法内将当前实例的throttle_classes设为空列表,从而取消该方法的限流:

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.throttling import UserRateThrottle

class ExampleView(APIView):
    throttle_classes = [UserRateThrottle]

    def get(self, request, format=None):
        # 覆盖当前方法的限流规则,取消限流
        self.throttle_classes = []
        content = {
            'status': 'request was permitted'
        }
        return Response(content)

    def post(self, request, format=None):
        content = {
            'status': 'request was permitted'
        }
        return Response(content)

这种方式无需额外导入装饰器,适合快速修改现有代码,但可读性稍弱。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 13:41:01