import asyncio
import pathlib
from time import perf_counter

import aiofiles
from httpx import AsyncClient, Response


async def get_file(client: AsyncClient, url: str) -> Response:
    return await client.get(url, follow_redirects=True)


async def write_file(response: Response) -> None:
    file_name = response.url.path.rsplit("/", 1)[1]
    print(file_name)
    async with aiofiles.open(f"photos/{file_name}", "wb") as f:
        await f.write(response.content)


async def download_file(client: AsyncClient, url: str) -> None:
    await write_file(await get_file(client, url))


async def main():
    pathlib.Path("photos").mkdir(exist_ok=True)
    async with AsyncClient() as client:
        await asyncio.gather(
            *(
                download_file(client, "https://loremflickr.com/320/240")
                for _ in range(10)
            )
        )


start = perf_counter()
asyncio.run(main())
print(perf_counter() - start)