aiohttp with asyncio 和 Semaphores 返回一个充满 Nones 的列表

aiohttp with asyncio and Semaphores returning a list filled with Nones

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

我主要是从其他来源复制代码,因为我还没有完全理解异步编程,但似乎在调试时我应该从函数中获取结果,但是当我调试时出现了问题收集结果。我试过在我的循环、我的聚会、确保未来等方面玩杂耍,但似乎没有 return 一个可行的列表。

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))

我已经注释掉了进度条组件,但是当没有信号量时,该实现 return 达到了预期的结果。

如有任何帮助,我们将不胜感激。我正在疯狂地阅读异步编程,但我还不能全神贯注。

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

替换此代码...

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)