python - python aiohttp服务器和客户端与asyncio
问题描述
我正在运行一个 aiohttp 服务器。它正在逐一接受请求,并且工作正常。
from aiohttp import web
async def hello(request):
return web.Response(text='done')
app = web.Application()
app.add_routes([web.get('/', hello)])
web.run_app(app)
现在我需要一个一个地发出两个慢速传出请求。我正在考虑将 aiohttp 客户端代码放入 hello 函数中。因此,当服务器等待出站请求返回时,它可以为下一个入站请求提供服务。
async def hello(request):
async def fetch(session, url):
with async_timeout.timeout(10):
async with session.get(url) as response:
return await response.text()
async def main(loop):
async with aiohttp.ClientSession(loop=loop) as session:
html1 = await fetch(session, URL1)
html2 = await fetch(session, URL2)
loop = asyncio.get_event_loop()
loop.run_until_complete(main(loop))
return web.Response(text='done')
上面的html1和html2会同时出去。第一次提取完成后如何进行第二次提取?或者其他一些设计可以提供帮助?