Skip to content
Myr

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

6 files+103 added−16 removed

modified:httpcore/models.py+57 added-11 removed
1import cgi2import typing3from urllib.parse import urlsplit45import chardet67from .config import SSLConfig, TimeoutConfig8from .decoders import (9 ACCEPT_ENCODING,10 SUPPORTED_DECODERS,
2 unmodified lines
13 MultiDecoder,14)15from .exceptions import ResponseClosed, ResponseNotRead, StreamConsumed16from .status_codes import codes14from .utils import get_reason_phrase, normalize_header_key, normalize_header_value17from .utils import (18 get_reason_phrase,19 is_known_encoding,20 normalize_header_key,21 normalize_header_value,22)2324URLTypes = typing.Union["URL", str]2526HeaderTypes = typing.Union[
180 unmodified lines
207208 def getlist(self, key: str, split_commas: bool = False) -> typing.List[str]:209 """210 Return multiple header values.203204 If there are header values that include commas, then we default to205 spliting them into multiple results, except for Set-Cookie.206207 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"213214 values = [215 item_value.decode(self.encoding)216 for item_key, item_value in self._list
207 unmodified lines
424 @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._content434435 @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._text445446 @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._encoding456457 @encoding.setter458 def encoding(self, value: str) -> None:459 self._encoding = value460461 @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 None469470 parsed = cgi.parse_header(content_type)[-1]471 return parsed.get("charset")472473 @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"]479480 @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 lines
modified:httpcore/utils.py+9 added
1import codecs2import http3import typing4from urllib.parse import quote5
74 unmodified lines
80 try:81 return http.HTTPStatus(status_code).phrase82 except ValueError as exc:83 return ""848586def is_known_encoding(encoding: str) -> bool:87 try:88 codecs.lookup(encoding)89 except LookupError:90 return False91 return True
modified:tests/models/test_responses.py+34 added-3 removed
10 unmodified lines
11def 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!"161718def 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"252627def 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"313233def test_response_default_encoding():34 response = httpcore.Response(200, content=b"")35 assert response.text == ""36 assert response.encoding == "utf-8"373839def 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"464748@pytest.mark.asyncio49async def test_read_response():50 response = httpcore.Response(200, content=b"Hello, world!")5152 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_closed5657 content = await response.read()58
41 unmodified lines
100def 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 lines
8 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!"131415@pytest.mark.asyncio16async def test_post(server):
36 unmodified lines
modified:requirements.txt+1 added
1certifi2chardet3h114h256# Optional
12 unmodified lines
modified:setup.py+1 added-1 removed
45 unmodified lines
46 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