django-rest-framework - 如何在 django Rest 框架中定义多个 throttle

标签 django-rest-framework

django_Rest_framework 的文档指出:

Multiple throttles can also be used if you want to impose both burst throttling rates, and sustained throttling rates. For example, you might want to limit a user to a maximum of 60 requests per minute, and 1000 requests per day.

但是,没有解释如何实现这样的情况。

我尝试过类似的方法,但没有成功

REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_CLASSES': (
        'rest_framework.throttling.AnonRateThrottle',
        'rest_framework.throttling.UserRateThrottle'
    ),
    'DEFAULT_THROTTLE_RATES': {
        'anon': '100/day',
        'user': ['30/minute', '1000/day']
    }
}

最佳答案

这是可能的,但有必要定义多个限制,每个时间单位一个。

  1. 首先,您可以在设置中定义所需的所有限制,例如每分钟不超过 30 个,每天不超过 1000 个。
        REST_FRAMEWORK = {
          'DEFAULT_THROTTLE_CLASSES': (
                    'rest_framework.throttling.AnonRateThrottle',
              'rest_framework.throttling.UserRateThrottle'
          ),
          'DEFAULT_THROTTLE_RATES': {
              'anon': '100/day',
              'user_min': '30/minute',
              'user_day': '1000/day',
          }
        }
  • 您可以将 Throttling 类添加为 UserRateThrottle 的子类,并具有您定义的范围:
  • from rest_framework.throttling import UserRateThrottle
    
    class UserMinThrottle(UserRateThrottle):
                 scope = 'user_min'
    
  • 最后,在 APIView 上,您将具有您在上一步中定义的限制的类设置为throttle_classes。
  • class YourAPIView(APIView):
         throttle_classes = [
              UserMinThrottle,
              UserDayThrottle
         ]
    

    关于django-rest-framework - 如何在 django Rest 框架中定义多个 throttle ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56128915/

    相关文章:

    django - 如何以正确的方式组织 REST-API 版本控制?

    django - 当部署 Django 应用程序 (`python manage.py collectstatic` 不起作用时,如何向 AWS 提供静态文件)?

    django - Django elasticsearch DSL DRF建议问题

    python - 如何在测试时将 Django/DRF 中的日期时间转换为字符串

    Angular 2 登录到 Django Rest Framework 后端

    python - Django 请求数据返回 str 而不是 list

    python - Django REST Framework 出现不需要的字段错误

    django - 在 Django Rest Framework 中创建或更新(使用 PUT)

    python - 记录对 django-rest-framework 的请求

    python - Django 1.9 第一次迁移没有创建表