我的用户需要非常高的节流阀,所以他们可以使用很多系统.是否有一种简单的方法可以让它们比其他用户更高的节流?
我环顾四周但没找到任何东西.
我找到了一种方法来扩展UserRateThrottle并将特殊用户添加到我的设置文件中.
这个类只是覆盖了该allow_request
方法,添加了一些特殊的逻辑来查看OVERRIDE_THROTTLE_RATES
变量中是否列出了用户名:
class ExceptionalUserRateThrottle(UserRateThrottle): def allow_request(self, request, view): """ Give special access to a few special accounts. Mirrors code in super class with minor tweaks. """ 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() # Adjust if user has special privileges. override_rate = settings.REST_FRAMEWORK['OVERRIDE_THROTTLE_RATES'].get( request.user.username, None, ) if override_rate is not None: self.num_requests, self.duration = self.parse_rate(override_rate) # Drop any requests from the history which have now passed the # throttle duration 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()
要使用它,只需将您设置DEFAULT_THROTTLE_CLASS
为此类,然后将一些特殊用户放入OVERRIDE_THROTTLE_RATES
:
'DEFAULT_THROTTLE_CLASSES': ( 'rest_framework.throttling.AnonRateThrottle', 'cl.api.utils.ExceptionalUserRateThrottle', ), 'DEFAULT_THROTTLE_RATES': { 'anon': '100/day', 'user': '1000/hour', }, 'OVERRIDE_THROTTLE_RATES': { 'scout': '10000/hour', 'scout_test': '10000/hour', },