Last active
October 18, 2022 15:29
-
-
Save thetonus/b81d684ec44034ac587ef761279e9cb1 to your computer and use it in GitHub Desktop.
Download file with Asyncio and Aiofiles
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
import os | |
from typing import List | |
import aiofiles | |
import httpx | |
async def download(client: httpx.AsyncClient, link: str, filename: str) -> None: | |
""" Download link """ | |
async with client.stream("GET", link) as resp: | |
resp.raise_for_status() | |
print(f"Downloading: {link}") | |
async with aiofiles.open(filename, "wb") as f: | |
async for data in resp.aiter_bytes(): | |
if data: | |
await f.write(data) | |
async def main() -> None: | |
""" Download data """ | |
async with httpx.AsyncClient(timeout=None, http2=True) as client: | |
links = [] | |
await asyncio.gather(*[download(client, link) for link in links]) | |
if __name__ == "__main__": | |
loop = asyncio.get_event_loop() | |
loop.run_until_complete(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
pip install httpx[http2]
orpoetry add h2
to add http2 support.