Search code examples
djangodjango-rest-frameworkthrottling

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()

Solution

  • 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