File tree Expand file tree Collapse file tree 2 files changed +43
-0
lines changed
Expand file tree Collapse file tree 2 files changed +43
-0
lines changed Original file line number Diff line number Diff line change 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
Original file line number Diff line number Diff line change 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
You can’t perform that action at this time.
0 commit comments