【问题标题】:Get aiohttp results as string以字符串形式获取 aiohttp 结果
【发布时间】:2018-11-16 21:44:05
【问题描述】:

我正在尝试在 python 中使用异步从网站获取数据。作为示例,我使用了这段代码(在 A Better Coroutine Example 下):https://www.blog.pythonlibrary.org/2016/07/26/python-3-an-intro-to-asyncio/

现在这工作正常,但它将二进制块写入文件,我不希望它在文件中。我想要直接得到的数据。但我目前有一个协程对象列表,我无法从中获取数据。

代码:

# -*- coding: utf-8 -*-
import aiohttp
import asyncio
import async_timeout

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, urls):
    async with aiohttp.ClientSession(loop=loop) as session:
        tasks = [fetch(session, url) for url in urls]
        await asyncio.gather(*tasks)
        return tasks

# time normal way of retrieval
if __name__ == '__main__':
    urls = [a list of urls..]

    loop = asyncio.get_event_loop()
    details_async = loop.run_until_complete(main(loop, urls))

谢谢

【问题讨论】:

    标签: python python-asyncio aiohttp


    【解决方案1】:

    问题出在main()末尾的return tasks,原文章中没有。您应该返回由asyncio.gather 返回的元组,而不是返回协程对象(一旦传递给asyncio.gather 就没有用了),其中包含以正确顺序运行协程的结果。例如:

    async def main(loop, urls):
        async with aiohttp.ClientSession(loop=loop) as session:
            tasks = [fetch(session, url) for url in urls]
            results = await asyncio.gather(*tasks)
            return results
    

    现在loop.run_until_complete(main(loop, urls)) 将返回一个与 URL 顺序相同的文本元组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-06
      • 1970-01-01
      • 1970-01-01
      • 2014-04-26
      • 2015-05-28
      相关资源
      最近更新 更多