python限制调用接口速度

复制代码
import time
import requests
import pandas as pd
from concurrent.futures import ThreadPoolExecutor


class RateLimiter:
    def __init__(self, max_calls, period):
        self.max_calls = max_calls
        self.period = period
        self.calls = 0
        self.reset_time = time.time()

    def can_call(self):
        current_time = time.time()
        if current_time - self.reset_time > self.period:
            self.reset_time = current_time
            self.calls = 0
        return self.calls < self.max_calls

    def called(self):
        self.calls += 1

在这里,RateLimiter类通过在指定时间段内限制最大调用次数来实现速率限制。构造函数__init__接受两个参数:max_calls表示最大调用次数,period表示时间段(以秒为单位)。

类中的can_call方法用于判断是否可以进行调用。它首先检查当前时间与上次重置时间之间的时间差是否超过设定的时间段。如果超过了时间段,则重置计数器,并更新重置时间和调用次数。最后,判断调用次数是否小于最大调用次数,如果是则返回True,表示可以进行调用;否则返回False,表示已经达到限制。

called方法用于在每次调用后更新调用次数。当函数或接口被调用时,应该在合适的位置调用called方法,以便在限制内适当增加调用次数。

这种速率限制器通常用于控制对外部API的访问次数,以免超出API提供商的规定限制。它能够平滑地限制请求速率,避免因短时间内大量请求而导致服务崩溃或被封禁。

相关推荐
阿尔的代码屋1 小时前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
AI探索者18 小时前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者18 小时前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh20 小时前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅20 小时前
Python函数入门详解(定义+调用+参数)
python
曲幽21 小时前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时1 天前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
哈里谢顿1 天前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780512 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng82 天前
Python+Django+H5+MySQL项目搭建
python·django