Add response.text and response.encoding
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Tom Christie · committed by Tom Christie · parent 4255d41 · Browse files · 6 files·+103 added−16 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+103 added−16 removed
- tests:+35 added−4 removed
- other:+68 added−12 removed
Provenance
- Commit
d8df61b- Tree
de4e79b- Author
Tom Christie <tom@tomchristie.com>- Committer
Tom Christie <tom@tomchristie.com>- Parent
4255d41
6 files changed+103 added−16 removed
modified:httpcore/models.py+57 added-11 removed
1+import cgi2 import typing3 from urllib.parse import urlsplit4 5+import chardet6+7 from .config import SSLConfig, TimeoutConfig8 from .decoders import (9 ACCEPT_ENCODING,10 SUPPORTED_DECODERS,2 unmodified lines13 MultiDecoder,14 )15 from .exceptions import ResponseClosed, ResponseNotRead, StreamConsumed16 from .status_codes import codes14-from .utils import get_reason_phrase, normalize_header_key, normalize_header_value17+from .utils import (18+ get_reason_phrase,19+ is_known_encoding,20+ normalize_header_key,21+ normalize_header_value,22+)23 24 URLTypes = typing.Union["URL", str]25 26 HeaderTypes = typing.Union[180 unmodified lines207 208 def getlist(self, key: str, split_commas: bool = False) -> typing.List[str]:209 """210 Return multiple header values.203-204- If there are header values that include commas, then we default to205- spliting them into multiple results, except for Set-Cookie.206-207- See: https://tools.ietf.org/html/rfc7230#section-3.2.2211 """212 get_header_key = key.lower().encode(self.encoding)210- if split_commas is None:211- split_commas = get_header_key != b"set-cookie"213 214 values = [215 item_value.decode(self.encoding)216 for item_key, item_value in self._list207 unmodified lines424 @property425 def content(self) -> bytes:426 if not hasattr(self, "_content"):427 if hasattr(self, "_raw_content"):427- self._content = (428- self.decoder.decode(self._raw_content) + self.decoder.flush()429- )428+ content = self.decoder.decode(self._raw_content)429+ content += self.decoder.flush()430+ self._content = content431 else:432 raise ResponseNotRead()433 return self._content434 435 @property436+ def text(self) -> str:437+ if not hasattr(self, "_text"):438+ content = self.content439+ if not content:440+ self._text = ""441+ else:442+ encoding = self.encoding443+ self._text = content.decode(encoding, errors="replace")444+ return self._text445+446+ @property447+ def encoding(self) -> str:448+ if not hasattr(self, "_encoding"):449+ encoding = self.charset_encoding450+ if encoding is None or not is_known_encoding(encoding):451+ encoding = self.apparent_encoding452+ if encoding is None or not is_known_encoding(encoding):453+ encoding = "utf-8"454+ self._encoding = encoding455+ return self._encoding456+457+ @encoding.setter458+ def encoding(self, value: str) -> None:459+ self._encoding = value460+461+ @property462+ def charset_encoding(self) -> typing.Optional[str]:463+ """464+ Return the encoding, as specified by the Content-Type header.465+ """466+ content_type = self.headers.get("Content-Type")467+ if content_type is None:468+ return None469+470+ parsed = cgi.parse_header(content_type)[-1]471+ return parsed.get("charset")472+473+ @property474+ def apparent_encoding(self) -> typing.Optional[str]:475+ """476+ Return the encoding, as it appears to autodetection.477+ """478+ return chardet.detect(self.content)["encoding"]479+480+ @property481 def decoder(self) -> Decoder:482 """483 Returns a decoder instance which can be used to decode the raw byte484 content, depending on the Content-Encoding used in the response.81 unmodified linesmodified:httpcore/utils.py+9 added
1+import codecs2 import http3 import typing4 from urllib.parse import quote5 74 unmodified lines80 try:81 return http.HTTPStatus(status_code).phrase82 except ValueError as exc:83 return ""84+85+86+def is_known_encoding(encoding: str) -> bool:87+ try:88+ codecs.lookup(encoding)89+ except LookupError:90+ return False91+ return Truemodified:tests/models/test_responses.py+34 added-3 removed
10 unmodified lines11 def test_response():12 response = httpcore.Response(200, content=b"Hello, world!")13 assert response.status_code == 20014 assert response.reason_phrase == "OK"15- assert response.content == b"Hello, world!"16- assert response.is_closed15+ assert response.text == "Hello, world!"16 17 18+def test_response_content_type_encoding():19+ headers = {"Content-Type": "text-plain; charset=latin-1"}20+ response = httpcore.Response(21+ 200, content="Latin 1: ÿ".encode("latin-1"), headers=headers22+ )23+ assert response.text == "Latin 1: ÿ"24+ assert response.encoding == "latin-1"25+26+27+def test_response_autodetect_encoding():28+ response = httpcore.Response(200, content="Snowmen: ☃☃☃".encode("utf-8"))29+ assert response.text == "Snowmen: ☃☃☃"30+ assert response.encoding == "utf-8"31+32+33+def test_response_default_encoding():34+ response = httpcore.Response(200, content=b"")35+ assert response.text == ""36+ assert response.encoding == "utf-8"37+38+39+def test_response_force_encoding():40+ response = httpcore.Response(200, content="Snowman: ☃".encode("utf-8"))41+ response.encoding = "iso-8859-1"42+ assert response.status_code == 20043+ assert response.reason_phrase == "OK"44+ assert response.text == "Snowman: â\x98\x83"45+ assert response.encoding == "iso-8859-1"46+47+48 @pytest.mark.asyncio49 async def test_read_response():50 response = httpcore.Response(200, content=b"Hello, world!")51 52 assert response.status_code == 20024- assert response.content == b"Hello, world!"53+ assert response.text == "Hello, world!"54+ assert response.encoding == "ascii"55 assert response.is_closed56 57 content = await response.read()58 41 unmodified lines100 def test_unknown_status_code():101 response = httpcore.Response(600)102 assert response.status_code == 600103 assert response.reason_phrase == ""104+ assert response.text == ""modified:tests/test_client.py+1 added-1 removed
7 unmodified lines8 url = "http://127.0.0.1:8000/"9 async with httpcore.Client() as client:10 response = await client.get(url)11 assert response.status_code == 20012- assert response.content == b"Hello, world!"12+ assert response.text == "Hello, world!"13 14 15 @pytest.mark.asyncio16 async def test_post(server):36 unmodified linesmodified:requirements.txt+1 added
1 certifi2+chardet3 h114 h25 6 # Optional12 unmodified linesmodified:setup.py+1 added-1 removed
45 unmodified lines46 author="Tom Christie",47 author_email="tom@tomchristie.com",48 packages=get_packages("httpcore"),49 data_files=[("", ["LICENSE.md"])],50- install_requires=["h11", "h2", "certifi"],50+ install_requires=["h11", "h2", "certifi", "chardet"],51 classifiers=[52 "Development Status :: 3 - Alpha",53 "Environment :: Web Environment",54 "Intended Audience :: Developers",9 unmodified lines