Skip to content
Myr

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

4 files+157 added−0 removed

modified:httpx/decoders.py+67 added
1 unmodified line
2Handlers for Content-Encoding.34See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding5"""6import codecs7import typing8import zlib910import chardet1112from .exceptions import DecodingError1314try:15 import brotli
124 unmodified lines
140 data = child.decode(data) + child.flush()141 return data142143144class TextDecoder:145 """146 Handles incrementally decoding bytes into text147 """148149 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()154155 # 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()160161 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 += data170171 # 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 = None181182 return text183 except UnicodeDecodeError: # pragma: nocover184 raise DecodingError() from None185186 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())194195 return self.decoder.decode(b"", True)196 except UnicodeDecodeError: # pragma: nocover197 raise DecodingError() from None198199 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")204205 return result206207208SUPPORTED_DECODERS = {209 "identity": IdentityDecoder,210 "gzip": GZipDecoder,211 "deflate": DeflateDecoder,
11 unmodified lines
modified:httpx/models.py+23 added
15 unmodified lines
16 SUPPORTED_DECODERS,17 Decoder,18 IdentityDecoder,19 MultiDecoder,20 TextDecoder,21)22from .exceptions import (23 CookieConflict,24 HTTPError,
865 unmodified lines
890 async for chunk in self.raw():891 yield self.decoder.decode(chunk)892 yield self.decoder.flush()893894 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()904905 async def raw(self) -> typing.AsyncIterator[bytes]:906 """907 A byte-iterator over the raw response content.908 """
71 unmodified lines
980 for chunk in self.raw():981 yield self.decoder.decode(chunk)982 yield self.decoder.flush()983984 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()994995 def raw(self) -> typing.Iterator[bytes]:996 """997 A byte-iterator over the raw response content.998 """
197 unmodified lines
modified:tests/models/test_responses.py+15 added
286 unmodified lines
287 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()291292293@pytest.mark.asyncio294async def test_stream_text():295 async def iterator():296 yield b"Hello, world!"297298 response = httpx.AsyncResponse(200, content=iterator().__aiter__())299300 await response.read()301302 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 lines
3import brotli4import pytest56import httpx7from httpx.decoders import TextDecoder8910def test_deflate():11 body = b"test 123"
76 unmodified lines
88 response = httpx.Response(200, headers=headers, content=compressed_body)89 response.content909192@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)109def test_text_decoder(data, encoding):110 def iterator():111 nonlocal data112 for chunk in data:113 yield chunk114115 response = httpx.Response(200, content=iterator())116 assert "".join(response.stream_text()) == (b"".join(data)).decode(encoding)117118119def test_text_decoder_known_encoding():120 def iterator():121 yield b"\x83g"122 yield b"\x83"123 yield b"\x89\x83x\x83\x8b"124125 response = httpx.Response(126 200,127 headers=[(b"Content-Type", b"text/html; charset=shift-jis")],128 content=iterator(),129 )130131 assert "".join(response.stream_text()) == "トラベル"132133134def test_text_decoder_empty_cases():135 decoder = TextDecoder()136 assert decoder.flush() == ""137138 decoder = TextDecoder()139 assert decoder.decode(b"") == ""140 assert decoder.flush() == ""141142143def test_invalid_content_encoding_header():144 headers = [(b"Content-Encoding", b"invalid-header")]145 body = b"test 123"146
3 unmodified lines