Python aiohttp Web 服务器一次不能处理多个请求

问题描述 投票:0回答:1

我是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
python python-3.x aiohttp
1个回答
0
投票

您的

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)

这将允许您的服务器同时处理多个请求。

© www.soinside.com 2019 - 2024. All rights reserved.