Speed ​​limiter

I found this speed-limiting python decorator based on redis classes. How to write a similar decorator that uses only what is available in the standard library, which can be used as follows?

def ratelimit(limit, every): # 🐍 python magic 🐍 @ratelimit(limit=1, every=2) def printlimited(x): print x # print one number every two seconds for x in range(10): printlimited(x) 

There are other answers in stackoverflow, but they do not allow you to specify a denominator.

+6
source share
1 answer

You can use threading.Semaphore to count and block requests that exceed the limit, combined with threading.Timer to schedule a function that issues a semaphore.

 from threading import Semaphore, Timer from functools import wraps def ratelimit(limit, every): def limitdecorator(fn): semaphore = Semaphore(limit) @wraps(fn) def wrapper(*args, **kwargs): semaphore.acquire() try: return fn(*args, **kwargs) finally: # don't catch but ensure semaphore release timer = Timer(every, semaphore.release) timer.setDaemon(True) # allows the timer to be canceled on exit timer.start() return wrapper return limitdecorator 

I expanded this idea and published a library on PyPI called limit .

+8
source

All Articles