【发布时间】:2017-02-02 07:31:43
【问题描述】:
我正在使用最新版本的 aiohttp (1.0.2) 和 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 工作原理的理解有缺陷?
【问题讨论】:
标签: asynchronous python-3.5 python-asyncio aiohttp