throttling.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. from rest_framework import throttling
  2. from rest_framework.settings import api_settings
  3. from desecapi import metrics
  4. class ScopedRatesThrottle(throttling.ScopedRateThrottle):
  5. """
  6. Like DRF's ScopedRateThrottle, but supports several rates per scope, e.g. for burst vs. sustained limit.
  7. """
  8. def parse_rate(self, rates):
  9. return [super(ScopedRatesThrottle, self).parse_rate(rate) for rate in rates]
  10. def allow_request(self, request, view):
  11. # We can only determine the scope once we're called by the view.
  12. self.scope = getattr(view, self.scope_attr, None)
  13. # If a view does not have a `throttle_scope` always allow the request
  14. if not self.scope:
  15. return True
  16. # Determine the allowed request rate as we normally would during
  17. # the `__init__` call.
  18. self.rate = self.get_rate()
  19. if self.rate is None:
  20. return True
  21. self.now = self.timer()
  22. self.num_requests, self.duration = zip(*self.parse_rate(self.rate))
  23. self.key = self.get_cache_key(request, view)
  24. self.history = {key: [] for key in self.key}
  25. self.history.update(self.cache.get_many(self.key))
  26. for num_requests, duration, key in zip(self.num_requests, self.duration, self.key):
  27. history = self.history[key]
  28. # Drop any requests from the history which have now passed the
  29. # throttle duration
  30. while history and history[-1] <= self.now - duration:
  31. history.pop()
  32. if len(history) >= num_requests:
  33. # Prepare variables used by the Throttle's wait() method that gets called by APIView.check_throttles()
  34. self.num_requests, self.duration, self.key, self.history = num_requests, duration, key, history
  35. response = self.throttle_failure()
  36. metrics.get('desecapi_throttle_failure').labels(request.method, self.scope, request.user.pk).inc()
  37. return response
  38. self.history[key] = history
  39. return self.throttle_success()
  40. def throttle_success(self):
  41. for key in self.history:
  42. self.history[key].insert(0, self.now)
  43. self.cache.set_many(self.history, max(self.duration))
  44. return True
  45. # Override the static attribute of the parent class so that we can dynamically apply override settings for testing
  46. @property
  47. def THROTTLE_RATES(self):
  48. return api_settings.DEFAULT_THROTTLE_RATES
  49. def get_cache_key(self, request, view):
  50. key = super().get_cache_key(request, view)
  51. return [f'{key}_{duration}' for duration in self.duration]