If you are using rate limiting with Django Rest Framework you probably already know that
it provides some pretty simple methods for setting global rate limits
You can also set rate limits for specific views using the
throttle_classes property on class-based views
@throttle_classes decorator for function based views.
What if you are using
ViewSets but want different throttling rules to apply to different actions? Unfortunately
DRF provides no official method of doing this. Luckily we can accomplish this functionality without too much fuss.
The solution comes from combining the ScopedRateThrottle
throttle class with the
get_throttles() method of
ViewSet let's override the
What we are doing here is pretty simple: checking to see if the action being performed is one we want to throttle , and if so,
throttle_scope property on the
This alone won't do anything (in fact it will error) so let's add the necessary config to
settings.py to make it work:
The magic is contained within the ScopedRateThrottle.
This class will look for the
throttle_scope property on the view, and if found, look up a corresponding key in the
Notice that the keys are namespaced with
.foo. This isn't necessary, but if you're using more than one
ViewSet and you don't
want the rules to apply to all of them, you should namespace them.
There you have it, throttling for