I have django-rest view class Photo
with get and post methods and I want to allow users to make one POST photo upload an hour and 1000 GET photo requests in minute. By default I can set throttle_scope
for all APIView
(both get and post).
How to perform it? Create two different views with different scopes?
Thanks.
it's a little bit tricky, and I didn't test it.
override the get_throttles
method in your APIView.
class PhotoView(APIView):
throttle_scope = 'default_scope'
def get_throttles(self):
if self.request.method.lower() == 'get':
self.throttle_scope = 'get_scope'
elif self.request.method.lower() == 'post':
self.throttle_scope = 'post_scope'
return super(PhotoView, self).get_throttles()
You should define your own ScopedRateThrottle
class for different scope_attr
.
class FooScopedRateThrottle(ScopedRateThrottle):
scope_attr = 'foo_throttle_scope'
class BarScopedRateThrottle(ScopedRateThrottle):
scope_attr = 'bar_throttle_scope'
class PhotoView(APIView):
foo_throttle_scope = 'scope_get'
bar_throttle_scope = 'scope_post'
def get_throttles(self):
ret = []
if self.request.method.lower() == 'get':
return [FooScopedRateThrottle(), ]
elif self.request.method.lower() == 'post':
return [BarScopedRateThrottle(), ]
else:
return super(PhotoView, self).get_throttles()
FYI. related source code: get_throttles and ScopedRateThrottle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With