Add `charset_normalizer` detection. (#1791)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Add charset_normalizer detection * Tweak JSON tests for slightly different charset decoding behaviour * Add charset-normalizer to docs
authored by Tom Christie · committed by GitHub · parent 7724661 · Browse files · 7 files·+82 added−91 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+82 added−91 removed
- tests:+50 added−38 removed
- other:+32 added−53 removed
Provenance
- Commit
acb5e6a- Tree
b2ad80c- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
7724661
7 files changed+82 added−91 removed
modified:docs/index.md+1 added
109 unmodified linesExpand all11011111211311411511611711829 unmodified lines109 unmodified linesExpand all* `httpcore` - The underlying transport implementation for `httpx`. * `h11` - HTTP/1.1 support. * `h2` - HTTP/2 support. *(Optional)** `certifi` - SSL certificates.* `charset_normalizer` - Charset auto-detection.* `rfc3986` - URL parsing & normalization. * `idna` - Internationalized domain name support.* `sniffio` - Async library autodetection.* `async_generator` - Backport support for `contextlib.asynccontextmanager`. *(Only required for Python 3.6)*29 unmodified linesmodified:httpx/_decoders.py+2 added-41 removed
239 unmodified lines240 """241 Handles incrementally decoding bytes into text242 """243 244- def __init__(self, encoding: typing.Optional[str] = None):245- self.decoder: typing.Optional[codecs.IncrementalDecoder] = None246- if encoding is not None:247- self.decoder = codecs.getincrementaldecoder(encoding)(errors="strict")244+ def __init__(self, encoding: str = "utf-8"):245+ self.decoder = codecs.getincrementaldecoder(encoding)(errors="replace")246 247 def decode(self, data: bytes) -> str:250- """251- If an encoding is explicitly specified, then we use that.252- Otherwise our strategy is to attempt UTF-8, and fallback to Windows 1252.253-254- Note that UTF-8 is a strict superset of ascii, and Windows 1252 is a255- superset of the non-control characters in iso-8859-1, so we essentially256- end up supporting any of ascii, utf-8, iso-8859-1, cp1252.257-258- Given that UTF-8 is now by *far* the most widely used encoding, this259- should be a pretty robust strategy for cases where a charset has260- not been explicitly included.261-262- Useful stats on the prevalence of different charsets in the wild...263-264- * https://w3techs.com/technologies/overview/character_encoding265- * https://w3techs.com/technologies/history_overview/character_encoding266-267- The HTML5 spec also has some useful guidelines, suggesting defaults of268- either UTF-8 or Windows 1252 in most cases...269-270- * https://dev.w3.org/html5/spec-LC/Overview.html271- """272- if self.decoder is None:273- # If this is the first decode pass then we need to determine which274- # encoding to use by attempting UTF-8 and raising any decode errors.275- attempt_utf_8 = codecs.getincrementaldecoder("utf-8")(errors="strict")276- try:277- attempt_utf_8.decode(data)278- except UnicodeDecodeError:279- # Could not decode as UTF-8. Use Windows 1252.280- self.decoder = codecs.getincrementaldecoder("cp1252")(errors="replace")281- else:282- # Can decode as UTF-8. Use UTF-8 with lenient error settings.283- self.decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")284-248 return self.decoder.decode(data)249 250 def flush(self) -> str:288- if self.decoder is None:289- return ""251 return self.decoder.decode(b"", True)252 253 254 class LineDecoder:76 unmodified linesmodified:httpx/_models.py+27 added-12 removed
6 unmodified lines7 from collections.abc import MutableMapping8 from http.cookiejar import Cookie, CookieJar9 from urllib.parse import parse_qs, quote, unquote, urlencode10 11+import charset_normalizer12 import idna13 import rfc398614 import rfc3986.exceptions15 1298 unmodified lines1314 content = self.content1315 if not content:1316 self._text = ""1317 else:1317- decoder = TextDecoder(encoding=self.encoding)1318+ decoder = TextDecoder(encoding=self.encoding or "utf-8")1319 self._text = "".join([decoder.decode(self.content), decoder.flush()])1320 return self._text1321 1322 @property1323 def encoding(self) -> typing.Optional[str]:1324 """1324- Return the encoding, which may have been set explicitly, or may have1325- been specified by the Content-Type header.1325+ Return an encoding to use for decoding the byte content into text.1326+ The priority for determining this is given by...1327+1328+ * `.encoding = <>` has been set explicitly.1329+ * The encoding as specified by the charset parameter in the Content-Type header.1330+ * The encoding as determined by `charset_normalizer`.1331+ * UTF-8.1332 """1333 if not hasattr(self, "_encoding"):1334 encoding = self.charset_encoding1335 if encoding is None or not is_known_encoding(encoding):1330- self._encoding = None1331- else:1332- self._encoding = encoding1336+ encoding = self.apparent_encoding1337+ self._encoding = encoding1338 return self._encoding1339 1340 @encoding.setter1341 def encoding(self, value: str) -> None:13 unmodified lines1355 return None1356 1357 return params["charset"].strip("'\"")1358 1359+ @property1360+ def apparent_encoding(self) -> typing.Optional[str]:1361+ """1362+ Return the encoding, as detemined by `charset_normalizer`.1363+ """1364+ content = getattr(self, "_content", b"")1365+ if len(content) < 32:1366+ # charset_normalizer will issue warnings if we run it with1367+ # fewer bytes than this cutoff.1368+ return None1369+ match = charset_normalizer.from_bytes(self.content).best()1370+ return None if match is None else match.encoding1371+1372 def _get_content_decoder(self) -> ContentDecoder:1373 """1374 Returns a decoder instance which can be used to decode the raw byte1375 content, depending on the Content-Encoding used in the response.52 unmodified lines1428 def json(self, **kwargs: typing.Any) -> typing.Any:1429 if self.charset_encoding is None and self.content and len(self.content) > 3:1430 encoding = guess_json_utf(self.content)1431 if encoding is not None:1414- try:1415- return jsonlib.loads(self.content.decode(encoding), **kwargs)1432+ return jsonlib.loads(self.content.decode(encoding), **kwargs)1416- except UnicodeDecodeError:1417- pass1433 return jsonlib.loads(self.text, **kwargs)1434 1435 @property1436 def cookies(self) -> "Cookies":72 unmodified lines1509 A str-iterator over the decoded response content1510 that handles both gzip, deflate, etc but also detects the content's1511 string encoding.1512 """1498- decoder = TextDecoder(encoding=self.encoding)1513+ decoder = TextDecoder(encoding=self.encoding or "utf-8")1514 chunker = TextChunker(chunk_size=chunk_size)1515 with request_context(request=self._request):1516 for byte_content in self.iter_bytes():1517 text_content = decoder.decode(byte_content)89 unmodified lines1607 A str-iterator over the decoded response content1608 that handles both gzip, deflate, etc but also detects the content's1609 string encoding.1610 """1596- decoder = TextDecoder(encoding=self.encoding)1611+ decoder = TextDecoder(encoding=self.encoding or "utf-8")1612 chunker = TextChunker(chunk_size=chunk_size)1613 with request_context(request=self._request):1614 async for byte_content in self.aiter_bytes():1615 text_content = decoder.decode(byte_content)247 unmodified linesmodified:tests/models/test_responses.py+45 added-32 removed
1 import json2 import pickle3-from unittest import mock3 4 import brotlicffi5 import pytest6 188 unmodified lines195 """196 A response with ISO 8859-1 encoded content should decode correctly,197 even with no charset specified.198 """200- content = "Accented: Österreich".encode("iso-8859-1")199+ content = "Accented: Österreich abcdefghijklmnopqrstuzwxyz".encode("iso-8859-1")200 headers = {"Content-Type": "text/plain"}201 response = httpx.Response(202 200,203 content=content,204 headers=headers,205 )207- assert response.text == "Accented: Österreich"208- assert response.encoding is None206+ assert response.text == "Accented: Österreich abcdefghijklmnopqrstuzwxyz"207+ assert response.charset_encoding is None208+ assert response.apparent_encoding is not None209 210 211 def test_response_no_charset_with_cp_1252_content():212 """213 A response with Windows 1252 encoded content should decode correctly,214 even with no charset specified.215 """216- content = "Euro Currency: €".encode("cp1252")216+ content = "Euro Currency: € abcdefghijklmnopqrstuzwxyz".encode("cp1252")217 headers = {"Content-Type": "text/plain"}218 response = httpx.Response(219 200,220 content=content,221 headers=headers,222 )223- assert response.text == "Euro Currency: €"224- assert response.encoding is None223+ assert response.text == "Euro Currency: € abcdefghijklmnopqrstuzwxyz"224+ assert response.charset_encoding is None225+ assert response.apparent_encoding is not None226 227 228 def test_response_non_text_encoding():229 """488 unmodified lines718 )719 assert response.json(parse_int=str)["amount"] == "1"720 721 722+@pytest.mark.parametrize(723+ "encoding",724+ [725+ "utf-8",726+ "utf-8-sig",727+ "utf-16",728+ "utf-16-be",729+ "utf-16-le",730+ "utf-32",731+ "utf-32-be",732+ "utf-32-le",733+ ],734+)721-def test_json_without_specified_encoding():735+def test_json_without_specified_charset(encoding):736 data = {"greeting": "hello", "recipient": "world"}723- content = json.dumps(data).encode("utf-32-be")737+ content = json.dumps(data).encode(encoding)738 headers = {"Content-Type": "application/json"}739 response = httpx.Response(740 200,741 content=content,1 unmodified line743 )744 assert response.json() == data745 746 733-def test_json_without_specified_encoding_decode_error():747+@pytest.mark.parametrize(748+ "encoding",749+ [750+ "utf-8",751+ "utf-8-sig",752+ "utf-16",753+ "utf-16-be",754+ "utf-16-le",755+ "utf-32",756+ "utf-32-be",757+ "utf-32-le",758+ ],759+)760+def test_json_with_specified_charset(encoding):761 data = {"greeting": "hello", "recipient": "world"}735- content = json.dumps(data).encode("utf-32-be")736- headers = {"Content-Type": "application/json"}737- # force incorrect guess from `guess_json_utf` to trigger error738- with mock.patch("httpx._models.guess_json_utf", return_value="utf-32-le"):739- response = httpx.Response(740- 200,741- content=content,742- headers=headers,743- )744- with pytest.raises(json.decoder.JSONDecodeError):745- response.json()762+ content = json.dumps(data).encode(encoding)763+ headers = {"Content-Type": f"application/json; charset={encoding}"}764+ response = httpx.Response(765+ 200,766+ content=content,767+ headers=headers,768+ )769+ assert response.json() == data770 771 748-def test_json_without_specified_encoding_value_error():749- data = {"greeting": "hello", "recipient": "world"}750- content = json.dumps(data).encode("utf-32-be")751- headers = {"Content-Type": "application/json"}752- # force incorrect guess from `guess_json_utf` to trigger error753- with mock.patch("httpx._models.guess_json_utf", return_value="utf-32-le"):754- response = httpx.Response(200, content=content, headers=headers)755- with pytest.raises(json.decoder.JSONDecodeError):756- response.json()757-758-772 @pytest.mark.parametrize(773 "headers, expected",774 [775 (129 unmodified linesmodified:tests/test_decoders.py+5 added-6 removed
177 unmodified lines178 ["data", "encoding"],179 [180 ((b"Hello,", b" world!"), "ascii"),181 ((b"\xe3\x83", b"\x88\xe3\x83\xa9", b"\xe3", b"\x83\x99\xe3\x83\xab"), "utf-8"),182- ((b"Euro character: \x88!", b""), "cp1252"),183- ((b"Accented: \xd6sterreich", b""), "iso-8859-1"),182+ ((b"Euro character: \x88! abcdefghijklmnopqrstuvwxyz", b""), "cp1252"),183+ ((b"Accented: \xd6sterreich abcdefghijklmnopqrstuvwxyz", b""), "iso-8859-1"),184 ],185 )186 @pytest.mark.asyncio187 async def test_text_decoder(data, encoding):10 unmodified lines198 await response.aread()199 assert response.text == (b"".join(data)).decode(encoding)200 201 # Streaming `.aiter_text` iteratively.202- response = httpx.Response(203- 200,204- content=iterator(),205- )202+ # Note that if we streamed the text *without* having read it first, then203+ # we won't get a `charset_normalizer` guess, and will instead always rely204+ # on utf-8 if no charset is specified.205 text = "".join([part async for part in response.aiter_text()])206 assert text == (b"".join(data)).decode(encoding)207 208 149 unmodified linesmodified:README.md+1 added
117 unmodified lines118 * `httpcore` - The underlying transport implementation for `httpx`.119 * `h11` - HTTP/1.1 support.120 * `h2` - HTTP/2 support. *(Optional)*121 * `certifi` - SSL certificates.122+* `charset_normalizer` - Charset auto-detection.123 * `rfc3986` - URL parsing & normalization.124 * `idna` - Internationalized domain name support.125 * `sniffio` - Async library autodetection.126 * `async_generator` - Backport support for `contextlib.asynccontextmanager`. *(Only required for Python 3.6)*8 unmodified linesmodified:setup.py+1 added
55 unmodified lines56 include_package_data=True,57 zip_safe=False,58 install_requires=[59 "certifi",60+ "charset_normalizer",61 "sniffio",62 "rfc3986[idna2008]>=1.3,<2",63 "httpcore>=0.13.3,<0.14.0",64 "async_generator; python_version < '3.7'"23 unmodified lines