This commit is contained in:
Tom Christie 2013-06-14 15:39:56 +01:00
parent df957c8625
commit 52298480c2

View File

@ -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
}