Repository navigation
Replies: 2 comments 1 reply
|
It's the point of streaming, to not load the entire data into the memory, and if it will not raise an error, what should it return? |
|
For the size-limit use case in your follow-up, explicitly collect a bounded body, then create a new buffered import httpx
class BodyTooLarge(ValueError):
pass
async def get_buffered(client, url, max_bytes=1_000_000):
if max_bytes < 0:
raise ValueError("max_bytes must be nonnegative")
async with client.stream("GET", url) as response:
response.raise_for_status()
body = bytearray()
async for chunk in response.aiter_bytes(chunk_size=64 * 1024):
if len(body) + len(chunk) > max_bytes:
raise BodyTooLarge(f"Decoded body exceeds {max_bytes} bytes")
body.extend(chunk)
headers = response.headers.copy()
for name in ("content-encoding", "content-length", "transfer-encoding"):
if name in headers:
del headers[name]
headers["content-length"] = str(len(body))
return httpx.Response(
response.status_code,
headers=headers,
content=bytes(body),
request=response.request,
)The returned object's Two details matter here:
The streaming context closes on success, an oversized body, or a read error. This bounds the body retained by application code, not the entire process RSS: HTTPX decoding/chunk buffers and the final bytes copy still consume memory. Calling Async streaming documentation. AI-assisted; checked small/empty bodies, oversize rejection, gzip header normalization and stream cleanup on HTTPX 0.28.1. |
Uh oh!
There was an error while loading. Please reload this page.
The following code open a stream and iter on all chunks.
Although all chunks have been consumed response.content remains unusable (by raising a ResponseNotRead).
It would be great to set
response._contentonce the iteration is over. WDYT?All reactions