Skip to content
Myr

Add Response.stream_lines (#575)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Tom Christie · committed by GitHub · parent fdaa012 · Browse files · 4 files+125 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+125 added−0 removed

  • tests:+55 added−0 removed
  • other:+70 added−0 removed

4 files+125 added−0 removed

modified:httpx/decoders.py+61 added
209 unmodified lines
210211 return result212213214class LineDecoder:215 """216 Handles incrementally reading lines from text.217218 Uses universal line decoding, supporting any of `\n`, `\r`, or `\r\n`219 as line endings, normalizing to `\n`.220 """221222 def __init__(self) -> None:223 self.buffer = ""224225 def decode(self, text: str) -> typing.List[str]:226 lines = []227228 if text.startswith("\n") and self.buffer and self.buffer[-1] == "\r":229 # Handle the case where we have an "\r\n" split across230 # our previous input, and our new chunk.231 lines.append(self.buffer[:-1] + "\n")232 self.buffer = ""233 text = text[1:]234235 while text:236 num_chars = len(text)237 for idx in range(num_chars):238 char = text[idx]239 next_char = None if idx + 1 == num_chars else text[idx + 1]240 if char == "\n":241 lines.append(self.buffer + text[: idx + 1])242 self.buffer = ""243 text = text[idx + 1 :]244 break245 elif char == "\r" and next_char == "\n":246 lines.append(self.buffer + text[:idx] + "\n")247 self.buffer = ""248 text = text[idx + 2 :]249 break250 elif char == "\r" and next_char is not None:251 lines.append(self.buffer + text[:idx] + "\n")252 self.buffer = ""253 text = text[idx + 1 :]254 break255 elif next_char is None:256 self.buffer = text257 text = ""258 break259260 return lines261262 def flush(self) -> typing.List[str]:263 if self.buffer.endswith("\r"):264 # Handle the case where we had a trailing '\r', which could have265 # been a '\r\n' pair.266 lines = [self.buffer[:-1] + "\n"]267 elif self.buffer:268 lines = [self.buffer]269 else:270 lines = []271 self.buffer = ""272 return lines273274275SUPPORTED_DECODERS = {276 "identity": IdentityDecoder,277 "gzip": GZipDecoder,278 "deflate": DeflateDecoder,
11 unmodified lines
modified:httpx/models.py+9 added
15 unmodified lines
16 ACCEPT_ENCODING,17 SUPPORTED_DECODERS,18 Decoder,19 IdentityDecoder,20 LineDecoder,21 MultiDecoder,22 TextDecoder,23)24from .exceptions import (
911 unmodified lines
936 async for chunk in self.stream():937 yield decoder.decode(chunk)938 yield decoder.flush()939940 async def stream_lines(self) -> typing.AsyncIterator[str]:941 decoder = LineDecoder()942 async for text in self.stream_text():943 for line in decoder.decode(text):944 yield line945 for line in decoder.flush():946 yield line947948 async def raw(self) -> typing.AsyncIterator[bytes]:949 """950 A byte-iterator over the raw response content.951 """
206 unmodified lines
modified:tests/models/test_responses.py+12 added
163 unmodified lines
164 assert content == "Hello, world!"165166167@pytest.mark.asyncio168async def test_stream_lines():169 response = httpx.Response(200, content=b"Hello,\nworld!")170171 await response.read()172173 content = []174 async for line in response.stream_lines():175 content.append(line)176 assert content == ["Hello,\n", "world!"]177178179@pytest.mark.asyncio180async def test_stream_interface_after_read():181 response = httpx.Response(200, content=b"Hello, world!")182183 await response.read()
104 unmodified lines
modified:tests/test_decoders.py+43 added
7 unmodified lines
8 BrotliDecoder,9 DeflateDecoder,10 GZipDecoder,11 IdentityDecoder,12 LineDecoder,13 TextDecoder,14)1516
150 unmodified lines
167 assert decoder.decode(b"") == ""168 assert decoder.flush() == ""169170171def test_line_decoder_nl():172 decoder = LineDecoder()173 assert decoder.decode("") == []174 assert decoder.decode("a\n\nb\nc") == ["a\n", "\n", "b\n"]175 assert decoder.flush() == ["c"]176177 decoder = LineDecoder()178 assert decoder.decode("") == []179 assert decoder.decode("a\n\nb\nc\n") == ["a\n", "\n", "b\n", "c\n"]180 assert decoder.flush() == []181182183def test_line_decoder_cr():184 decoder = LineDecoder()185 assert decoder.decode("") == []186 assert decoder.decode("a\r\rb\rc") == ["a\n", "\n", "b\n"]187 assert decoder.flush() == ["c"]188189 decoder = LineDecoder()190 assert decoder.decode("") == []191 assert decoder.decode("a\r\rb\rc\r") == ["a\n", "\n", "b\n"]192 assert decoder.flush() == ["c\n"]193194195def test_line_decoder_crnl():196 decoder = LineDecoder()197 assert decoder.decode("") == []198 assert decoder.decode("a\r\n\r\nb\r\nc") == ["a\n", "\n", "b\n"]199 assert decoder.flush() == ["c"]200201 decoder = LineDecoder()202 assert decoder.decode("") == []203 assert decoder.decode("a\r\n\r\nb\r\nc\r\n") == ["a\n", "\n", "b\n", "c\n"]204 assert decoder.flush() == []205206 decoder = LineDecoder()207 assert decoder.decode("") == []208 assert decoder.decode("a\r") == []209 assert decoder.decode("\n\r\nb\r\nc") == ["a\n", "\n", "b\n"]210 assert decoder.flush() == ["c"]211212213def test_invalid_content_encoding_header():214 headers = [(b"Content-Encoding", b"invalid-header")]215 body = b"test 123"216
2 unmodified lines