基于Django自定义限流,按用户高级账户状态控制API调用频次
解决方案与验证步骤
1. 当前视图级指定限流类的实现是正确的
- 你现在仅在
Translator APIView中单独指定自定义限流类的做法没问题,这样只会限制翻译API的调用次数,不会影响登录等其他接口的交互。 - 之前全局设置限流类导致所有交互被计数,是因为DRF会对所有继承
APIView的视图生效,包括登录、注册这类不需要限流的接口,这是全局配置的必然结果。
2. 自定义限流类的正确实现示例
确保你的UserTypeThrottle类继承自DRF的SimpleRateThrottle,并正确重写核心方法:
from rest_framework.throttling import SimpleRateThrottle class UserTypeThrottle(SimpleRateThrottle): scope = "user_type" def get_cache_key(self, request, view): # 仅对已登录用户限流,匿名用户可按需调整规则 if not request.user.is_authenticated: return None # 不限制匿名用户,或改为基于IP的标识 return self.cache_format % { "scope": self.scope, "ident": request.user.pk } def get_rate(self): # 根据用户的premium_account状态返回对应限流速率 return "5/day" if self.request.user.premium_account else "1/day"
3. 配置与视图绑定的正确方式
在settings.py中配置scope的默认速率(会被自定义类的get_rate方法覆盖,仅作为 fallback):
REST_FRAMEWORK = { "DEFAULT_THROTTLE_RATES": { "user_type": "1/day", } }
然后在翻译视图中绑定限流类:
from rest_framework.views import APIView from rest_framework.response import Response class TranslatorAPIView(APIView): throttle_classes = [UserTypeThrottle] # 仅在此视图应用限流规则 def post(self, request): # 此处编写翻译逻辑 return Response({"result": "翻译内容"})
4. 优化建议
- 如果多个视图需要相同限流规则,可以用Mixin类统一注入,避免重复代码:
class ThrottledTranslationMixin: throttle_classes = [UserTypeThrottle] class TranslatorAPIView(ThrottledTranslationMixin, APIView): # 视图逻辑代码
- 若要限制匿名用户,可在
get_cache_key中用request.META.get('REMOTE_ADDR')作为标识,并在get_rate中添加对应的速率规则。
内容的提问来源于stack exchange,提问作者mitch1625
相关产品推荐
相关产品推荐

