在Python2.7中,如何使用修饰符对函数进行速率限制?

2024-05-15 11:13:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用Python编写一个decorator来限制函数在一段时间内被调用的次数。我希望这样使用它:

@ratelimit(seconds=15)
def foo():
    print 'hello'

start = time.time()
while time.time() - start < 10:
    foo()

> 'hello'
> 'hello'

因此修饰函数最多可以每seconds调用一次。关于实现它,我有这个方法,但它不起作用,因为我不确定在后续调用之间持久化last_call的正确方法:

^{pr2}$

Tags: 方法函数hellofootimedefdecorator次数
1条回答
网友
1楼 · 发布于 2024-05-15 11:13:37

下面的代码在Python2.7中运行得很好。在

import time
from functools import wraps

last_called = dict()  # When last called, and with what result

def ratelimit(seconds=10, timer=time.time):
    def decorator(func):
        last_called[func] = None

        @wraps(func)
        def wrapper(*args, **kwargs):
            now = timer()
            call_data = last_called.get(func, None)
            if call_data is None or now - call_data[0] >= seconds:
                result = func(*args, **kwargs)
                last_called[func] = (now, result)
            else:
                result = call_data[1]  # Replay rate-limited result
            return result
        return wrapper
    return decorator

相关问题 更多 >