throttling.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. # Amend scope with optional bucket
  22. bucket = getattr(view, self.scope_attr + '_bucket', None)
  23. if bucket is not None:
  24. self.scope += ':' + bucket
  25. self.now = self.timer()
  26. self.num_requests, self.duration = zip(*self.parse_rate(self.rate))
  27. self.key = self.get_cache_key(request, view)
  28. self.history = {key: [] for key in self.key}
  29. self.history.update(self.cache.get_many(self.key))
  30. for num_requests, duration, key in zip(self.num_requests, self.duration, self.key):
  31. history = self.history[key]
  32. # Drop any requests from the history which have now passed the
  33. # throttle duration
  34. while history and history[-1] <= self.now - duration:
  35. history.pop()
  36. if len(history) >= num_requests:
  37. # Prepare variables used by the Throttle's wait() method that gets called by APIView.check_throttles()
  38. self.num_requests, self.duration, self.key, self.history = num_requests, duration, key, history
  39. response = self.throttle_failure()
  40. metrics.get('desecapi_throttle_failure').labels(request.method, self.scope, request.user.pk).inc()
  41. return response
  42. self.history[key] = history
  43. return self.throttle_success()
  44. def throttle_success(self):
  45. for key in self.history:
  46. self.history[key].insert(0, self.now)
  47. self.cache.set_many(self.history, max(self.duration))
  48. return True
  49. # Override the static attribute of the parent class so that we can dynamically apply override settings for testing
  50. @property
  51. def THROTTLE_RATES(self):
  52. return api_settings.DEFAULT_THROTTLE_RATES
  53. def get_cache_key(self, request, view):
  54. key = super().get_cache_key(request, view)
  55. return [f'{key}_{duration}' for duration in self.duration]