Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django REST how to set throttle period to allow one request in 10 minutes?

Documentation says that period should be one of: ('s', 'sec', 'm', 'min', 'h', 'hour', 'd', 'day'). I am curious if I can set period to something like 1/10min?

like image 779
pythad Avatar asked May 16 '18 12:05

pythad


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 Restapi in Django?

Django REST framework (DRF) is a powerful and flexible toolkit for building Web APIs. Its main benefit is that it makes serialization much easier. Django REST framework is based on Django's class-based views, so it's an excellent option if you're familiar with Django.

Is Django REST Framework slow?

The Django REST Framework(DRF) is a framework for quickly building robust REST API's. However when fetching models with nested relationships we run into performance issues. DRF becomes slow. This isn't due to DRF itself, but rather due to the n+1 problem.


2 Answers

Looking at the code and documentation you cannot do this 'out of the box'. But I do see the possibility described to make your own custom throttle based on one of the existing one's:

from rest_framework.throttling import AnonRateThrottle


class AnonTenPerTenMinutesThrottle(AnonRateThrottle):
    def parse_rate(self, rate):
        """
        Given the request rate string, return a two tuple of:
        <allowed number of requests>, <period of time in seconds>

        So we always return a rate for 10 request per 10 minutes.

        Args:
            string: rate to be parsed, which we ignore.

        Returns:
            tuple:  <allowed number of requests>, <period of time in seconds>
        """
        return (10, 600)
like image 144
The Pjot Avatar answered Oct 19 '22 07:10

The Pjot


Basically what XY said is true but it might not work because you still have to put the rate like this:

from rest_framework.throttling import AnonRateThrottle

class AnonTenPerTenMinutesThrottle(AnonRateThrottle):
    

    rate = '1/s' # <<<<< This line is very important
    # You just can enter any rate you want it will directly be overwritten by parse_rate
    

    def parse_rate(self, rate):
        """
        Given the request rate string, return a two tuple of:
        <allowed number of requests>, <period of time in seconds>

        So we always return a rate for 10 request per 10 minutes.

        Args:
            string: rate to be parsed, which we ignore.

        Returns:
            tuple:  <allowed number of requests>, <period of time in seconds>
        """
        return (10, 600) # 10 Requests per 600 seconds (10 minutes)
like image 28
Henrik Avatar answered Oct 19 '22 05:10

Henrik