From 52298480c2966b0a155a1e564fd2f1f594a50cae Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 14 Jun 2013 15:39:56 +0100 Subject: [PATCH] Clean up --- rest_framework/throttling.py | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/rest_framework/throttling.py b/rest_framework/throttling.py index ec9c80ffd..f6bb1cc84 100644 --- a/rest_framework/throttling.py +++ b/rest_framework/throttling.py @@ -188,16 +188,24 @@ class ScopedRateThrottle(SimpleRateThrottle): scope_attr = 'throttle_scope' def __init__(self): + # Override the usual SimpleRateThrottle, because we can't determine + # the rate until called by the view. pass def allow_request(self, request, view): + # We can only determine the scope once we're called by the view. self.scope = getattr(view, self.scope_attr, None) + # If a view does not have a `throttle_scope` always allow the request if not self.scope: return True + # Determine the allowed request rate as we normally would during + # the `__init__` call. self.rate = self.get_rate() self.num_requests, self.duration = self.parse_rate(self.rate) + + # We can now proceed as normal. return super(ScopedRateThrottle, self).allow_request(request, view) def get_cache_key(self, request, view): @@ -207,18 +215,12 @@ class ScopedRateThrottle(SimpleRateThrottle): Otherwise generate the unique cache key by concatenating the user id with the '.throttle_scope` property of the view. """ - scope = getattr(view, self.scope_attr, None) - - if not scope: - # Only throttle views if `.throttle_scope` is set on the view. - return None - if request.user.is_authenticated(): ident = request.user.id else: ident = request.META.get('REMOTE_ADDR', None) return self.cache_format % { - 'scope': scope, + 'scope': self.scope, 'ident': ident }