速率限制python装饰器

速率限制python装饰器,python,algorithm,decorator,python-decorators,rate-limiting,Python,Algorithm,Decorator,Python Decorators,Rate Limiting,我发现了基于redis类的速率限制python decorator。我如何编写一个类似的装饰器,它只使用标准库中可用的、可按如下方式使用的内容 def ratelimit(limit, every): # You can use a threading.Semaphore to count and block the requests that are exceeding the limit, in combination with threading.Timer to schedule

我发现了基于redis类的速率限制python decorator。我如何编写一个类似的装饰器,它只使用标准库中可用的、可按如下方式使用的内容

def ratelimit(limit, every):
    # You can use a 
threading.Semaphore
to count and block the requests that are exceeding the limit, in combination with
threading.Timer
to schedule a function that releases the 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
def rate limit(限制,每个):
#您可以使用来统计和阻止超出限制的请求,并结合调度释放信号量的函数


我扩展了这个想法,并在PyPI上发布了一个名为的库。

如果包装函数引发异常,则不会释放信号量。您可以使用
try..finally
子句来确保发生这种情况。