Skip to content

Commit 7197d11

Browse files
authored
Merge pull request #7 from sodrooome/feature-2
add simple rate throttle
2 parents 8a3927f + 5f03f11 commit 7197d11

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

src/throttle/simple_throttle.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import time
2+
from rest_framework.settings import api_settings
3+
from django.core.exceptions import ImproperlyConfigured
4+
5+
class SimpleRateThrottle(BaseThrottle):
6+
cache = default_cache
7+
timer = time.time
8+
cache_format = 'throttle_%(scope)s_%(ident)s'
9+
scope = None
10+
THROTTLE_RATES = api_settings.DEFAULT_THROTTLE_RATES
11+
12+
def __init__(self):
13+
if not getattr(self, 'rate', None):
14+
self.rate = self.get_rate()
15+
self.num_requests, self.duration = self.parse_rate(self.rate)
16+
17+
def get_cache_key(self, request, view):
18+
raise NotImplementedError('.get_cache_key() must be overridden')
19+
20+
def get_rate(self):
21+
if not getattr(self, 'scope', None):
22+
msg = ("You must set either `.scope` or `.rate` for '%s' throttle" %
23+
self.__class__.__name__)
24+
raise ImproperlyConfigured(msg)
25+
26+
try:
27+
return self.THROTTLE_RATES[self.scope]
28+
except KeyError:
29+
msg = "No default throttle rate set for '%s' scope" % self.scope
30+
raise ImproperlyConfigured(msg)

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy