Naftali Shtern
Naftali Shtern

Reputation: 41

Use Throttling to restrict the number of times a certain request can be made globally

I am using Django Throttling, and want to add a behavior that will throttle users from calling a certain request more than X times in rate - globally.

Using AnonRateThrottle or UserRateThrottle is not good enough for me, because it checks the number of times that a certain User or IP address made the request. I want to limit the global calls to a certain api_view, no matter who made the request.

For example, if the rate is 1/min and user X made a request, than every other user will be throttled for the next minute.

EDIT: Thanks to Kaushal's answer below, I found a way to make this work by adding:

def get_cache_key(self, request, view):
    return request.method + request.get_full_path()

Upvotes: 0

Views: 2550

Answers (2)

Kaushal
Kaushal

Reputation: 662

To apply throttle globally for view you can use same key. here idea is use same key per view. that mean for all request it'll use same key to get request count data

from rest_framework import throttling

class MyViewRateThrottle(throttling.SimpleRateThrottle):
    rate = '3/m'

    def get_cache_key(self, request, view):
        return view.__class__.__name__

this will throttle per view. same as you're looking for

Upvotes: 1

Mahammadhusain kadiwala
Mahammadhusain kadiwala

Reputation: 3650

Here I created Throttling for specific user

throttling.py

from rest_framework.throttling import UserRateThrottle

class RockyRateThrottle(UserRateThrottle):
 scope = 'rocky'

settings.py

REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_RATES':{
        'anon': '2/day',     # For Anonymous user
        'user': '5/hour',    # For Registred user
        'rocky': '3/minute'  # For register but specific user
    }
}

views.py

from rest_framework.throttling import AnonRateThrottle, UserRateThrottle
from api.throttling import RockyRateThrottle


class StudentModelViewSet(viewsets.ModelViewSet):
  queryset = Student.objects.all()
  serializer_class = StudentSerializer
  authentication_classes=[SessionAuthentication]
  permission_classes=[IsAuthenticatedOrReadOnly]
  #  throttle_classes = [AnonRateThrottle, UserRateThrottle]
  throttle_classes = [AnonRateThrottle, RockyRateThrottle] # this is working for 'anon' and 'Rocky'

Upvotes: 0

Related Questions