Результати виконання задач можна обробляти порціями, batch-ами
(наприклад виводити порціями або записувати у БД)
Такі можливості дає стороння бібліотека aiostream
import time
import asyncio
import os
import time
from functools import partial
from httpx import Response, AsyncClient
from aiostream import pipe, stream
API_KEY = "reqres_******************"
TOTAL_REQUESTS = 20
CONCURRENCY = 4
BATCH_SIZE = 5
async def fetch_data(url: str, client: AsyncClient) -> Response:
print("fetch", url, flush=True)
return await client.get(url)
async def main() -> None:
async with AsyncClient(headers={"x-api-key": API_KEY}) as client:
urls = (
f"https://reqres.in/api/users?delay={i % 3 + 1}"
for i in range(TOTAL_REQUESTS)
)
pipeline = (
stream.iterate(urls)
| pipe.map(
partial(fetch_data, client=client),
ordered=True,
task_limit=CONCURRENCY,
)
| pipe.chunks(BATCH_SIZE)
| pipe.enumerate(start=1)
)
start = time.monotonic()
async with pipeline.stream() as batches:
async for number, batch in batches:
elapsed = time.monotonic() - start
codes = [r.status_code for r in batch]
print(f"[{elapsed:5.2f} s] batch {number}: {codes}")
print(f"Elapsed: {time.monotonic() - start:.2f} s")
if __name__ == "__main__":
asyncio.run(main())
#asyncio #gather


