diff options
| author | Tom Christie | 2013-12-12 15:18:35 -0800 |
|---|---|---|
| committer | Tom Christie | 2013-12-12 15:18:35 -0800 |
| commit | d6d4621c4580ae4902fc895bdca78aced0ec7eab (patch) | |
| tree | dec9003eacb39906dffb7690640e0ebd694893f0 /rest_framework/throttling.py | |
| parent | 36046168b62967f815e328402fcf2afad21c69fb (diff) | |
| parent | 23db6c98495d7b3c18a3069c6cb770d5cbc18ee1 (diff) | |
| download | django-rest-framework-d6d4621c4580ae4902fc895bdca78aced0ec7eab.tar.bz2 | |
Merge pull request #1273 from kahnjw/add_get_ident_method_to_base_throttle
Add get_ident method to base throttle class
Diffstat (limited to 'rest_framework/throttling.py')
| -rw-r--r-- | rest_framework/throttling.py | 25 |
1 files changed, 18 insertions, 7 deletions
diff --git a/rest_framework/throttling.py b/rest_framework/throttling.py index a946d837..60e46d47 100644 --- a/rest_framework/throttling.py +++ b/rest_framework/throttling.py @@ -18,6 +18,21 @@ class BaseThrottle(object): """ raise NotImplementedError('.allow_request() must be overridden') + def get_ident(self, request): + """ + Identify the machine making the request by parsing HTTP_X_FORWARDED_FOR + if present and number of proxies is > 0. If not use all of + HTTP_X_FORWARDED_FOR if it is available, if not use REMOTE_ADDR. + """ + xff = request.META.get('HTTP_X_FORWARDED_FOR') + remote_addr = request.META.get('REMOTE_ADDR') + num_proxies = api_settings.NUM_PROXIES + + if xff and num_proxies: + return xff.split(',')[-min(num_proxies, len(xff))].strip() + + return xff if xff else remote_addr + def wait(self): """ Optionally, return a recommended number of seconds to wait before @@ -152,13 +167,9 @@ class AnonRateThrottle(SimpleRateThrottle): if request.user.is_authenticated(): return None # Only throttle unauthenticated requests. - ident = request.META.get('HTTP_X_FORWARDED_FOR') - if ident is None: - ident = request.META.get('REMOTE_ADDR') - return self.cache_format % { 'scope': self.scope, - 'ident': ident + 'ident': self.get_ident(request) } @@ -176,7 +187,7 @@ class UserRateThrottle(SimpleRateThrottle): if request.user.is_authenticated(): ident = request.user.id else: - ident = request.META.get('REMOTE_ADDR', None) + ident = self.get_ident(request) return self.cache_format % { 'scope': self.scope, @@ -224,7 +235,7 @@ class ScopedRateThrottle(SimpleRateThrottle): if request.user.is_authenticated(): ident = request.user.id else: - ident = request.META.get('REMOTE_ADDR', None) + ident = self.get_ident(request) return self.cache_format % { 'scope': self.scope, |
