Implement Response.stream_text() (#183)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Seth Michael Larson · committed by GitHub · parent 9536b76 · Browse files · 4 files·+157 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+157 added−0 removed
- tests:+67 added−0 removed
- other:+90 added−0 removed
Provenance
- Commit
af907e8- Tree
73e53e0- Author
Seth Michael Larson <sethmichaellarson@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
9536b76
4 files changed+157 added−0 removed
modified:httpx/decoders.py+67 added
1 unmodified line2 Handlers for Content-Encoding.3 4 See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding5 """6+import codecs7 import typing8 import zlib9 10+import chardet11+12 from .exceptions import DecodingError13 14 try:15 import brotli124 unmodified lines140 data = child.decode(data) + child.flush()141 return data142 143 144+class TextDecoder:145+ """146+ Handles incrementally decoding bytes into text147+ """148+149+ def __init__(self, encoding: typing.Optional[str] = None):150+ self.decoder: typing.Optional[codecs.IncrementalDecoder] = (151+ None if encoding is None else codecs.getincrementaldecoder(encoding)()152+ )153+ self.detector = chardet.universaldetector.UniversalDetector()154+155+ # This buffer is only needed if 'decoder' is 'None'156+ # we want to trigger errors if data is getting added to157+ # our internal buffer for some silly reason while158+ # a decoder is discovered.159+ self.buffer: typing.Optional[bytearray] = None if self.decoder else bytearray()160+161+ def decode(self, data: bytes) -> str:162+ try:163+ if self.decoder is not None:164+ text = self.decoder.decode(data)165+ else:166+ assert self.buffer is not None167+ text = ""168+ self.detector.feed(data)169+ self.buffer += data170+171+ # Should be more than enough data to process, we don't172+ # want to buffer too long as chardet will wait until173+ # detector.close() is used to give back common174+ # encodings like 'utf-8'.175+ if len(self.buffer) >= 4096:176+ self.decoder = codecs.getincrementaldecoder(177+ self._detector_result()178+ )()179+ text = self.decoder.decode(bytes(self.buffer), False)180+ self.buffer = None181+182+ return text183+ except UnicodeDecodeError: # pragma: nocover184+ raise DecodingError() from None185+186+ def flush(self) -> str:187+ try:188+ if self.decoder is None:189+ # Empty string case as chardet is guaranteed to not have a guess.190+ assert self.buffer is not None191+ if len(self.buffer) == 0:192+ return ""193+ return bytes(self.buffer).decode(self._detector_result())194+195+ return self.decoder.decode(b"", True)196+ except UnicodeDecodeError: # pragma: nocover197+ raise DecodingError() from None198+199+ def _detector_result(self) -> str:200+ self.detector.close()201+ result = self.detector.result["encoding"]202+ if not result: # pragma: nocover203+ raise DecodingError("Unable to determine encoding of content")204+205+ return result206+207+208 SUPPORTED_DECODERS = {209 "identity": IdentityDecoder,210 "gzip": GZipDecoder,211 "deflate": DeflateDecoder,11 unmodified linesmodified:httpx/models.py+23 added
15 unmodified lines16 SUPPORTED_DECODERS,17 Decoder,18 IdentityDecoder,19 MultiDecoder,20+ TextDecoder,21 )22 from .exceptions import (23 CookieConflict,24 HTTPError,865 unmodified lines890 async for chunk in self.raw():891 yield self.decoder.decode(chunk)892 yield self.decoder.flush()893 894+ async def stream_text(self) -> typing.AsyncIterator[str]:895+ """896+ A str-iterator over the decoded response content897+ that handles both gzip, deflate, etc but also detects the content's898+ string encoding.899+ """900+ decoder = TextDecoder(encoding=self.charset_encoding)901+ async for chunk in self.stream():902+ yield decoder.decode(chunk)903+ yield decoder.flush()904+905 async def raw(self) -> typing.AsyncIterator[bytes]:906 """907 A byte-iterator over the raw response content.908 """71 unmodified lines980 for chunk in self.raw():981 yield self.decoder.decode(chunk)982 yield self.decoder.flush()983 984+ def stream_text(self) -> typing.Iterator[str]:985+ """986+ A str-iterator over the decoded response content987+ that handles both gzip, deflate, etc but also detects the content's988+ string encoding.989+ """990+ decoder = TextDecoder(encoding=self.charset_encoding)991+ for chunk in self.stream():992+ yield decoder.decode(chunk)993+ yield decoder.flush()994+995 def raw(self) -> typing.Iterator[bytes]:996 """997 A byte-iterator over the raw response content.998 """197 unmodified linesmodified:tests/models/test_responses.py+15 added
286 unmodified lines287 with mock.patch("httpx.models.guess_json_utf", return_value="utf-32"):288 response = httpx.Response(200, content=content, headers=headers)289 with pytest.raises(json.JSONDecodeError):290 response.json()291+292+293+@pytest.mark.asyncio294+async def test_stream_text():295+ async def iterator():296+ yield b"Hello, world!"297+298+ response = httpx.AsyncResponse(200, content=iterator().__aiter__())299+300+ await response.read()301+302+ content = ""303+ async for part in response.stream_text():304+ content += part305+ assert content == "Hello, world!"modified:tests/test_decoders.py+52 added
2 unmodified lines3 import brotli4 import pytest5 6 import httpx7+from httpx.decoders import TextDecoder8 9 10 def test_deflate():11 body = b"test 123"76 unmodified lines88 response = httpx.Response(200, headers=headers, content=compressed_body)89 response.content90 91 92+@pytest.mark.parametrize(93+ ["data", "encoding"],94+ [95+ ((b"Hello,", b" world!"), "ascii"),96+ ((b"\xe3\x83", b"\x88\xe3\x83\xa9", b"\xe3", b"\x83\x99\xe3\x83\xab"), "utf-8"),97+ ((b"\x83g\x83\x89\x83x\x83\x8b",) * 64, "shift-jis"),98+ ((b"\x83g\x83\x89\x83x\x83\x8b",) * 600, "shift-jis"),99+ (100+ (b"\xcb\xee\xf0\xe5\xec \xe8\xef\xf1\xf3\xec \xe4\xee\xeb\xee\xf0",) * 64,101+ "MacCyrillic",102+ ),103+ (104+ (b"\xa5\xa6\xa5\xa7\xa5\xd6\xa4\xce\xb9\xf1\xba\xdd\xb2\xbd",) * 512,105+ "euc-jp",106+ ),107+ ],108+)109+def test_text_decoder(data, encoding):110+ def iterator():111+ nonlocal data112+ for chunk in data:113+ yield chunk114+115+ response = httpx.Response(200, content=iterator())116+ assert "".join(response.stream_text()) == (b"".join(data)).decode(encoding)117+118+119+def test_text_decoder_known_encoding():120+ def iterator():121+ yield b"\x83g"122+ yield b"\x83"123+ yield b"\x89\x83x\x83\x8b"124+125+ response = httpx.Response(126+ 200,127+ headers=[(b"Content-Type", b"text/html; charset=shift-jis")],128+ content=iterator(),129+ )130+131+ assert "".join(response.stream_text()) == "トラベル"132+133+134+def test_text_decoder_empty_cases():135+ decoder = TextDecoder()136+ assert decoder.flush() == ""137+138+ decoder = TextDecoder()139+ assert decoder.decode(b"") == ""140+ assert decoder.flush() == ""141+142+143 def test_invalid_content_encoding_header():144 headers = [(b"Content-Encoding", b"invalid-header")]145 body = b"test 123"146 3 unmodified lines