设计一个装饰器,限制函数的调用频率(例如每秒最多调用5次),如果超出限制则抛出异常。
import time
from functools import wraps
# 定义一个装饰器,用于限制函数的调用频率
def rate_limit(max_calls, per_seconds):
"""
:param max_calls: 允许的最大调用次数
:param per_seconds: 时间间隔(秒)
"""
def decorator(func):
# 使用列表存储每次调用的时间戳
call_history = []
@wraps(func)
def wrapper(*args, **kwargs):
nonlocal call_history
current_time = time.time()
# 移除超出时间范围的时间戳
call_history = [t for t in call_history if current_time - t < per_seconds]
if len(call_history) >= max_calls:
raise Exception(f"Rate limit exceeded: {max_calls} calls per {per_seconds} seconds")
# 记录当前调用时间
call_history.append(current_time)
return func(*args, **kwargs)
return wrapper
return decorator
# 示例:使用装饰器限制函数调用频率
@rate_limit(max_calls=5, per_seconds=1)
def print_hello(name):
print(f"Hello, {name}!")
# 测试装饰器效果
for i in range(10):
try:
print_hello(f"User_{i}")
except Exception as e:
print(f"Error: {e}")
time.sleep(0.2) # 模拟函数的快速调用
# 输出结果可能如下:
# Hello, User_0!
# Hello, User_1!
# Hello, User_2!
# Hello, User_3!
# Hello, User_4!
# Error: Rate limit exceeded: 5 calls per 1 seconds
# Hello, User_6!
# Hello, User_7!
# Hello, User_8!
# Hello, User_9!
详细说明
-
装饰器定义:
- 装饰器
rate_limit接受两个参数:max_calls(允许的最大调用次数)和per_seconds(时间间隔,以秒为单位)。 - 内部定义了一个
decorator函数,用于实际装饰目标函数。 - 使用
call_history列表存储每次函数调用的时间戳。
- 装饰器
-
时间戳管理:
- 在
wrapper函数中,首先获取当前时间戳current_time。 - 过滤
call_history,移除所有超过per_seconds时间范围的时间戳。
- 在
-
频率检查:
- 如果当前
call_history的长度超过max_calls,则抛出异常,提示调用频率超出限制。 - 如果未超出限制,则将当前时间戳添加到
call_history,并调用目标函数。
- 如果当前
-
示例演示:
- 装饰器应用于
print_hello函数,限制每秒最多调用5次。 - 在循环中快速调用函数,并通过
try-except捕获异常。 - 调用间隔为0.2秒,因此前5次调用成功,第6次抛出异常。
- 装饰器应用于
-
灵活性:
- 可以通过调整
max_calls和per_seconds参数,自定义频率限制规则。
- 可以通过调整
-
线程安全:
- 目前实现是非线程安全的,如果在多线程环境中使用,需要额外加锁机制。
-
适用场景:
- 适用于需要限制API调用频率、防止恶意请求或资源过度消耗的场景。
扩展思考
如果需要支持异步函数的频率限制,可以类似地实现一个异步装饰器,结合asyncio库来管理时间戳和调用频率。同时,线程安全版本可以通过threading.Lock实现。