AIOHTTP Streaming Chunked Download

Download large files with aiohttp while iterating response chunks, hashing each block on the fly and keeping memory usage flat.

PythonData Fetching

Code

pythonsnippet
36 lines
# stream chunks incrementally to disk instead of buffering
import asyncio
import hashlib

import aiohttp


async def download_and_hash(url: str, block_hint: int = 1024 * 64) -> dict:
    digest = hashlib.sha256()
    received = 0
    chunks = 0

    timeout = aiohttp.ClientTimeout(total=None, sock_read=30)
    async with aiohttp.ClientSession(timeout=timeout) as session:
        async with session.get(url) as resp:
            resp.raise_for_status()
            total = int(resp.headers.get('Content-Length', 0))

            async for chunk in resp.content.iter_chunked(block_hint):
                digest.update(chunk)
                received += len(chunk)
                chunks += 1
                if chunks % 200 == 0:
                    print(f'progress {received / total:.1%}')

    return {
        'bytes': received,
        'chunks': chunks,
        'sha256': digest.hexdigest(),
    }


result = asyncio.run(
    download_and_hash('https://cdn.example.com/datasets/prices.parquet')
)
print('verified sha256:', result['sha256'][:16], 'bytes:', result['bytes'])

How it works

AIOHTTP Streaming Chunked Download keeps everything in the function download_and_hash.

Asynchronous boundaries use await, so failures surface as exceptions at the call site rather than being swallowed.

What comes back is a new object, not a reference to anything passed in.

Caveats

  • Plan for an install step: asyncio and aiohttp are a real dependency, resolved by the package manager.

Using it

The primary signature is def download_and_hash(url: str, block_hint: int = 1024 * 64) -> dict

The demo output is labeled (progress, verified sha256:), so every printed line maps back to its originating operation.

Treat download_and_hash as the API: import it, and ignore the supporting code.

Key statements

received += len(chunk)
chunks += 1
if chunks % 200 == 0:
    print(f'progress {received / total:.1%}')
return {
'bytes': received,
'chunks': chunks,
'sha256': digest.hexdigest(),
}

FAQ

Does `download_and_hash` modify its input?
It does not. Inputs are only read; the return value is freshly built.
Which packages must be installed first?
Yes. The imports resolve to `asyncio` and `aiohttp`, which the package manager must provide.