raise StreamConsumed()
self._is_stream_consumed = True
- if hasattr(self._stream, "read") and not isinstance(
- self._stream, SyncByteStream
- ):
+ if hasattr(self._stream, "read"):
# File-like interfaces should use 'read' directly.
chunk = self._stream.read(self.CHUNK_SIZE) # type: ignore
while chunk:
raise StreamConsumed()
self._is_stream_consumed = True
- if hasattr(self._stream, "aread") and not isinstance(
- self._stream, AsyncByteStream
- ):
+ if hasattr(self._stream, "aread"):
# File-like interfaces should use 'aread' directly.
chunk = await self._stream.aread(self.CHUNK_SIZE) # type: ignore
while chunk:
"""
Subclasses can override this method to release any network resources
after a request/response cycle is complete.
-
- Streaming cases should use a `try...finally` block to ensure that
- the stream `close()` method is always called.
-
- Example:
-
- status_code, headers, stream, extensions = transport.handle_request(...)
- try:
- ...
- finally:
- stream.close()
- """
-
- def read(self) -> bytes:
"""
- Simple cases can use `.read()` as a convenience method for consuming
- the entire stream and then closing it.
-
- Example:
-
- status_code, headers, stream, extensions = transport.handle_request(...)
- body = stream.read()
- """
- try:
- return b"".join([part for part in self])
- finally:
- self.close()
class AsyncByteStream:
async def aclose(self) -> None:
pass
-
- async def aread(self) -> bytes:
- try:
- return b"".join([part async for part in self])
- finally:
- await self.aclose()
assert isinstance(stream, httpx.SyncByteStream)
assert isinstance(stream, httpx.AsyncByteStream)
- sync_content = stream.read()
- async_content = await stream.aread()
+ sync_content = b"".join([part for part in stream])
+ async_content = b"".join([part async for part in stream])
assert headers == {}
assert sync_content == b""