python - 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
解决方案
我知道这并不能直接回答您的问题,但实际上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}]
推荐阅读
- android - 如何从 firebase 实时数据库中获取子值和过滤器?
- python - 使用由随机像素组成的图像生成与 CIFAR10 相同大小的训练集
- gradle - 通过 Bitbucket Pipeline 使用 Gradle 构建
- python - 关于 Epoch 问题的梯度下降成本图
- c++ - 如何使用 OpenGL 在 Gtk+ 中进行 3D 渲染?
- python - 如何在 Python 中将一个文件中的值匹配到另一个文件
- c++ - 我们可以在不使用友元函数的情况下重载 '<<' 运算符吗?
- python-3.x - 无法在 Windows 中使用 Python 3.9 创建虚拟环境
- matlab - 如何使用单个语句(例如 for 循环或条件语句)按整数因子 M 对序列 x 进行下采样
- java - 按月休眠多个组