Skip to content

Instantly share code, notes, and snippets.

@krsmedlund
Last active March 22, 2022 17:26
Show Gist options
  • Save krsmedlund/c8a9d8ba0f834498259f74443e6a7bd7 to your computer and use it in GitHub Desktop.
Save krsmedlund/c8a9d8ba0f834498259f74443e6a7bd7 to your computer and use it in GitHub Desktop.
ScopedRateThrottle per HTTP method.
class ScopedMethodRateThrottle(ScopedRateThrottle):
"""
If you need to set different throttles per different http method on the same view.
# Usage
## views.py
class MyView(SomeAPIView):
throttle_classes = [ScopedMethodRateThrottle,]
throttle_scope = {
"GET": "myapp.myview.get",
"POST": "myapp.myview.post",
"DELETE": "generic-delete-quota",
}
## settings.py
REST_FRAMEWORK = {
"DEFAULT_THROTTLE_RATES": {
"myapp.myview.get": "100/day",
"myapp.myview.post": "10/day",
"generic-delete-quota": "1/minute",
}
}
"""
def allow_request(self, request, view):
self.scope = getattr(view, self.scope_attr, dict()).get(request.method)
if not self.scope:
return True
self.rate = self.get_rate()
self.num_requests, self.duration = self.parse_rate(self.rate)
return super().allow_request(request, view)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment