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
Provenance
- Commit
1d73150- Tree
3f2cb03- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
5f2d620
3 files changed+12 added−47 removed
modified:httpx/_models.py+1 added-6 removed
41 unmodified lines42 SyncByteStream,43 )44 from ._urls import URL45 from ._utils import (46- guess_json_utf,46 is_known_encoding,47 normalize_header_key,48 normalize_header_value,49 obfuscate_sensitive_headers,707 unmodified lines757 message = message.format(self, error_type=error_type)758 raise HTTPStatusError(message, request=request, response=self)759 760 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)762 763 @property764 def cookies(self) -> "Cookies":765 if not hasattr(self, "_cookies"):449 unmodified linesmodified:httpx/_utils.py-35 removed
89 unmodified lines90 value = _HTML5_FORM_ENCODING_RE.sub(replacer, value)91 return f'{name}="{value}"'.encode()92 93 94-# Null bytes; no need to recreate these on each call to guess_json_utf95-_null = b"\x00"96-_null2 = _null * 297-_null3 = _null * 398-99-100-def 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 None127-128-94 def 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 linesmodified:tests/test_utils.py+11 added-6 removed
1+import json2 import logging3 import os4 import random5 4 unmodified lines10 from 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 lines33 "utf-32-le",34 ),35 )36 def 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}40 41 42 def 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()47 48 49 @pytest.mark.parametrize(50 ("encoding", "expected"),4 unmodified lines55 ("utf-32-le", "utf-32"),56 ),57 )58 def 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}62 63 64 @pytest.mark.parametrize(65 "value, expected",222 unmodified lines