-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathratelimit.py
47 lines (35 loc) · 1.33 KB
/
ratelimit.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
from collections import deque
from functools import partial, wraps
import time
class RateLimited(RuntimeError):
pass
class RateLimit:
def __init__(self, max_calls, interval, clock=time.perf_counter):
self.max_calls = max_calls
self.interval = interval
self.clock = clock
self.calls = deque(maxlen=max_calls)
def cooldown(self, timestamp=None):
"""Return the remaining time until the rate limit resets."""
if timestamp is None:
timestamp = self.clock()
if len(self.calls) < self.max_calls:
return 0.0
current_interval = timestamp - self.calls[-1]
if current_interval > self.interval:
return 0.0
return self.interval - current_interval
def record_attempt(self):
"""Raise RateLimited, or do nothing."""
timestamp = self.clock()
cooldown = self.cooldown(timestamp)
if cooldown:
raise RateLimited(cooldown)
self.calls.append(timestamp)
def attempt(self, func, *args, **kwargs):
"""Call the function, or raise RateLimited."""
self.record_attempt()
return func(*args, **kwargs)
def __call__(self, func):
"""Allow this object to be used as a function wrapper or decorator."""
return wraps(func)(partial(self.attempt, func))