Debian Codegraph @

rest_framework/throttling.py

raw
1 """
2 Provides various throttling policies.
3 """
4 import time
5
6 from django.core.cache import cache as default_cache
7 from django.core.exceptions import ImproperlyConfigured
8
9 from rest_framework.settings import api_settings
10
11
12 class BaseThrottle:
13 """
14 Rate throttling of requests.
15 """
16
17 def allow_request(self, request, view):
18 """
19 Return `True` if the request should be allowed, `False` otherwise.
20 """
21 raise NotImplementedError('.allow_request() must be overridden')
22
23 def get_ident(self, request):
24 """
25 Identify the machine making the request by parsing HTTP_X_FORWARDED_FOR
26 if present and number of proxies is > 0. If not use all of
27 HTTP_X_FORWARDED_FOR if it is available, if not use REMOTE_ADDR.
28 """
29 xff = request.headers.get('x-forwarded-for')
30 remote_addr = request.META.get('REMOTE_ADDR')
31 num_proxies = api_settings.NUM_PROXIES
32
33 if num_proxies is not None:
34 if num_proxies == 0 or xff is None:
35 return remote_addr
36 addrs = xff.split(',')
37 client_addr = addrs[-min(num_proxies, len(addrs))]
38 return client_addr.strip()
39
40 return ''.join(xff.split()) if xff else remote_addr
41
42 def wait(self):
43 """
44 Optionally, return a recommended number of seconds to wait before
45 the next request.
46 """
47 return None
48
49
50 class SimpleRateThrottle(BaseThrottle):
51 """
52 A simple cache implementation, that only requires `.get_cache_key()`
53 to be overridden.
54
55 The rate (requests / seconds) is set by a `rate` attribute on the Throttle
56 class. The attribute is a string of the form 'number_of_requests/period'.
57
58 Period should be one of: ('s', 'sec', 'm', 'min', 'h', 'hour', 'd', 'day')
59
60 Previous request information used for throttling is stored in the cache.
61 """
62 cache = default_cache
63 timer = time.time
64 cache_format = 'throttle_%(scope)s_%(ident)s'
65 scope = None
66 THROTTLE_RATES = api_settings.DEFAULT_THROTTLE_RATES
67
68 def __init__(self):
69 if not getattr(self, 'rate', None):
70 self.rate = self.get_rate()
71 self.num_requests, self.duration = self.parse_rate(self.rate)
72
73 def get_cache_key(self, request, view):
74 """
75 Should return a unique cache-key which can be used for throttling.
76 Must be overridden.
77
78 May return `None` if the request should not be throttled.
79 """
80 raise NotImplementedError('.get_cache_key() must be overridden')
81
82 def get_rate(self):
83 """
84 Determine the string representation of the allowed request rate.
85 """
86 if not getattr(self, 'scope', None):
87 msg = ("You must set either `.scope` or `.rate` for '%s' throttle" %
88 self.__class__.__name__)
89 raise ImproperlyConfigured(msg)
90
91 try:
92 return self.THROTTLE_RATES[self.scope]
93 except KeyError:
94 msg = "No default throttle rate set for '%s' scope" % self.scope
95 raise ImproperlyConfigured(msg)
96
97 def parse_rate(self, rate):
98 """
99 Given the request rate string, return a two tuple of:
100 <allowed number of requests>, <period of time in seconds>
101 """
102 if rate is None:
103 return (None, None)
104 num, period = rate.split('/')
105 num_requests = int(num)
106 duration = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400}[period[0]]
107 return (num_requests, duration)
108
109 def allow_request(self, request, view):
110 """
111 Implement the check to see if the request should be throttled.
112
113 On success calls `throttle_success`.
114 On failure calls `throttle_failure`.
115 """
116 if self.rate is None:
117 return True
118
119 self.key = self.get_cache_key(request, view)
120 if self.key is None:
121 return True
122
123 self.history = self.cache.get(self.key, [])
124 self.now = self.timer()
125
126 # Drop any requests from the history which have now passed the
127 # throttle duration
128 while self.history and self.history[-1] <= self.now - self.duration:
129 self.history.pop()
130 if len(self.history) >= self.num_requests:
131 return self.throttle_failure()
132 return self.throttle_success()
133
134 def throttle_success(self):
135 """
136 Inserts the current request's timestamp along with the key
137 into the cache.
138 """
139 self.history.insert(0, self.now)
140 self.cache.set(self.key, self.history, self.duration)
141 return True
142
143 def throttle_failure(self):
144 """
145 Called when a request to the API has failed due to throttling.
146 """
147 return False
148
149 def wait(self):
150 """
151 Returns the recommended next request time in seconds.
152 """
153 if self.history:
154 remaining_duration = self.duration - (self.now - self.history[-1])
155 else:
156 remaining_duration = self.duration
157
158 available_requests = self.num_requests - len(self.history) + 1
159 if available_requests <= 0:
160 return None
161
162 return remaining_duration / float(available_requests)
163
164
165 class AnonRateThrottle(SimpleRateThrottle):
166 """
167 Limits the rate of API calls that may be made by a anonymous users.
168
169 The IP address of the request will be used as the unique cache key.
170 """
171 scope = 'anon'
172
173 def get_cache_key(self, request, view):
174 if request.user and request.user.is_authenticated:
175 return None # Only throttle unauthenticated requests.
176
177 return self.cache_format % {
178 'scope': self.scope,
179 'ident': self.get_ident(request)
180 }
181
182
183 class UserRateThrottle(SimpleRateThrottle):
184 """
185 Limits the rate of API calls that may be made by a given user.
186
187 The user id will be used as a unique cache key if the user is
188 authenticated. For anonymous requests, the IP address of the request will
189 be used.
190 """
191 scope = 'user'
192
193 def get_cache_key(self, request, view):
194 if request.user and request.user.is_authenticated:
195 ident = request.user.pk
196 else:
197 ident = self.get_ident(request)
198
199 return self.cache_format % {
200 'scope': self.scope,
201 'ident': ident
202 }
203
204
205 class ScopedRateThrottle(SimpleRateThrottle):
206 """
207 Limits the rate of API calls by different amounts for various parts of
208 the API. Any view that has the `throttle_scope` property set will be
209 throttled. The unique cache key will be generated by concatenating the
210 user id of the request, and the scope of the view being accessed.
211 """
212 scope_attr = 'throttle_scope'
213
214 def __init__(self):
215 # Override the usual SimpleRateThrottle, because we can't determine
216 # the rate until called by the view.
217 pass
218
219 def allow_request(self, request, view):
220 # We can only determine the scope once we're called by the view.
221 self.scope = getattr(view, self.scope_attr, None)
222
223 # If a view does not have a `throttle_scope` always allow the request
224 if not self.scope:
225 return True
226
227 # Determine the allowed request rate as we normally would during
228 # the `__init__` call.
229 self.rate = self.get_rate()
230 self.num_requests, self.duration = self.parse_rate(self.rate)
231
232 # We can now proceed as normal.
233 return super().allow_request(request, view)
234
235 def get_cache_key(self, request, view):
236 """
237 If `view.throttle_scope` is not set, don't apply this throttle.
238
239 Otherwise generate the unique cache key by concatenating the user id
240 with the `.throttle_scope` property of the view.
241 """
242 if request.user and request.user.is_authenticated:
243 ident = request.user.pk
244 else:
245 ident = self.get_ident(request)
246
247 return self.cache_format % {
248 'scope': self.scope,
249 'ident': ident
250 }