You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python AIOHTTP Web服务器无法同时处理多个请求的问题

aiohttp无法同时处理多连接的原因及解决办法

核心问题出在同步阻塞代码time.sleep(10),哪怕你尝试用async def定义处理函数,只要函数里存在这种阻塞操作,aiohttp的事件循环就会被彻底卡住。

为什么会这样?

aiohttp是基于异步IO的Web框架,靠事件循环实现并发处理。事件循环的工作逻辑是:当任务遇到await标记的异步操作时,会暂时挂起当前任务,转而处理队列里的其他任务。但time.sleep()是同步阻塞调用,它会占用整个线程的执行时间,在这10秒里事件循环完全无法处理新的请求,必须等当前请求的sleep结束,才能轮到下一个请求执行。

修正方案

把同步的time.sleep(10)替换成异步的await asyncio.sleep(10),同时确保处理函数是async def定义的,并且正确await异步操作:

import asyncio
from aiohttp import web

async def testF(request):
    print('Called')
    await asyncio.sleep(10)  # 替换为异步睡眠
    print('Answered')
    return web.Response(
        content_type="application/json",
        text='',
    )

if __name__ == "__main__":
    app_aio = web.Application()
    app_aio.router.add_post("/test", testF)
    web.run_app(app_aio, host="0.0.0.0", port=5200)

修正后的效果

当多个请求同时进来时,第一个请求执行到await asyncio.sleep(10)会被挂起,事件循环立刻去处理下一个请求,所以会先打印所有的Called;等10秒后,所有挂起的任务依次恢复执行,打印Answered,和你期望的输出一致。

内容的提问来源于stack exchange,提问作者Marco Vinicius Castellari

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 01:32:38