diff options
| author | markotibold | 2011-06-11 03:16:35 +0200 |
|---|---|---|
| committer | markotibold | 2011-06-11 03:16:35 +0200 |
| commit | f854bc9065e53882a83a7878cdaaace15e32acca (patch) | |
| tree | 372897d4a64124e3ab3b384dd9520b10740f11d2 /djangorestframework/permissions.py | |
| parent | 87db5fbda550e0dc1b808d1df30700bf2606c10d (diff) | |
| download | django-rest-framework-f854bc9065e53882a83a7878cdaaace15e32acca.tar.bz2 | |
* fixed `test_request_throttling_is_per_user` - it didn't make a request for the 2nd user
* implemented per_resource_throttling + test
needs refactoring
Diffstat (limited to 'djangorestframework/permissions.py')
| -rw-r--r-- | djangorestframework/permissions.py | 32 |
1 files changed, 32 insertions, 0 deletions
diff --git a/djangorestframework/permissions.py b/djangorestframework/permissions.py index a9b3f08b..b3fd212b 100644 --- a/djangorestframework/permissions.py +++ b/djangorestframework/permissions.py @@ -122,3 +122,35 @@ class PerUserThrottling(BasePermission): history.insert(0, now) cache.set(key, history, duration) + +class PerResourceThrottling(BasePermission): + """ + Rate throttling of requests on a per-resource basis. + + The rate (requests / seconds) is set by a :attr:`throttle` attribute on the ``View`` class. + The attribute is a two tuple of the form (number of requests, duration in seconds). + + The user id will be used as a unique identifier if the user is authenticated. + For anonymous requests, the IP address of the client will be used. + + Previous request information used for throttling is stored in the cache. + """ + + def check_permission(self, ignore): + (num_requests, duration) = getattr(self.view, 'throttle', (0, 0)) + + + key = 'throttle_%s' % self.view.__class__.__name__ + + history = cache.get(key, []) + now = time.time() + + # Drop any requests from the history which have now passed the throttle duration + while history and history[0] < now - duration: + history.pop() + + if len(history) >= num_requests: + raise _503_THROTTLED_RESPONSE + + history.insert(0, now) + cache.set(key, history, duration) |
