我是Python新手,可能在这里很愚蠢,但我不明白为什么我的服务器一次不能处理多个连接。
我的示例代码:
import time
from aiohttp import web
def testF(request): #I've tried with async def testF also
print('Called')
time.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)
如果我运行此网络服务器并一次多次调用该网址,它只会在第一个返回后开始第二次运行,为什么?
电流输出:
Called
Answered
Called
Answered
Called
Answered
Called
Answered
预期输出:
Called
Called
Called
Called
Answered
Answered
Answered
Answered
您的
testF
函数正在阻塞,因为它使用 time.sleep
。使用 await asyncio.sleep
实现无阻塞睡眠。
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)
这将允许您的服务器同时处理多个请求。