实现限流器
您正在构建一个情感分析 API,用户可以分析文本的情感。为防止滥用,您需要实现限流:每个 API 密钥每分钟仅允许 5 次请求。RateLimiter 类已创建,您需要在 RateLimiter 类中补充 is_rate_limited 方法,用于检查在 1 分钟时间窗口内已发起的请求数量。
datetime 库中的 datetime 和 timedelta 类已预先导入。
本练习是课程的一部分
使用 FastAPI 在生产环境中部署 AI
练习说明
- 获取当前时间,并计算 1 分钟前的时间戳。
- 过滤请求列表,仅保留最近 1 分钟内的时间戳。
- 检查最近请求的数量是否超过限制。
交互式实操练习
通过完成这段示例代码来试试这个练习。
def is_rate_limited(self, api_key: str) -> bool:
# Get current time and the timestamp for one minute ago
now = _____
minute_ago = now - _____(minutes=1)
# Remove requests older than 1 minute
self.requests[api_key] = [
req_time for req_time in self.requests[api_key]
if req_time > _____]
# Check if no. of requests exceeded the set limit
if len(self.requests[api_key]) ____ self.requests_per_minute:
return True
self.requests[api_key].append(now)
return False