Skip to content

Commit a4b87ac

Browse files
author
manas-shinde
committed
feat : Added new decorator - rate_limiter.
1 parent aeb56d8 commit a4b87ac

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

decorators/rate_limiter.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import time
2+
import threading
3+
import functools
4+
5+
6+
def rate_limiter(calls_per_second):
7+
interval = 1 / calls_per_second
8+
lock = threading.Lock()
9+
last_called = [0.0]
10+
11+
def decorator(func):
12+
@functools.wraps(func)
13+
def wrapper(*args, **kwargs):
14+
with lock:
15+
now = time.time()
16+
wait = interval - (now - last_called[0])
17+
if wait > 0:
18+
time.sleep(wait)
19+
last_called[0] = time.time()
20+
return func(*args, **kwargs)
21+
return wrapper
22+
return decorator

tests/test_rate_limiter.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import time
2+
from decorators.rate_limiter import rate_limiter
3+
4+
calls = []
5+
6+
7+
# Max 2 calls per second = 0.5s delay between calls
8+
@rate_limiter(calls_per_second=2)
9+
def limited_func(x):
10+
calls.append(time.time())
11+
return x * 2
12+
13+
14+
def test_rate_limiter_timing():
15+
calls.clear()
16+
for i in range(3):
17+
limited_func(i)
18+
19+
assert len(calls) == 3
20+
assert (calls[1] - calls[0]) >= 0.49
21+
assert (calls[2] - calls[1]) >= 0.49

0 commit comments

Comments
 (0)