python3.5: 使用 aiohttp 是否可以同时提供多个响应?

python3.5: with aiohttp is it possible to serve several responses concurently?

我正在使用最新版本 (1.0.2) 的 aiohttp 和 python3.5 我有以下服务器代码

import asyncio

from aiohttp.web import Application, Response, StreamResponse, run_app


async def long(request):
    resp = StreamResponse()
    name = request.match_info.get('name', 'Anonymous')
    resp.content_type = 'text/plain'
    for _ in range(1000000):
        answer = ('Hello world\n').encode('utf8')

        await resp.prepare(request)
        resp.write(answer)
    await resp.write_eof()
    return resp


async def init(loop):

    app = Application(loop=loop)
    app.router.add_get('/long', long)
    return app

loop = asyncio.get_event_loop()
app = loop.run_until_complete(init(loop))
run_app(app)

如果我然后 运行 在不同的终端中发出两个 curl 请求 curl http://localhost:8080/long,只有第一个会收到数据

我的想法是,使用 asyncio 你可以在单线程代码中开始服务其他响应,而另一个正在等待 I/O

我在网上找到的关于concurent+asyncio的大部分代码只讲客户端,没有讲服务器端

我是不是遗漏了什么,或者我对 asyncio 工作原理的理解有问题?

只需在 resp.write() 之后按 await resp.drain() 即可让 aiohttp 有机会在任务之间切换:

import asyncio

from aiohttp.web import Application, Response, StreamResponse, run_app


async def long(request):
    resp = StreamResponse()
    name = request.match_info.get('name', 'Anonymous')
    resp.content_type = 'text/plain'
    await resp.prepare(request)  # prepare should be called once
    for _ in range(1000000):
        answer = ('Hello world\n').encode('utf8')

        resp.write(answer)
        await resp.drain()  # switch point
    await resp.write_eof()
    return resp


async def init(loop):

    app = Application(loop=loop)
    app.router.add_get('/long', long)
    return app

loop = asyncio.get_event_loop()
app = loop.run_until_complete(init(loop))
run_app(app)