我找到了基于 redis 类的this速率限制python装饰器。如何编写一个类似的装饰器,它只使用标准库中可用的内容,如下所示?
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)
stackoverflow上还有其他answers,但它们不允许指定分母。
答案 0 :(得分:8)
您可以使用threading.Semaphore
来计算和阻止超出限制的请求,并结合threading.Timer
来安排释放信号量的函数。
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