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

Django REST Framework限流在测试用例中报错:未设置'anon'范围默认速率

Django REST Framework限流在测试用例中报错问题

问题背景

项目中使用DRF的限流功能,本地和生产环境运行正常,但测试用例调用接口时返回错误。

配置信息

REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_CLASSES': [
        'rest_framework.throttling.AnonRateThrottle',
        'rest_framework.throttling.UserRateThrottle',
        'rest_framework.throttling.ScopedRateThrottle',
    ],
    'DEFAULT_THROTTLE_RATES': {
        'anon': '100/min',
        'user': '200/min',
        # 限制用户每分钟访问路由的次数
        'authentication': '3/min',
        # 用于未登录用户的路由,比如请求OTP
        'monitor': '3/min',
    },
    'DEFAULT_AUTHENTICATION_CLASSES': (
        # 设置DRF默认认证为JWT
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticatedOrReadOnly',
    ),
    'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
}

测试用例代码

def test_verify_and_check_if_profile_created(self):
    """
    测试用户配置文件是否创建,同时先验证用户
    :return:
    """
    # 检查用户配置文件不为空
    self.assertIsNotNone(self.user.user_profile)
    # 为已设置的用户请求OTP
    client = APIClient()
    client.credentials(HTTP_INSTASAW_SK_HEADER=config('INSTASAW_SK_HEADER'))
    request_otp_response = client.post('/api/v1/auth/verify_account/', {
        "email": self.user_email,
    })
    print(request_otp_response.json())

错误信息

django.core.exceptions.ImproperlyConfigured: No default throttle rate set for 'anon' scope

解决方案

1. 确认测试环境配置加载

检查测试用例是否正确加载项目主配置。如果测试使用自定义settings文件,确保REST_FRAMEWORK['DEFAULT_THROTTLE_RATES']中包含anon项,避免测试配置覆盖主配置时遗漏该字段。

2. 测试用例中临时禁用限流

如果测试不需要验证限流逻辑,可以在测试中临时关闭限流:

def test_verify_and_check_if_profile_created(self):
    from django.conf import settings
    # 保存原限流配置
    original_throttle_classes = settings.REST_FRAMEWORK['DEFAULT_THROTTLE_CLASSES']
    # 临时移除所有限流类
    settings.REST_FRAMEWORK['DEFAULT_THROTTLE_CLASSES'] = []
    
    # 执行测试逻辑
    self.assertIsNotNone(self.user.user_profile)
    client = APIClient()
    client.credentials(HTTP_INSTASAW_SK_HEADER=config('INSTASAW_SK_HEADER'))
    request_otp_response = client.post('/api/v1/auth/verify_account/', {
        "email": self.user_email,
    })
    print(request_otp_response.json())
    
    # 恢复原配置
    settings.REST_FRAMEWORK['DEFAULT_THROTTLE_CLASSES'] = original_throttle_classes

3. 检查配置继承关系

若测试环境使用独立settings文件(如test_settings.py),确保它通过from .settings import *继承主配置,避免重新定义REST_FRAMEWORK时丢失DEFAULT_THROTTLE_RATES的配置项。

4. 验证视图的限流Scope设置

确认verify_account视图类正确设置了throttle_scope = 'authentication',避免视图默认使用anon限流但配置加载异常的情况。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 17:19:04