Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

make HTTPResponse.stream use read1 when amt=None #3216

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 3 additions & 0 deletions changelog/3216.feature.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
HTTPResponse.stream(amt=None) now yields data from non-chunked responses as it
is available. Previously all intermediate data was buffered and only returned
as a single bytes object at the end of the the response.
12 changes: 10 additions & 2 deletions src/urllib3/response.py
Original file line number Diff line number Diff line change
Expand Up @@ -1020,10 +1020,18 @@ def stream(
yield from self.read_chunked(amt, decode_content=decode_content)
else:
while not is_fp_closed(self._fp) or len(self._decoded_buffer) > 0:
data = self.read(amt=amt, decode_content=decode_content)

if amt is None:
data = self.read1(amt=amt, decode_content=decode_content)
else:
data = self.read(amt=amt, decode_content=decode_content)
if data:
yield data
else:
if self._fp:
self._fp.close()
illia-v marked this conversation as resolved.
Show resolved Hide resolved
break
if self.length_remaining:
raise IncompleteRead(self._fp_bytes_read, self.length_remaining)
smason marked this conversation as resolved.
Show resolved Hide resolved

# Overrides from io.IOBase
def readable(self) -> bool:
Expand Down
26 changes: 26 additions & 0 deletions test/test_response.py
Original file line number Diff line number Diff line change
Expand Up @@ -1021,6 +1021,32 @@ def close(self) -> None:
with pytest.raises(StopIteration):
next(stream)

def test_mock_stream_via_read1(self) -> None:
class MockHTTPRequest:
def __init__(self, chunkiter: typing.Iterator[bytes]) -> None:
self.chunkiter = chunkiter
self.closed = False

def read(self, amt: int) -> bytes:
"not called, presence indicates to HTTPResponse that this is a stream"
assert False

def read1(self, amt: int | None = None) -> bytes:
assert not self.closed
try:
return next(self.chunkiter)
except StopIteration:
return b""

def close(self) -> None:
self.closed = True

chunks = b"foo longer bar".split()
fp = MockHTTPRequest(iter(chunks))
resp = HTTPResponse(fp, preload_content=False) # type: ignore[arg-type]
assert list(resp.stream(None)) == chunks
assert fp.closed

def test_mock_transfer_encoding_chunked(self) -> None:
stream = [b"fo", b"o", b"bar"]
fp = MockChunkedEncodingResponse(stream)
Expand Down