@@ -188,16 +188,24 @@ class ScopedRateThrottle(SimpleRateThrottle):
188
188
scope_attr = 'throttle_scope'
189
189
190
190
def __init__ (self ):
191
+ # Override the usual SimpleRateThrottle, because we can't determine
192
+ # the rate until called by the view.
191
193
pass
192
194
193
195
def allow_request (self , request , view ):
196
+ # We can only determine the scope once we're called by the view.
194
197
self .scope = getattr (view , self .scope_attr , None )
195
198
199
+ # If a view does not have a `throttle_scope` always allow the request
196
200
if not self .scope :
197
201
return True
198
202
203
+ # Determine the allowed request rate as we normally would during
204
+ # the `__init__` call.
199
205
self .rate = self .get_rate ()
200
206
self .num_requests , self .duration = self .parse_rate (self .rate )
207
+
208
+ # We can now proceed as normal.
201
209
return super (ScopedRateThrottle , self ).allow_request (request , view )
202
210
203
211
def get_cache_key (self , request , view ):
@@ -207,18 +215,12 @@ def get_cache_key(self, request, view):
207
215
Otherwise generate the unique cache key by concatenating the user id
208
216
with the '.throttle_scope` property of the view.
209
217
"""
210
- scope = getattr (view , self .scope_attr , None )
211
-
212
- if not scope :
213
- # Only throttle views if `.throttle_scope` is set on the view.
214
- return None
215
-
216
218
if request .user .is_authenticated ():
217
219
ident = request .user .id
218
220
else :
219
221
ident = request .META .get ('REMOTE_ADDR' , None )
220
222
221
223
return self .cache_format % {
222
- 'scope' : scope ,
224
+ 'scope' : self . scope ,
223
225
'ident' : ident
224
226
}
0 commit comments