Different scope throttle limits depending on the type of user in the same action of a single API

21 Views Asked by At

I have categorized my multiple APIs in 5 different categories now I want that throttling limit of those APIs should not be common all across. I want different limits for type of user:

example: if it is user_1 scope throttling limits should {Category1: 100/hr; Category2: 100/min; Category3 : 10/hr; Category4: 10/min ;Category1: 20/sec;}
and if it is user_2 scope throttling limits should {Category1: 230/hr; Category2: 40/min; Category3 : 120/hr; Category4: 15/min ;Category1: 50/sec;}

I have tried multiple methods by creating custom class, creating dictionary and importing overring but nothing works. This is what I tried; have commented upperpart to make it distinguish:

from rest_framework.throttling import UserRateThrottle,ScopedRateThrottle
# from backend.settings.base import VIEWSET_CATEGORIES
from backend.settings.base import *

# class APIThrottle(ScopedRateThrottle):
#     def allow_request(self, request, view):
#         category = self.determine_category(view)
#         if category:
#             self.set_rate_limit(category)
#         return super().allow_request(request, view)

#     def determine_category(self, view):
#         viewset_path = f"{view.__module__}.{view.__class__.__name__}"
#         return VIEWSET_CATEGORIES.get(viewset_path)

#     def set_rate_limit(self, category):
#         self.scope = category
#         if category == 'category1':
#             self.rate = '5/hour'
#         elif category == 'category2':
#             self.rate = '10/hour'
class ExpectionUserRateThrottle(UserRateThrottle):
    def allow_request(self, request, view):
        if self.rate is None:
            return True
        
        self.key = self.get_cache_key(request, view)
        if self.key is None:
            return True
        
        self.history = self.cache.get(self.key, [])
        self.now = self.timer()
        
        override_rate = settings.REST_FRAMEWORK['OVER_THROTTLE_RATES'].get(
            request.user.username,
            None,)
        if override_rate is not None:
            self.num_requests, self.duration = self.parse_rate(override_rate)


        while self.history and self.history[-1] <= self.now - self.duration:
            self.history.pop()
        if len(self.history) >= self.num_requests:
            return self.throttle_failure()
        return self.throttle_success()
0

There are 0 best solutions below