aiohttp 与 asyncio 和信号量返回一个填充 None 的列表

Mic*_*yre 3 python python-3.x python-asyncio aiohttp

我有一个脚本可以检查数十万个提供的网站的状态代码,并且我试图将信号量集成到流程中以加快处理速度。问题是,每当我集成信号量时,我只会得到一个填充有 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))
Run Code Online (Sandbox Code Playgroud)

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

任何帮助将不胜感激。我正在疯狂地阅读异步编程,但我还无法全神贯注于它。

Mik*_*mov 5

您应该显式返回等待协程的结果。

替换此代码...

async def bound_fetch(sem, session, url):
    async with sem:
        await fetch(session, url)
Run Code Online (Sandbox Code Playgroud)

... 有了这个:

async def bound_fetch(sem, session, url):
    async with sem:
        return await fetch(session, url)
Run Code Online (Sandbox Code Playgroud)

  • 这个函数看起来是从 https://pawelmhm.github.io/asyncio/python/aiohttp/2016/04/22/asyncio-aiohttp.html 中提取的,它也缺少“return”。 (2认同)