Skip to content

Instantly share code, notes, and snippets.

@thetonus
Last active October 18, 2022 15:29
Show Gist options
  • Save thetonus/b81d684ec44034ac587ef761279e9cb1 to your computer and use it in GitHub Desktop.
Save thetonus/b81d684ec44034ac587ef761279e9cb1 to your computer and use it in GitHub Desktop.
Download file with Asyncio and Aiofiles
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())
@thetonus
Copy link
Author

pip install httpx[http2] or poetry add h2 to add http2 support.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment