aboutsummaryrefslogtreecommitdiffstats
path: root/rest_framework/throttling.py
diff options
context:
space:
mode:
authorTom Christie2014-08-20 12:06:29 +0100
committerTom Christie2014-08-20 12:06:29 +0100
commit6ffc97c808f8026c063011e2d048604f3a6b70fa (patch)
tree93586ece6e50ab5ef6282ffd104e886ed48d9180 /rest_framework/throttling.py
parentf7b3e1e62b8e2c8bd1d1eb79a1cb0b3f4a0559a9 (diff)
parent874d2be83c612fb5e04aa6a28901c2afe4bf9d3b (diff)
downloaddjango-rest-framework-6ffc97c808f8026c063011e2d048604f3a6b70fa.tar.bz2
Merge pull request #1770 from tomchristie/2.4.0
2.4.0 Release.
Diffstat (limited to 'rest_framework/throttling.py')
-rw-r--r--rest_framework/throttling.py25
1 files changed, 22 insertions, 3 deletions
diff --git a/rest_framework/throttling.py b/rest_framework/throttling.py
index 91be9cfd..7e9f9d71 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
@@ -162,7 +181,7 @@ class AnonRateThrottle(SimpleRateThrottle):
return self.cache_format % {
'scope': self.scope,
- 'ident': ident
+ 'ident': self.get_ident(request)
}
@@ -180,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,
@@ -228,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,