简体   繁体   English

使用 aiohttp 分离异步请求并保存

[英]Separating async requests and saving using aiohttp

I am currently calling an external API many times and downloading the response's content from each call.我目前正在多次调用外部 API 并从每次调用中下载响应的内容。 I am using aiohttp and asyncio to speed up this process, but am having trouble figuring out how to separate the fetch functionality from the save functionality.我正在使用 aiohttp 和 asyncio 来加速这个过程,但是在弄清楚如何将获取功能与保存功能分开时遇到了麻烦。

Setup设置

import asyncio
import os

from aiohttp import ClientSession

Currently, I am using the following function:目前,我正在使用以下 function:

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)

My main call looks like this:我的主要调用如下所示:

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)

Given this basic example, is it possible to separate the fetch and save functionality in fetch_and_save ?鉴于这个基本示例,是否可以在fetch_and_save中分离获取和保存功能?

Just create independent functions for fetch portion and save portion.只需为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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM