You need to enable JavaScript to run this app. Python中带URL变量的最高效并行API请求实现咨询
优惠活动
大模型
产品
解决方案
定价
更多

Python中带URL变量的最高效并行API请求实现咨询

批量设备API请求最优实现方案

原有实现的核心问题

  • 串行for循环模式:每个请求等待上一个响应返回后才发起,总耗时为所有请求响应时间之和,无并发能力,设备数量越多耗时线性增长
  • 混合「asyncio+线程池+同步requests」模式:
    • 同步requests在线程中执行,需要和事件循环做上下文切换,额外性能开销高
    • 仅设置max_workers=5是限制同时在飞的请求数,无法实现「每秒固定5个请求」的QPS限流,遇到快速响应的场景会超出阈值触发429错误
    • 任务列表未绑定实际设备序列号,空跑20个无意义请求,完全不匹配业务逻辑
  • 原串行代码的429处理逻辑存在重复判断问题,可能触发无效重复请求

最优方案选型逻辑

  • 采用原生异步HTTP客户端替代混合线程池模式,无额外线程切换开销,并发性能更高
  • 实现时间窗口精准限流器,严格控制1秒内最多发起5个请求,完全匹配API限流要求
  • 完全对齐原有业务逻辑:保留429自动重试、错误打印、结果收集规则,入参出参结构和原getrequest函数完全一致,可直接替换不需要修改上层调用代码
  • 增加全局请求超时控制,避免单个请求挂死导致整个程序阻塞

可直接替换的代码实现

需提前安装异步HTTP客户端依赖:pip install aiohttp

import asyncio
import time
from aiohttp import ClientSession, ClientResponseError

# 严格每秒固定请求数的时间窗口限流器
class RateLimiter:
    def __init__(self, max_per_sec: int):
        self.max_per_sec = max_per_sec
        self.timestamps = []
        self.lock = asyncio.Lock()

    async def acquire(self):
        async with self.lock:
            now = time.time()
            # 清理1秒外的过期请求时间戳
            self.timestamps = [t for t in self.timestamps if now - t < 1]
            # 达到当前窗口请求上限时,等待最早的时间戳满1秒后再放行
            if len(self.timestamps) >= self.max_per_sec:
                wait_time = 1 - (now - self.timestamps[0])
                if wait_time > 0:
                    await asyncio.sleep(wait_time)
                # 等待完成后重新清理过期时间戳
                now = time.time()
                self.timestamps = [t for t in self.timestamps if now - t < 1]
            # 记录本次请求的发起时间
            self.timestamps.append(now)

# 单设备请求逻辑,含429自动重试
async def fetch_device_info(session: ClientSession, rate_limiter: RateLimiter, device_info: list):
    serial = device_info[1]
    url = f"https://api.test.com/{serial}"
    while True:
        await rate_limiter.acquire()
        try:
            async with session.get(url) as resp:
                if resp.status == 200:
                    return await resp.json()
                # 遇到429状态码时,按返回头的Retry-After值等待后重试
                if resp.status == 429:
                    retry_after = int(resp.headers.get("Retry-After", 1))
                    await asyncio.sleep(retry_after)
                    continue
                # 其他状态码抛出异常
                raise ClientResponseError(
                    resp.request_info,
                    resp.history,
                    status=resp.status,
                    message=f"Unexpected status {resp.status}",
                )
        except Exception as e:
            # 对齐原有错误打印逻辑
            print('ERROR 01: Unable to contact')
            if hasattr(e, "status"):
                print(f"API response: {e.status}")
            else:
                print("API response: Network connection error")
            return None

# 替换原有getrequest的主函数,入参出参和原函数完全一致
def getrequest(devser: list):
    # 初始化限流器:每秒最多5个请求
    rate_limiter = RateLimiter(max_per_sec=5)
    dlist = []

    async def _run_all_tasks():
        # 设置单请求10秒超时,避免程序挂死
        async with ClientSession(timeout=10) as session:
            # 为每台设备创建独立异步任务,但实际发起节奏受流控器限制
            tasks = [fetch_device_info(session, rate_limiter, device) for device in devser]
            results = await asyncio.gather(*tasks)
            # 过滤请求失败的空结果
            dlist.extend([res for res in results if res is not None])

    asyncio.run(_run_all_tasks())
    return dlist

实现效果说明

  • 耗时优化:以12台设备为例,总耗时基本等于单台设备的最大响应时间,相比串行实现耗时下降90%以上
  • 限流精度:严格按照每秒5个请求的节奏发起,虽然为每台设备创建了独立异步任务,但实际请求发起节奏完全受限于流控器,不会一次性发起全部请求触发API封禁,从根源上减少429触发概率
  • 兼容原有逻辑:入参直接传入原设备嵌套列表即可,出参为收集到的设备信息字典列表,和原函数返回结构完全一致,不需要修改上层调用代码
  • 异常容错:单个设备请求失败不会中断整个批量任务,会直接打印错误日志并跳过,不影响其他设备的请求处理

内容的提问来源于stack exchange,提问作者user5940357

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.17 17:54:03