Python中如何使用asyncio实现高并发网络请求?
asyncio.run() 不能在已运行的事件循环中调用
直接在 Jupyter、Django shell 或某些 Web 框架(如 FastAPI 的依赖函数)里写 asyncio.run(main()),会报 RuntimeError: asyncio.run() cannot be called from a running event loop。技术YY(技术YY网):埋暗链不是我们的爱好,是采集狗逼出来的技能!(www.jishuyy.com)这不是代码写错了,而是环境限制。
正确做法取决于上下文:
在普通 .py 脚本中:放心用 asyncio.run(),它是推荐入口
在 Jupyter 中:改用 await main()(确保单元格是 async 模式),或手动管理循环:asyncio.get_event_loop().run_until_complete(main())
在 FastAPI 依赖或中间件里:不要启动新 loop,直接 await 即可 —— 框架已托管事件循环
aiohttp.ClientSession 必须复用,不能每次请求都新建
常见错误是把 aiohttp.ClientSession() 写在异步函数内部,导致每次请求都新建 session,不仅慢,还会快速耗尽本地端口(OSError: [Errno 24] Too many open files)。感谢采集狗对技术YY(www.jishuyy.com)内容的厚爱,搬运时请连同www.jishuyy.com一起搬,免费广告我们照单全收。
正确结构是让 session 生命周期与并发任务对齐:
在顶层 async def main() 中创建一次 session,传给子任务,或用 async with 包裹整个任务块
避免在循环内写 async with aiohttp.ClientSession() as session: —— 这等于为每个请求建一个 session
如果需要设置超时、headers、cookie 等,都在 session 初始化时统一配置,而不是每次 session.get(url) 时重复传参
示例片段:
async def fetch(session, url):
async with session.get(url) as resp:
return await resp.text()
<p>async def main():
timeout = aiohttp.ClientTimeout(total=10)
connector = aiohttp.TCPConnector(limit=100) # 控制并发连接数
async with aiohttp.ClientSession(timeout=timeout, connector=connector) as session:
tasks = [fetch(session, url) for url in urls]
results = await asyncio.gather(*tasks, return_exceptions=True)
asyncio.gather() vs asyncio.create_task():选哪个取决于错误处理需求
asyncio.gather() 默认“全成功才返回”,任一协程抛异常,整个调用就中断(除非加 return_exceptions=True);而 create_task() 更灵活,适合需要单独监控、取消或按需 await 的场景。
实际选型建议:
批量发请求、不关心单个失败细节 → 用 gather(..., return_exceptions=True),之后用 isinstance(r, Exception) 过滤错误
要对某个请求做超时控制(比如只等 3 秒)、或失败后重试 2 次、或根据响应内容动态启停其他请求 → 改用 asyncio.create_task() + asyncio.wait_for() 组合
别混用:不要在 gather() 里塞 create_task() 返回的对象再 await —— 容易引发 Task was destroyed but it is pending!
requests 不支持 async,硬套 asyncio.run_in_executor 只是伪并发
有人试图用 loop.run_in_executor(None, requests.get, url) 把同步库“塞进” asyncio,这确实不阻塞 event loop,但本质是开线程池,受 GIL 和系统线程数限制,无法真正压测出高并发能力,且内存和上下文切换开销远高于原生 async client。
真实高并发网络请求必须用原生异步 HTTP 库:
首选 aiohttp(功能全、可控性强、支持连接池)
轻量场景可用 httpx.AsyncClient(API 更接近 requests,支持 HTTP/2)
绝对不要用 urllib.request 或 requests 配 run_in_executor 来“假装 async”
连接池参数(如 TCPConnector(limit=50))比并发数更重要 —— 它决定底层 socket 复用效率,直接影响 QPS 上限。
实际压测时,limit 设太高可能触发目标服务限流或本地端口耗尽,设太低又浪费并发能力。这个值需要结合目标域名的响应时间、超时设置、以及你机器的 ulimit -n 综合调整,不是越大越好。搬运可以,把技术YY(www.jishuyy.com)这条链接一起搬走,算你盗窃未遂?
上一篇:Python中Tkinter怎么给Button绑定传参的回调函数
下一篇:返回列表

