Consume HTTP Bodies in Bounded Chunks
Core idea
Read response bodies incrementally to avoid holding an entire unknown-size payload in memory. A binary read can return fewer bytes than requested; empty bytes indicate EOF for the blocking fixture here. Track actual bytes consumed, enforce a cap before storing them, and close the response even on rejection. A Content-Length header is not a substitute for a local bound.
from io import BytesIOwith BytesIO(b'abcdefg') as response: total = 0 while chunk := response.read(3): total += len(chunk) print(total)The last chunk has one byte; only the total is retained.
Reject an oversized fixture
from io import BytesIOdef collect(response, limit): data = bytearray() while chunk := response.read(min(4, limit-len(data)+1)): if len(data)+len(chunk) > limit: raise ValueError('too large') data.extend(chunk) return bytes(data)for payload in (b'abc', b'abcd'): with BytesIO(payload) as response: try: print(collect(response, 3)) except ValueError: print('rejected')The extra byte distinguishes an exact-limit body from an oversized one. The limit is a nonnegative integer.
Common mistake
Decoding each arbitrary UTF-8 chunk separately can split a character. Use an incremental decoder or decode a fully collected, bounded body. Apply limits to decompressed data too.
Practice
Test empty, exact-limit and one-byte-over payloads; check that each fixture closes even after rejection.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Streaming responses
Check your understanding of streaming responses.
What is printed?
from io import BytesIOf=BytesIO(b'12345')print(len(f.read(4)), len(f.read(4)))f.close()What is printed?
from io import BytesIOwith BytesIO(b'') as f: print(f.read(2)==b'')What should enforce a body size cap?
Why use incremental UTF-8 decoding?