【问题标题】:Separating async requests and saving using aiohttp使用 aiohttp 分离异步请求并保存
【发布时间】:2021-03-31 17:00:54
【问题描述】:

我目前正在多次调用外部 API,并从每次调用中下载响应的内容。我正在使用 aiohttp 和 asyncio 来加快这个过程,但我无法弄清楚如何将提取功能与保存功能分开。

设置

import asyncio
import os

from aiohttp import ClientSession

目前,我正在使用以下功能:

async def fetch_and_save(link, path, client):
    async with await client.get(link) as response:
        contents = await response.read()

        if not os.path.exists(os.path.dirname(path)):
            os.makedirs(os.path.dirname(path))
        with open(path, "wb") as f:
            f.write(contents)

我的主要调用如下所示:

async def fetch_and_save_all(inputs):
    async with ClientSession() as client:
        tasks = [asyncio.ensure_future(fetch_and_save(link, path, client))
                 for link, path in inputs]
        for f in asyncio.as_completed(tasks):
            await f


def main(inputs):
    loop = asyncio.get_event_loop()
    loop.run_until_complete(fetch_and_save_all(inputs))

if __name__ == "__main__":
    inputs = [
        (f"https://httpbin.org/range/{i}", f"./tmp/{i}.txt") for i in range(1, 10)]
    main(inputs)

鉴于这个基本示例,是否可以在fetch_and_save 中分离获取和保存功能?

【问题讨论】:

  • 您所说的“分离”到底是什么意思?期望的最终结果或界面是什么?当然你可以简单地将保存代码移动到一个单独的函数中,但我不认为这就是你的意思。
  • @sytech 我真的很难模拟获取并认为保存使过程复杂化。
  • 我明白了。简单地将用于获取和保存的相应代码移动到它们自己的函数中不能解决这个问题吗?例如fetch_and_save 会做类似await save(await fetch(...)) 的事情,然后可以独立地模拟各个函数。

标签: python asynchronous async-await python-asyncio aiohttp


【解决方案1】:

只需为fetch 部分和save 部分创建独立的函数。

async def fetch(link, client):
    async with await client.get(link) as response:
        contents = await response.read()
    return contents

def save(contents, path):
    if not os.path.exists(os.path.dirname(path)):
        os.makedirs(os.path.dirname(path))
    with open(path, 'wb') as f:
        bytes_written = f.write(contents)
    return bytes_written

async def fetch_and_save(link, path, client):
    contents = await fetch(link, client)
    save(contents, path)

【讨论】:

    猜你喜欢
    • 2019-09-21
    • 2021-02-15
    • 1970-01-01
    • 2013-04-23
    • 1970-01-01
    • 1970-01-01
    • 2018-04-24
    • 2019-07-21
    • 2015-10-24
    相关资源
    最近更新 更多