首页 > 解决方案 > aiohttp RuntimeError: await 未与未来一起使用

问题描述

我知道python asyncio - RuntimeError: await 没有与 future 一起使用,但是那里的答案没有解决这里发生的事情。

使用时aiohttp遇到以下错误:

  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/asyncio/selector_events.py", line 485, in sock_connect
    return await fut
RuntimeError: await wasn't used with future
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x7fb28040f760>

这是相关的代码:

urls = # some list of URLs including `https://www.alphavantage.co/query?function=OVERVIEW&symbol=IBM&apikey=demo`.....

async def run_tasks():
    session = aiohttp.ClientSession()
    tasks = [session.get(url) for url in urls]
    await asyncio.gather(*tasks)
    await session.close()

asyncio.run(run_tasks())

看起来我正在正确地等待事件循环,但我一直遇到这个问题,什么给出了?

版本:

aiohttp==3.7.4.post0
asyncio==3.4.3
Python 3.8.0

标签: pythonpython-asyncioaiohttp

解决方案


我知道这并不能直接回答您的问题,但实际上aiohttp 请求生命周期中有一些异步调用,因此您必须await在几个地方:

import asyncio

import aiohttp

URL = "https://stackoverflow.com"


async def main():
    session = aiohttp.ClientSession()
    resp = await session.get(URL)
    html = await resp.text()

    print(f"{URL} <{resp.status}> ({len(html)})")

    resp.release()

    await session.close()


if __name__ == "__main__":
    asyncio.run(main())

通常且更简单的方法是使用上下文管理器,以确保正确关闭所有剩余资源:

import asyncio

import aiohttp

URLS = [
    "https://serverfault.com",
    "https://stackoverflow.com",
]


async def fetch(session, url):
    async with session.get(url) as resp:
        html = await resp.text()

        print(f"{url} <{resp.status}>")

    return {url: len(html)}


async def main():
    tasks = []

    async with aiohttp.ClientSession() as session:
        for url in URLS:
            tasks.append(asyncio.create_task(fetch(session, url)))

        data = await asyncio.gather(*tasks)

    print(data)


if __name__ == "__main__":
    asyncio.run(main())

测试:

$ python test.py
https://serverfault.com <200>
https://stackoverflow.com <200>
[{'https://serverfault.com': 143272}, {'https://stackoverflow.com': 191046}]

推荐阅读