【问题标题】:aiohttp with asyncio and Semaphores returning a list filled with Nones带有 asyncio 和 Semaphores 的 aiohttp 返回一个填充了 None 的列表
【发布时间】:2019-05-15 14:36:48
【问题描述】:

我有一个脚本可以检查几十万个提供的网站的状态代码,我试图将信号量集成到流中以加快处理速度。问题是,每当我集成信号量时,我只会得到一个填充了 None 对象的列表,我不完全确定为什么。

我主要是从其他来源复制代码,因为我还没有完全理解异步编程,但是当我调试时,我似乎应该从函数中获得结果,但是当我收集结果。我尝试过在循环、聚会、确保未来等方面进行杂耍,但似乎没有任何东西可以返回有效的列表。

async def fetch(session, url):
    try:
        async with session.head(url, allow_redirects=True) as resp:
            return url, resp.real_url, resp.status, resp.reason
    except Exception as e:
        return url, None, e, 'Error'


async def bound_fetch(sem, session, url):
    async with sem:
        await fetch(session, url)


async def run(urls):
    timeout = 15
    tasks = []

    sem = asyncio.Semaphore(100)
    conn = aiohttp.TCPConnector(limit=64, ssl=False)

    async with aiohttp.ClientSession(connector=conn) as session:
        for url in urls:
            task = asyncio.wait_for(bound_fetch(sem, session, url), timeout)
            tasks.append(task)

        responses = await asyncio.gather(*tasks)

    # responses = [await f for f in tqdm.tqdm(asyncio.as_completed(tasks), total=len(tasks))]
    return responses

urls = ['https://google.com', 'https://yahoo.com']

loop = asyncio.ProactorEventLoop()
data = loop.run_until_complete(run(urls))

我已经注释掉了进度条组件,但是当没有信号量时,该实现会返回所需的结果。

任何帮助将不胜感激。我正在疯狂地阅读异步编程,但我还不能完全理解它。

【问题讨论】:

  • 我遇到了与 None 完全相同的问题,因为我错过了他返回 :)- 我自己确实发现了错误,但是您帮助我弄清楚了如何使用进度条,所以感谢您发布问题:)

标签: python python-3.x python-asyncio aiohttp


【解决方案1】:

您应该明确返回等待协程的结果。

替换此代码...

async def bound_fetch(sem, session, url):
    async with sem:
        await fetch(session, url)

...用这个:

async def bound_fetch(sem, session, url):
    async with sem:
        return await fetch(session, url)

【讨论】:

猜你喜欢
  • 2019-08-06
  • 2017-02-04
  • 1970-01-01
  • 2018-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-07
相关资源
最近更新 更多