Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django REST POST and GET different throttle scopes

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.

like image 603
foo Avatar asked Mar 16 '16 15:03

foo


1 Answers

Solution 1:

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

solution 2

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

like image 93
soooooot Avatar answered Jan 01 '23 07:01

soooooot