【发布时间】:2021-06-25 22:34:20
【问题描述】:
正如标题所说 - 我遇到了异步问题。我要实现的目标是写在每个函数下。可悲的是,在这种代码状态下,我得到了错误:
TypeError: object StreamReader can't be used in 'await' expression 最后是RuntimeError: Event loop is closed
我在谷歌上搜索了一段时间,并没有真正找到适合我的东西的解决方案。有没有人可以帮助我并弄清楚我做错了什么?我可以在一个异步函数中使用 2x async with .. 吗?
谢谢!
def load_file(file_path):
with open(file_path, "r") as f:
content = f.readlines()
content = [a.strip() for a in content]
return content
### --> Getting list of urls
async def task(session, item, urls):
async with session.get(item) as resp:
image_bytes = BytesIO(await resp.content)
### --> Downloading the image and getting image bytes
async with session.post(
TORCH_URL, data=image_bytes, headers={"authorization": TOKEN}
) as resp:
response = await resp.json()
print(response)
### --> Sending the image bytes to an API and getting a little json file as a response
async def asyncmain(urls, path, content):
tasks = []
async with aiohttp.ClientSession() as session:
tasks = [task(session, url, urls) for url in content]
await asyncio.gather(*tasks)
### --> Gathering the tasks with .gather()
@click.command()
@click.option("--urls", "-u", is_flag=True, help="Use this if you have urls")
@click.option(
"--path",
"-p",
help="Path to file with variant IDs, can be combined with -u (having urls in file)",
)
def main(urls, path):
tasks = []
content = load_file(path)
asyncio.run(asyncmain(urls, path, content), debug=True)
### --> Fire asyncio.run with some params
if __name__ == "__main__":
main()
【问题讨论】:
-
提供minimal reproducible example 会让更多人愿意提供帮助。
标签: python async-await python-asyncio aiohttp