简体   繁体   中英

Use Throttling to restrict the number of times a certain request can be made globally

I am using Django Throttling, and want to add a behavior that will throttle users from calling a certain request more than X times in rate - globally.

Using AnonRateThrottle or UserRateThrottle is not good enough for me, because it checks the number of times that a certain User or IP address made the request. I want to limit the global calls to a certain api_view, no matter who made the request.

For example, if the rate is 1/min and user X made a request, than every other user will be throttled for the next minute.

Here I created Throttling for specific user

throttling.py

from rest_framework.throttling import UserRateThrottle

class RockyRateThrottle(UserRateThrottle):
 scope = 'rocky'

settings.py

REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_RATES':{
        'anon': '2/day',     # For Anonymous user
        'user': '5/hour',    # For Registred user
        'rocky': '3/minute'  # For register but specific user
    }
}

views.py

from rest_framework.throttling import AnonRateThrottle, UserRateThrottle
from api.throttling import RockyRateThrottle


class StudentModelViewSet(viewsets.ModelViewSet):
  queryset = Student.objects.all()
  serializer_class = StudentSerializer
  authentication_classes=[SessionAuthentication]
  permission_classes=[IsAuthenticatedOrReadOnly]
  #  throttle_classes = [AnonRateThrottle, UserRateThrottle]
  throttle_classes = [AnonRateThrottle, RockyRateThrottle] # this is working for 'anon' and 'Rocky'

To apply throttle globally for view you can use same key. here idea is use same key per view. that mean for all request it'll use same key to get request count data

from rest_framework import throttling

class MyViewRateThrottle(throttling.SimpleRateThrottle):
    rate = '3/m'

    def get_cache_key(self, request, view):
        return view.__name__

this will throttle per view. same as you're looking for

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM