Last active
March 22, 2022 17:26
-
-
Save krsmedlund/c8a9d8ba0f834498259f74443e6a7bd7 to your computer and use it in GitHub Desktop.
ScopedRateThrottle per HTTP method.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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