aboutsummaryrefslogtreecommitdiffstats
path: root/rest_framework/throttling.py
diff options
context:
space:
mode:
authorDmitry Mukhin2014-08-20 20:04:48 +0400
committerDmitry Mukhin2014-08-20 20:04:48 +0400
commit3b07d0c9978335e183f369480618b48ff1e1b1ab (patch)
tree041027c50d2965da1be7f93b1a6360e07ad976f9 /rest_framework/throttling.py
parentc3891b6e00daa7a92cca1c88599e046f72926bb4 (diff)
parent59b47eac14778767a17e56bd8adc0610417f2878 (diff)
downloaddjango-rest-framework-3b07d0c9978335e183f369480618b48ff1e1b1ab.tar.bz2
Merge branch 'master' into set-retry-after
Conflicts: tests/test_throttling.py
Diffstat (limited to 'rest_framework/throttling.py')
-rw-r--r--rest_framework/throttling.py29
1 files changed, 25 insertions, 4 deletions
diff --git a/rest_framework/throttling.py b/rest_framework/throttling.py
index efa9fb94..361dbddf 100644
--- a/rest_framework/throttling.py
+++ b/rest_framework/throttling.py
@@ -18,6 +18,25 @@ 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 num_proxies is not None:
+ if num_proxies == 0 or xff is None:
+ return remote_addr
+ addrs = xff.split(',')
+ client_addr = addrs[-min(num_proxies, len(xff))]
+ return client_addr.strip()
+
+ return xff if xff else remote_addr
+
def wait(self):
"""
Optionally, return a recommended number of seconds to wait before
@@ -41,7 +60,7 @@ class SimpleRateThrottle(BaseThrottle):
cache = default_cache
timer = time.time
- cache_format = 'throtte_%(scope)s_%(ident)s'
+ cache_format = 'throttle_%(scope)s_%(ident)s'
scope = None
THROTTLE_RATES = api_settings.DEFAULT_THROTTLE_RATES
@@ -157,10 +176,12 @@ class AnonRateThrottle(SimpleRateThrottle):
ident = request.META.get('HTTP_X_FORWARDED_FOR')
if ident is None:
ident = request.META.get('REMOTE_ADDR')
+ else:
+ ident = ''.join(ident.split())
return self.cache_format % {
'scope': self.scope,
- 'ident': ident
+ 'ident': self.get_ident(request)
}
@@ -178,7 +199,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,
@@ -226,7 +247,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,