Skip to content
Myr

Cleanup response.json() method (#2911)

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 5f2d620 · Browse files · 3 files+12 added−47 removed
This commit

State

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

Trailers

  • Co-authored-by: Kar Petrosyan <92274156+karpetrosyan@users.noreply.github.com>

Diff stats

3 files+12 added−47 removed

  • tests:+11 added−6 removed
  • other:+1 added−41 removed

3 files+12 added−47 removed

modified:httpx/_models.py+1 added-6 removed
41 unmodified lines
42 SyncByteStream,43)44from ._urls import URL45from ._utils import (46 guess_json_utf,46 is_known_encoding,47 normalize_header_key,48 normalize_header_value,49 obfuscate_sensitive_headers,
707 unmodified lines
757 message = message.format(self, error_type=error_type)758 raise HTTPStatusError(message, request=request, response=self)759760 def json(self, **kwargs: typing.Any) -> typing.Any:762 if self.charset_encoding is None and self.content and len(self.content) > 3:763 encoding = guess_json_utf(self.content)764 if encoding is not None:765 return jsonlib.loads(self.content.decode(encoding), **kwargs)766 return jsonlib.loads(self.text, **kwargs)761 return jsonlib.loads(self.content, **kwargs)762763 @property764 def cookies(self) -> "Cookies":765 if not hasattr(self, "_cookies"):
449 unmodified lines
modified:httpx/_utils.py-35 removed
89 unmodified lines
90 value = _HTML5_FORM_ENCODING_RE.sub(replacer, value)91 return f'{name}="{value}"'.encode()929394# Null bytes; no need to recreate these on each call to guess_json_utf95_null = b"\x00"96_null2 = _null * 297_null3 = _null * 39899100def guess_json_utf(data: bytes) -> typing.Optional[str]:101 # JSON always starts with two ASCII characters, so detection is as102 # easy as counting the nulls and from their location and count103 # determine the encoding. Also detect a BOM, if present.104 sample = data[:4]105 if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE):106 return "utf-32" # BOM included107 if sample[:3] == codecs.BOM_UTF8:108 return "utf-8-sig" # BOM included, MS style (discouraged)109 if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):110 return "utf-16" # BOM included111 nullcount = sample.count(_null)112 if nullcount == 0:113 return "utf-8"114 if nullcount == 2:115 if sample[::2] == _null2: # 1st and 3rd are null116 return "utf-16-be"117 if sample[1::2] == _null2: # 2nd and 4th are null118 return "utf-16-le"119 # Did not detect 2 valid UTF-16 ascii-range characters120 if nullcount == 3:121 if sample[:3] == _null3:122 return "utf-32-be"123 if sample[1:] == _null3:124 return "utf-32-le"125 # Did not detect a valid UTF-32 ascii-range character126 return None12712894def get_ca_bundle_from_env() -> typing.Optional[str]:95 if "SSL_CERT_FILE" in os.environ:96 ssl_file = Path(os.environ["SSL_CERT_FILE"])97 if ssl_file.is_file():
345 unmodified lines
modified:tests/test_utils.py+11 added-6 removed
1import json2import logging3import os4import random5
4 unmodified lines
10from httpx._utils import (11 URLPattern,12 get_ca_bundle_from_env,13 get_environment_proxies,13 guess_json_utf,14 is_https_redirect,15 obfuscate_sensitive_headers,16 parse_header_links,17 same_origin,
15 unmodified lines
33 "utf-32-le",34 ),35)36def test_encoded(encoding):37 data = "{}".encode(encoding)38 assert guess_json_utf(data) == encoding37 content = '{"abc": 123}'.encode(encoding)38 response = httpx.Response(200, content=content)39 assert response.json() == {"abc": 123}404142def test_bad_utf_like_encoding():42 assert guess_json_utf(b"\x00\x00\x00\x00") is None43 content = b"\x00\x00\x00\x00"44 response = httpx.Response(200, content=content)45 with pytest.raises(json.decoder.JSONDecodeError):46 response.json()474849@pytest.mark.parametrize(50 ("encoding", "expected"),
4 unmodified lines
55 ("utf-32-le", "utf-32"),56 ),57)58def test_guess_by_bom(encoding, expected):55 data = "\ufeff{}".encode(encoding)56 assert guess_json_utf(data) == expected59 content = '\ufeff{"abc": 123}'.encode(encoding)60 response = httpx.Response(200, content=content)61 assert response.json() == {"abc": 123}626364@pytest.mark.parametrize(65 "value, expected",
222 unmodified lines