Drop chardet (#1269)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Internal refactoring to swap auth/redirects ordering * Drop chardet for charset detection * Drop chardet in favour of simpler charset autodetection * Revert unintentionally included changes * Update test case * Refactor to prefer different decoding style * Update text decoding docs/docstrings * Resolve typo * Update docs/quickstart.md Co-authored-by: Florimond Manca <florimond.manca@gmail.com>
authored by Tom Christie · committed by GitHub · parent 2d6c30d · Browse files · 7 files·+125 added−109 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: Florimond Manca <florimond.manca@gmail.com>
Diff stats
7 files+125 added−109 removed
- tests:+56 added−28 removed
- other:+69 added−81 removed
Provenance
- Commit
d0fe113- Tree
5d8ae83- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
2d6c30d
7 files changed+125 added−109 removed
modified:docs/quickstart.md+15 added-2 removed
63 unmodified lines64 >>> r.text65 '<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'66 ```67 68-You can inspect what encoding has been used to decode the response.68+You can inspect what encoding will be used to decode the response.69 70 ```pycon71 >>> r.encoding72 'UTF-8'73 ```74 75+In some cases the response may not contain an explicit encoding, in which case HTTPX76+will attempt to automatically determine an encoding to use. This defaults to77+UTF-8, but also includes robust fallback behaviour for handling ascii,78+iso-8859-1 and windows 1252 encodings.79+80+```pycon81+>>> r.encoding82+None83+>>> r.text84+'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'85+```86+87+75-If you need to override the standard behavior and explicitly set the encoding to88+If you need to override the standard behaviour and explicitly set the encoding to89 use, then you can do that too.90 91 ```pycon92 >>> r.encoding = 'ISO-8859-1'394 unmodified linesmodified:httpx/_decoders.py+38 added-50 removed
5 unmodified lines6 import codecs7 import typing8 import zlib9 10-import chardet11-10 try:11 import brotli12 except ImportError: # pragma: nocover13 brotli = None146 unmodified lines160 Handles incrementally decoding bytes into text161 """162 163 def __init__(self, encoding: typing.Optional[str] = None):166- self.decoder: typing.Optional[codecs.IncrementalDecoder] = (167- None if encoding is None else codecs.getincrementaldecoder(encoding)()168- )169- self.detector = chardet.universaldetector.UniversalDetector()164+ self.decoder: typing.Optional[codecs.IncrementalDecoder] = None165+ if encoding is not None:166+ self.decoder = codecs.getincrementaldecoder(encoding)(errors="strict")167 171- # This buffer is only needed if 'decoder' is 'None'172- # we want to trigger errors if data is getting added to173- # our internal buffer for some silly reason while174- # a decoder is discovered.175- self.buffer: typing.Optional[bytearray] = None if self.decoder else bytearray()176-168 def decode(self, data: bytes) -> str:178- try:179- if self.decoder is not None:180- text = self.decoder.decode(data)181- else:182- assert self.buffer is not None183- text = ""184- self.detector.feed(data)185- self.buffer += data169+ """170+ If an encoding is explicitly specified, then we use that.171+ Otherwise our strategy is to attempt UTF-8, and fallback to Windows 1252.172 187- # Should be more than enough data to process, we don't188- # want to buffer too long as chardet will wait until189- # detector.close() is used to give back common190- # encodings like 'utf-8'.191- if len(self.buffer) >= 4096:192- self.decoder = codecs.getincrementaldecoder(193- self._detector_result()194- )()195- text = self.decoder.decode(bytes(self.buffer), False)196- self.buffer = None173+ Note that UTF-8 is a strict superset of ascii, and Windows 1252 is a174+ superset of the non-control characters in iso-8859-1, so we essentially175+ end up supporting any of ascii, utf-8, iso-8859-1, cp1252.176 198- return text199- except UnicodeDecodeError as exc: # pragma: nocover200- raise ValueError(str(exc))177+ Given that UTF-8 is now by *far* the most widely used encoding, this178+ should be a pretty robust strategy for cases where a charset has179+ not been explicitly included.180 202- def flush(self) -> str:203- try:204- if self.decoder is None:205- # Empty string case as chardet is guaranteed to not have a guess.206- assert self.buffer is not None207- if len(self.buffer) == 0:208- return ""209- return bytes(self.buffer).decode(self._detector_result())181+ Useful stats on the prevalence of different charsets in the wild...182 211- return self.decoder.decode(b"", True)212- except UnicodeDecodeError as exc: # pragma: nocover213- raise ValueError(str(exc))183+ * https://w3techs.com/technologies/overview/character_encoding184+ * https://w3techs.com/technologies/history_overview/character_encoding185 215- def _detector_result(self) -> str:216- self.detector.close()217- result = self.detector.result["encoding"]218- if not result: # pragma: nocover219- raise ValueError("Unable to determine encoding of content")186+ The HTML5 spec also has some useful guidelines, suggesting defaults of187+ either UTF-8 or Windows 1252 in most cases...188 221- return result189+ * https://dev.w3.org/html5/spec-LC/Overview.html190+ """191+ if self.decoder is None:192+ # If this is the first decode pass then we need to determine which193+ # encoding to use by attempting UTF-8 and raising any decode errors.194+ attempt_utf_8 = codecs.getincrementaldecoder("utf-8")(errors="strict")195+ try:196+ attempt_utf_8.decode(data)197+ except UnicodeDecodeError:198+ # Could not decode as UTF-8. Use Windows 1252.199+ self.decoder = codecs.getincrementaldecoder("cp1252")(errors="replace")200+ else:201+ # Can decode as UTF-8. Use UTF-8 with lenient error settings.202+ self.decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")203 204+ return self.decoder.decode(data)205 206+ def flush(self) -> str:207+ if self.decoder is None:208+ return ""209+ return self.decoder.decode(b"", True)210+211+212 class LineDecoder:213 """214 Handles incrementally reading lines from text.215 73 unmodified linesmodified:httpx/_models.py+16 added-28 removed
8 unmodified lines9 from collections.abc import MutableMapping10 from http.cookiejar import Cookie, CookieJar11 from urllib.parse import parse_qsl, quote, unquote, urlencode12 13-import chardet13 import rfc398614 import rfc3986.exceptions15 16 from ._content_streams import ByteStream, ContentStream, encode, encode_response736 unmodified lines753 content = self.content754 if not content:755 self._text = ""756 else:758- encoding = self.encoding759- self._text = content.decode(encoding, errors="replace")757+ decoder = TextDecoder(encoding=self.encoding)758+ self._text = "".join([decoder.decode(self.content), decoder.flush()])759 return self._text760 761 @property763- def encoding(self) -> str:762+ def encoding(self) -> typing.Optional[str]:763+ """764+ Return the encoding, which may have been set explicitly, or may have765+ been specified by the Content-Type header.766+ """767 if not hasattr(self, "_encoding"):768 encoding = self.charset_encoding769 if encoding is None or not is_known_encoding(encoding):767- encoding = self.apparent_encoding768- if encoding is None or not is_known_encoding(encoding):769- encoding = "utf-8"770- self._encoding = encoding770+ self._encoding = None771+ else:772+ self._encoding = encoding773 return self._encoding774 775 @encoding.setter776 def encoding(self, value: str) -> None:7 unmodified lines784 content_type = self.headers.get("Content-Type")785 if content_type is None:786 return None787 786- parsed = cgi.parse_header(content_type)787- media_type, params = parsed[0], parsed[-1]788- if "charset" in params:789- return params["charset"].strip("'\"")788+ _, params = cgi.parse_header(content_type)789+ if "charset" not in params:790+ return None791 791- # RFC 2616 specifies that 'iso-8859-1' should be used as the default792- # for 'text/*' media types, if no charset is provided.793- # See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1794- if media_type.startswith("text/"):795- return "iso-8859-1"792+ return params["charset"].strip("'\"")793 797- return None798-799- @property800- def apparent_encoding(self) -> typing.Optional[str]:801- """802- Return the encoding, as it appears to autodetection.803- """804- return chardet.detect(self.content)["encoding"]805-794 def _get_content_decoder(self) -> ContentDecoder:795 """796 Returns a decoder instance which can be used to decode the raw byte797 content, depending on the Content-Encoding used in the response.125 unmodified lines923 A str-iterator over the decoded response content924 that handles both gzip, deflate, etc but also detects the content's925 string encoding.926 """939- decoder = TextDecoder(encoding=self.charset_encoding)927+ decoder = TextDecoder(encoding=self.encoding)928 with self._wrap_decoder_errors():929 for chunk in self.iter_bytes():930 yield decoder.decode(chunk)931 yield decoder.flush()75 unmodified lines1007 A str-iterator over the decoded response content1008 that handles both gzip, deflate, etc but also detects the content's1009 string encoding.1010 """1023- decoder = TextDecoder(encoding=self.charset_encoding)1011+ decoder = TextDecoder(encoding=self.encoding)1012 with self._wrap_decoder_errors():1013 async for chunk in self.aiter_bytes():1014 yield decoder.decode(chunk)1015 yield decoder.flush()230 unmodified linesmodified:tests/client/test_client.py+1 added-1 removed
13 unmodified lines14 assert response.url == url15 assert response.content == b"Hello, world!"16 assert response.text == "Hello, world!"17 assert response.http_version == "HTTP/1.1"18- assert response.encoding == "iso-8859-1"18+ assert response.encoding is None19 assert response.request.url == url20 assert response.headers21 assert response.is_redirect is False22 assert repr(response) == "<Response [200 OK]>"253 unmodified linesmodified:tests/models/test_responses.py+53 added-17 removed
79 unmodified lines80 81 82 def test_response_autodetect_encoding():83 """84- Autodetect encoding if there is no charset info in a Content-Type header.84+ Autodetect encoding if there is no Content-Type header.85 """86- content = "おはようございます。".encode("EUC-JP")86+ content = "おはようございます。".encode("utf-8")87 response = httpx.Response(88 200,89 content=content,90 )91 assert response.text == "おはようございます。"92- assert response.encoding == "EUC-JP"92+ assert response.encoding is None93 94 95 def test_response_fallback_to_autodetect():96 """97 Fallback to autodetection if we get an invalid charset in the Content-Type header.98 """99 headers = {"Content-Type": "text-plain; charset=invalid-codec-name"}100- content = "おはようございます。".encode("EUC-JP")100+ content = "おはようございます。".encode("utf-8")101 response = httpx.Response(102 200,103 content=content,104 headers=headers,105 )106 assert response.text == "おはようございます。"107- assert response.encoding == "EUC-JP"107+ assert response.encoding is None108 109 110-def test_response_default_text_encoding():110+def test_response_no_charset_with_ascii_content():111 """112- A media type of 'text/*' with no charset should default to ISO-8859-1.113- See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1112+ A response with ascii encoded content should decode correctly,113+ even with no charset specified.114 """115 content = b"Hello, world!"116 headers = {"Content-Type": "text/plain"}117 response = httpx.Response(1 unmodified line119 content=content,120 headers=headers,121 )122 assert response.status_code == 200123- assert response.encoding == "iso-8859-1"123+ assert response.encoding is None124 assert response.text == "Hello, world!"125 126 127-def test_response_default_encoding():127+def test_response_no_charset_with_utf8_content():128 """129- Default to utf-8 if all else fails.129+ A response with UTF-8 encoded content should decode correctly,130+ even with no charset specified.131 """132+ content = "Unicode Snowman: ☃".encode("utf-8")133+ headers = {"Content-Type": "text/plain"}134 response = httpx.Response(135 200,133- content=b"",136+ content=content,137+ headers=headers,138 )135- assert response.text == ""136- assert response.encoding == "utf-8"139+ assert response.text == "Unicode Snowman: ☃"140+ assert response.encoding is None141 142 143+def test_response_no_charset_with_iso_8859_1_content():144+ """145+ A response with ISO 8859-1 encoded content should decode correctly,146+ even with no charset specified.147+ """148+ content = "Accented: Österreich".encode("iso-8859-1")149+ headers = {"Content-Type": "text/plain"}150+ response = httpx.Response(151+ 200,152+ content=content,153+ headers=headers,154+ )155+ assert response.text == "Accented: Österreich"156+ assert response.encoding is None157+158+159+def test_response_no_charset_with_cp_1252_content():160+ """161+ A response with Windows 1252 encoded content should decode correctly,162+ even with no charset specified.163+ """164+ content = "Euro Currency: €".encode("cp1252")165+ headers = {"Content-Type": "text/plain"}166+ response = httpx.Response(167+ 200,168+ content=content,169+ headers=headers,170+ )171+ assert response.text == "Euro Currency: €"172+ assert response.encoding is None173+174+175 def test_response_non_text_encoding():176 """177 Default to apparent encoding for non-text content-type headers.178 """3 unmodified lines182 content=b"xyz",183 headers=headers,184 )185 assert response.text == "xyz"150- assert response.encoding == "ascii"186+ assert response.encoding is None187 188 189 def test_response_set_explicit_encoding():190 headers = {28 unmodified lines219 )220 221 assert response.status_code == 200222 assert response.text == "Hello, world!"187- assert response.encoding == "ascii"223+ assert response.encoding is None224 assert response.is_closed225 226 content = response.read()227 10 unmodified lines238 )239 240 assert response.status_code == 200241 assert response.text == "Hello, world!"206- assert response.encoding == "ascii"242+ assert response.encoding is None243 assert response.is_closed244 245 content = await response.aread()246 366 unmodified linesmodified:tests/test_decoders.py+2 added-10 removed
175 unmodified lines176 ["data", "encoding"],177 [178 ((b"Hello,", b" world!"), "ascii"),179 ((b"\xe3\x83", b"\x88\xe3\x83\xa9", b"\xe3", b"\x83\x99\xe3\x83\xab"), "utf-8"),180- ((b"\x83g\x83\x89\x83x\x83\x8b",) * 64, "shift-jis"),181- ((b"\x83g\x83\x89\x83x\x83\x8b",) * 600, "shift-jis"),182- (183- (b"\xcb\xee\xf0\xe5\xec \xe8\xef\xf1\xf3\xec \xe4\xee\xeb\xee\xf0",) * 64,184- "MacCyrillic",185- ),186- (187- (b"\xa5\xa6\xa5\xa7\xa5\xd6\xa4\xce\xb9\xf1\xba\xdd\xb2\xbd",) * 512,188- "euc-jp",189- ),180+ ((b"Euro character: \x88!", b""), "cp1252"),181+ ((b"Accented: \xd6sterreich", b""), "iso-8859-1"),182 ],183 )184 @pytest.mark.asyncio185 async def test_text_decoder(data, encoding):127 unmodified linesmodified:setup.py-1 removed
55 unmodified lines56 zip_safe=False,57 install_requires=[58 "certifi",59 "sniffio",60- "chardet==3.*",60 "rfc3986[idna2008]>=1.3,<2",61 "httpcore==0.10.*",62 ],63 extras_require={19 unmodified lines