Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define multiple throttle in django rest framework

The documentation of django_Rest_framework states:

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.

However, it is not explained how to implement a situation like it.

I've tried something like this but it didn't work

REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_CLASSES': (
        'rest_framework.throttling.AnonRateThrottle',
        'rest_framework.throttling.UserRateThrottle'
    ),
    'DEFAULT_THROTTLE_RATES': {
        'anon': '100/day',
        'user': ['30/minute', '1000/day']
    }
}
like image 958
kiril Avatar asked May 14 '19 11:05

kiril


People also ask

What is throttling in Django REST?

Throttling is similar to permissions, in that it determines if a request should be authorized. Throttles indicate a temporary state, and are used to control the rate of requests that clients can make to an API. As with permissions, multiple throttles may be used.

What is the difference between rate limiting and throttling?

Rate Limiting and Throttling policies are designed to limit API access, but have different intentions: Rate limiting protects an API by applying a hard limit on its access. Throttling shapes API access by smoothing spikes in traffic.

What is throttling in REST API?

API throttling is the process of limiting the number of API requests a user can make in a certain period. An application programming interface (API) functions as a gateway between a user and a software application.


1 Answers

It is possible but it is necessary to define multiple limits, one for each time unit.

  1. First you define in the settings all the limits you need, for example no more than 30 per minute and no more than 1000 per day.
        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',
          }
        }
  1. You add Throttling classes as subclasses of UserRateThrottle with the scopes you defined:
from rest_framework.throttling import UserRateThrottle

class UserMinThrottle(UserRateThrottle):
             scope = 'user_min'
  1. Finally on the APIView you set as throttle_classes the classes with the limits you defined on the previous step.
class YourAPIView(APIView):
     throttle_classes = [
          UserMinThrottle,
          UserDayThrottle
     ]
like image 127
Duilio Avatar answered Nov 12 '22 20:11

Duilio