Make charset auto-detection optional. (#2165)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Add Response(..., default_encoding=...) * Add tests for Response(..., default_encoding=...) * Add Client(..., default_encoding=...) * Switch default encoding to 'utf-8' instead of 'autodetect' * Make charset_normalizer an optional dependancy, not a mandatory one. * Documentation * Use callable for default_encoding * Update tests for new charset autodetection API * Update docs for new charset autodetection API * Update requirements * Drop charset_normalizer from requirements
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
11 files+245 added−54 removed
- tests:+134 added−30 removed
- other:+111 added−24 removed
Provenance
- Commit
1c33a28- Tree
f86188b- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
940d61b
11 files changed+245 added−54 removed
modified:docs/advanced.md+82 added
143 unmodified lines144 ```145 146 For a list of all available client parameters, see the [`Client`](api.md#client) API reference.147 148+---149+150+## Character set encodings and auto-detection151+152+When accessing `response.text`, we need to decode the response bytes into a unicode text representation.153+154+By default `httpx` will use `"charset"` information included in the response `Content-Type` header to determine how the response bytes should be decoded into text.155+156+In cases where no charset information is included on the response, the default behaviour is to assume "utf-8" encoding, which is by far the most widely used text encoding on the internet.157+158+### Using the default encoding159+160+To understand this better let's start by looking at the default behaviour for text decoding...161+162+```python163+import httpx164+# Instantiate a client with the default configuration.165+client = httpx.Client()166+# Using the client...167+response = client.get(...)168+print(response.encoding) # This will either print the charset given in169+ # the Content-Type charset, or else "utf-8".170+print(response.text) # The text will either be decoded with the Content-Type171+ # charset, or using "utf-8".172+```173+174+This is normally absolutely fine. Most servers will respond with a properly formatted Content-Type header, including a charset encoding. And in most cases where no charset encoding is included, UTF-8 is very likely to be used, since it is so widely adopted.175+176+### Using an explicit encoding177+178+In some cases we might be making requests to a site where no character set information is being set explicitly by the server, but we know what the encoding is. In this case it's best to set the default encoding explicitly on the client.179+180+```python181+import httpx182+# Instantiate a client with a Japanese character set as the default encoding.183+client = httpx.Client(default_encoding="shift-jis")184+# Using the client...185+response = client.get(...)186+print(response.encoding) # This will either print the charset given in187+ # the Content-Type charset, or else "shift-jis".188+print(response.text) # The text will either be decoded with the Content-Type189+ # charset, or using "shift-jis".190+```191+192+### Using character set auto-detection193+194+In cases where the server is not reliably including character set information, and where we don't know what encoding is being used, we can enable auto-detection to make a best-guess attempt when decoding from bytes to text.195+196+To use auto-detection you need to set the `default_encoding` argument to a callable instead of a string. This callable should be a function which takes the input bytes as an argument and returns the character set to use for decoding those bytes to text.197+198+There are two widely used Python packages which both handle this functionality:199+200+* [`chardet`](https://chardet.readthedocs.io/) - This is a well established package, and is a port of [the auto-detection code in Mozilla](https://www-archive.mozilla.org/projects/intl/chardet.html).201+* [`charset-normalizer`](https://charset-normalizer.readthedocs.io/) - A newer package, motivated by `chardet`, with a different approach.202+203+Let's take a look at installing autodetection using one of these packages...204+205+ ```shell206+$ pip install httpx207+$ pip install chardet208+ ```209+210+Once `chardet` is installed, we can configure a client to use character-set autodetection.211+212+```python213+import httpx214+import chardet215+216+def autodetect(content):217+ return chardet.detect(content).get("encoding")218+219+# Using a client with character-set autodetection enabled.220+client = httpx.Client(default_encoding=autodetect)221+response = client.get(...)222+print(response.encoding) # This will either print the charset given in223+ # the Content-Type charset, or else the auto-detected224+ # character set.225+print(response.text)226+```227+228+---229+230 ## Calling into Python Web Apps231 232 You can configure an `httpx` client to call directly into a Python web application using the WSGI protocol.233 1026 unmodified linesmodified:docs/index.md-1 removed
107 unmodified linesExpand all10810911011111211211311411535 unmodified lines107 unmodified linesExpand all
* `httpcore` - The underlying transport implementation for `httpx`. * `h11` - HTTP/1.1 support.* `certifi` - SSL certificates.* `charset_normalizer` - Charset auto-detection.* `rfc3986` - URL parsing & normalization. * `idna` - Internationalized domain name support.* `sniffio` - Async library autodetection.
35 unmodified linesmodified:httpx/_client.py+14 added
166 unmodified lines167 typing.Mapping[str, typing.List[typing.Callable]]168 ] = None,169 base_url: URLTypes = "",170 trust_env: bool = True,171+ default_encoding: typing.Union[str, typing.Callable[[bytes], str]] = "utf-8",172 ):173 event_hooks = {} if event_hooks is None else event_hooks174 175 self._base_url = self._enforce_trailing_slash(URL(base_url))9 unmodified lines185 "request": list(event_hooks.get("request", [])),186 "response": list(event_hooks.get("response", [])),187 }188 self._trust_env = trust_env189+ self._default_encoding = default_encoding190 self._netrc = NetRCInfo()191 self._state = ClientState.UNOPENED192 193 @property418 unmodified lines612 * **app** - *(optional)* An WSGI application to send requests to,613 rather than sending actual network requests.614 * **trust_env** - *(optional)* Enables or disables usage of environment615 variables for configuration.616+ * **default_encoding** - *(optional)* The default encoding to use for decoding617+ response text, if no charset information is included in a response Content-Type618+ header. Set to a callable for automatic character set detection. Default: "utf-8".619 """620 621 def __init__(622 self,18 unmodified lines641 base_url: URLTypes = "",642 transport: typing.Optional[BaseTransport] = None,643 app: typing.Optional[typing.Callable] = None,644 trust_env: bool = True,645+ default_encoding: typing.Union[str, typing.Callable[[bytes], str]] = "utf-8",646 ):647 super().__init__(648 auth=auth,649 params=params,4 unmodified lines654 max_redirects=max_redirects,655 event_hooks=event_hooks,656 base_url=base_url,657 trust_env=trust_env,658+ default_encoding=default_encoding,659 )660 661 if http2:662 try:345 unmodified lines1008 response.stream = BoundSyncStream(1009 response.stream, response=response, timer=timer1010 )1011 self.cookies.extract_cookies(response)1012+ response.default_encoding = self._default_encoding1013 1014 status = f"{response.status_code} {response.reason_phrase}"1015 response_line = f"{response.http_version} {status}"1016 logger.debug(316 unmodified lines1333 * **app** - *(optional)* An ASGI application to send requests to,1334 rather than sending actual network requests.1335 * **trust_env** - *(optional)* Enables or disables usage of environment1336 variables for configuration.1337+ * **default_encoding** - *(optional)* The default encoding to use for decoding1338+ response text, if no charset information is included in a response Content-Type1339+ header. Set to a callable for automatic character set detection. Default: "utf-8".1340 """1341 1342 def __init__(1343 self,18 unmodified lines1362 base_url: URLTypes = "",1363 transport: typing.Optional[AsyncBaseTransport] = None,1364 app: typing.Optional[typing.Callable] = None,1365 trust_env: bool = True,1366+ default_encoding: str = "utf-8",1367 ):1368 super().__init__(1369 auth=auth,1370 params=params,4 unmodified lines1375 max_redirects=max_redirects,1376 event_hooks=event_hooks,1377 base_url=base_url,1378 trust_env=trust_env,1379+ default_encoding=default_encoding,1380 )1381 1382 if http2:1383 try:336 unmodified lines1720 response.stream = BoundAsyncStream(1721 response.stream, response=response, timer=timer1722 )1723 self.cookies.extract_cookies(response)1724+ response.default_encoding = self._default_encoding1725 1726 status = f"{response.status_code} {response.reason_phrase}"1727 response_line = f"{response.http_version} {status}"1728 logger.debug(272 unmodified linesmodified:httpx/_models.py+11 added-19 removed
5 unmodified lines6 import urllib.request7 from collections.abc import MutableMapping8 from http.cookiejar import Cookie, CookieJar9 10-import charset_normalizer11-10 from ._content import ByteStream, UnattachedStream, encode_request, encode_response11 from ._decoders import (12 SUPPORTED_DECODERS,13 ByteChunker,428 unmodified lines442 stream: typing.Union[SyncByteStream, AsyncByteStream, None] = None,443 request: typing.Optional[Request] = None,444 extensions: typing.Optional[dict] = None,445 history: typing.Optional[typing.List["Response"]] = None,446+ default_encoding: typing.Union[str, typing.Callable[[bytes], str]] = "utf-8",447 ):448 self.status_code = status_code449 self.headers = Headers(headers)450 8 unmodified lines459 460 self.is_closed = False461 self.is_stream_consumed = False462 463+ self.default_encoding = default_encoding464+465 if stream is None:466 headers, stream = encode_response(content, text, html, json)467 self._prepare(headers)468 self.stream = stream100 unmodified lines569 The priority for determining this is given by...570 571 * `.encoding = <>` has been set explicitly.572 * The encoding as specified by the charset parameter in the Content-Type header.572- * The encoding as determined by `charset_normalizer`.573- * UTF-8.573+ * The encoding as determined by `default_encoding`, which may either be574+ a string like "utf-8" indicating the encoding to use, or may be a callable575+ which enables charset autodetection.576 """577 if not hasattr(self, "_encoding"):578 encoding = self.charset_encoding579 if encoding is None or not is_known_encoding(encoding):578- encoding = self.apparent_encoding579- self._encoding = encoding580+ if isinstance(self.default_encoding, str):581+ encoding = self.default_encoding582+ elif hasattr(self, "_content"):583+ encoding = self.default_encoding(self._content)584+ self._encoding = encoding or "utf-8"585 return self._encoding586 587 @encoding.setter588 def encoding(self, value: str) -> None:13 unmodified lines602 return None603 604 return params["charset"].strip("'\"")605 601- @property602- def apparent_encoding(self) -> typing.Optional[str]:603- """604- Return the encoding, as determined by `charset_normalizer`.605- """606- content = getattr(self, "_content", b"")607- if len(content) < 32:608- # charset_normalizer will issue warnings if we run it with609- # fewer bytes than this cutoff.610- return None611- match = charset_normalizer.from_bytes(self.content).best()612- return None if match is None else match.encoding613-606 def _get_content_decoder(self) -> ContentDecoder:607 """608 Returns a decoder instance which can be used to decode the raw byte609 content, depending on the Content-Encoding used in the response.587 unmodified linesmodified:tests/client/test_client.py+61 added-1 removed
1 import typing2 from datetime import timedelta3 4+import chardet5 import pytest6 7 import httpx8 9 10+def autodetect(content):11+ return chardet.detect(content).get("encoding")12+13+14 def test_get(server):15 url = server.url16 with httpx.Client(http2=True) as http:17 response = http.get(url)1 unmodified line19 assert response.url == url20 assert response.content == b"Hello, world!"21 assert response.text == "Hello, world!"22 assert response.http_version == "HTTP/1.1"18- assert response.encoding is None23+ assert response.encoding == "utf-8"24 assert response.request.url == url25 assert response.headers26 assert response.is_redirect is False27 assert repr(response) == "<Response [200 OK]>"374 unmodified lines402 with httpx.Client(http2=True) as client:403 response = client.get(url)404 assert response.status_code == 200405 assert response.extensions["http_version"] == b"HTTP/1.1"406+407+408+def test_client_decode_text_using_autodetect():409+ # Ensure that a 'default_encoding=autodetect' on the response allows for410+ # encoding autodetection to be used when no "Content-Type: text/plain; charset=..."411+ # info is present.412+ #413+ # Here we have some french text encoded with ISO-8859-1, rather than UTF-8.414+ text = (415+ "Non-seulement Despréaux ne se trompait pas, mais de tous les écrivains "416+ "que la France a produits, sans excepter Voltaire lui-même, imprégné de "417+ "l'esprit anglais par son séjour à Londres, c'est incontestablement "418+ "Molière ou Poquelin qui reproduit avec l'exactitude la plus vive et la "419+ "plus complète le fond du génie français."420+ )421+422+ def cp1252_but_no_content_type(request):423+ content = text.encode("ISO-8859-1")424+ return httpx.Response(200, content=content)425+426+ transport = httpx.MockTransport(cp1252_but_no_content_type)427+ with httpx.Client(transport=transport, default_encoding=autodetect) as client:428+ response = client.get("http://www.example.com")429+430+ assert response.status_code == 200431+ assert response.reason_phrase == "OK"432+ assert response.encoding == "ISO-8859-1"433+ assert response.text == text434+435+436+def test_client_decode_text_using_explicit_encoding():437+ # Ensure that a 'default_encoding="..."' on the response is used for text decoding438+ # when no "Content-Type: text/plain; charset=..."" info is present.439+ #440+ # Here we have some french text encoded with ISO-8859-1, rather than UTF-8.441+ text = (442+ "Non-seulement Despréaux ne se trompait pas, mais de tous les écrivains "443+ "que la France a produits, sans excepter Voltaire lui-même, imprégné de "444+ "l'esprit anglais par son séjour à Londres, c'est incontestablement "445+ "Molière ou Poquelin qui reproduit avec l'exactitude la plus vive et la "446+ "plus complète le fond du génie français."447+ )448+449+ def cp1252_but_no_content_type(request):450+ content = text.encode("ISO-8859-1")451+ return httpx.Response(200, content=content)452+453+ transport = httpx.MockTransport(cp1252_but_no_content_type)454+ with httpx.Client(transport=transport, default_encoding=autodetect) as client:455+ response = client.get("http://www.example.com")456+457+ assert response.status_code == 200458+ assert response.reason_phrase == "OK"459+ assert response.encoding == "ISO-8859-1"460+ assert response.text == textmodified:tests/models/test_responses.py+67 added-24 removed
1 import json2 import pickle3 4+import chardet5 import pytest6 7 import httpx8 from httpx._compat import brotli14 unmodified lines23 yield b"Hello, "24 yield b"world!"25 26 27+def autodetect(content):28+ return chardet.detect(content).get("encoding")29+30+31 def test_response():32 response = httpx.Response(33 200,34 content=b"Hello, world!",133 unmodified lines168 assert response.text == "Latin 1: ÿ"169 assert response.encoding == "latin-1"170 171 167-def test_response_autodetect_encoding():172+def test_response_default_to_utf8_encoding():173 """169- Autodetect encoding if there is no Content-Type header.174+ Default to utf-8 encoding if there is no Content-Type header.175 """176 content = "おはようございます。".encode("utf-8")177 response = httpx.Response(178 200,179 content=content,180 )181 assert response.text == "おはようございます。"177- assert response.encoding is None182+ assert response.encoding == "utf-8"183 184 180-def test_response_fallback_to_autodetect():185+def test_response_fallback_to_utf8_encoding():186 """182- Fallback to autodetection if we get an invalid charset in the Content-Type header.187+ Fallback to utf-8 if we get an invalid charset in the Content-Type header.188 """189 headers = {"Content-Type": "text-plain; charset=invalid-codec-name"}190 content = "おはようございます。".encode("utf-8")191 response = httpx.Response(1 unmodified line193 content=content,194 headers=headers,195 )196 assert response.text == "おはようございます。"192- assert response.encoding is None197+ assert response.encoding == "utf-8"198 199 200 def test_response_no_charset_with_ascii_content():201 """7 unmodified lines209 content=content,210 headers=headers,211 )212 assert response.status_code == 200208- assert response.encoding is None213+ assert response.encoding == "utf-8"214 assert response.text == "Hello, world!"215 216 217 def test_response_no_charset_with_utf8_content():8 unmodified lines226 content=content,227 headers=headers,228 )229 assert response.text == "Unicode Snowman: ☃"225- assert response.encoding is None230+ assert response.encoding == "utf-8"231 232 233 def test_response_no_charset_with_iso_8859_1_content():234 """235 A response with ISO 8859-1 encoded content should decode correctly,231- even with no charset specified.236+ even with no charset specified, if autodetect is enabled.237 """238 content = "Accented: Österreich abcdefghijklmnopqrstuzwxyz".encode("iso-8859-1")239 headers = {"Content-Type": "text/plain"}240 response = httpx.Response(236- 200,237- content=content,238- headers=headers,241+ 200, content=content, headers=headers, default_encoding=autodetect242 )243 assert response.text == "Accented: Österreich abcdefghijklmnopqrstuzwxyz"244 assert response.charset_encoding is None242- assert response.apparent_encoding is not None245 246 247 def test_response_no_charset_with_cp_1252_content():248 """249 A response with Windows 1252 encoded content should decode correctly,248- even with no charset specified.250+ even with no charset specified, if autodetect is enabled.251 """252 content = "Euro Currency: € abcdefghijklmnopqrstuzwxyz".encode("cp1252")253 headers = {"Content-Type": "text/plain"}254 response = httpx.Response(253- 200,254- content=content,255- headers=headers,255+ 200, content=content, headers=headers, default_encoding=autodetect256 )257 assert response.text == "Euro Currency: € abcdefghijklmnopqrstuzwxyz"258 assert response.charset_encoding is None259- assert response.apparent_encoding is not None259 260 261 def test_response_non_text_encoding():262 """264- Default to apparent encoding for non-text content-type headers.263+ Default to attempting utf-8 encoding for non-text content-type headers.264 """265 headers = {"Content-Type": "image/png"}266 response = httpx.Response(267 200,268 content=b"xyz",269 headers=headers,270 )271 assert response.text == "xyz"273- assert response.encoding is None272+ assert response.encoding == "utf-8"273 274 275 def test_response_set_explicit_encoding():276 headers = {28 unmodified lines305 )306 307 assert response.status_code == 200308 assert response.text == "Hello, world!"310- assert response.encoding is None309+ assert response.encoding == "utf-8"310 assert response.is_closed311 312 content = response.read()313 6 unmodified lines320 response = httpx.Response(200)321 322 assert response.status_code == 200323 assert response.text == ""325- assert response.encoding is None324+ assert response.encoding == "utf-8"325 assert response.is_closed326 327 content = response.read()328 10 unmodified lines339 )340 341 assert response.status_code == 200342 assert response.text == "Hello, world!"344- assert response.encoding is None343+ assert response.encoding == "utf-8"344 assert response.is_closed345 346 content = await response.aread()347 7 unmodified lines355 response = httpx.Response(200)356 357 assert response.status_code == 200358 assert response.text == ""360- assert response.encoding is None359+ assert response.encoding == "utf-8"360 assert response.is_closed361 362 content = await response.aread()363 602 unmodified lines966 pickle_response = pickle.loads(pickle.dumps(response))967 assert pickle_response.is_stream_consumed is True968 assert pickle_response.content == b"Hello, world!"969 assert pickle_response.num_bytes_downloaded == 13970+971+972+def test_response_decode_text_using_autodetect():973+ # Ensure that a 'default_encoding="autodetect"' on the response allows for974+ # encoding autodetection to be used when no "Content-Type: text/plain; charset=..."975+ # info is present.976+ #977+ # Here we have some french text encoded with ISO-8859-1, rather than UTF-8.978+ text = (979+ "Non-seulement Despréaux ne se trompait pas, mais de tous les écrivains "980+ "que la France a produits, sans excepter Voltaire lui-même, imprégné de "981+ "l'esprit anglais par son séjour à Londres, c'est incontestablement "982+ "Molière ou Poquelin qui reproduit avec l'exactitude la plus vive et la "983+ "plus complète le fond du génie français."984+ )985+ content = text.encode("ISO-8859-1")986+ response = httpx.Response(200, content=content, default_encoding=autodetect)987+988+ assert response.status_code == 200989+ assert response.reason_phrase == "OK"990+ assert response.encoding == "ISO-8859-1"991+ assert response.text == text992+993+994+def test_response_decode_text_using_explicit_encoding():995+ # Ensure that a 'default_encoding="..."' on the response is used for text decoding996+ # when no "Content-Type: text/plain; charset=..."" info is present.997+ #998+ # Here we have some french text encoded with Windows-1252, rather than UTF-8.999+ # https://en.wikipedia.org/wiki/Windows-12521000+ text = (1001+ "Non-seulement Despréaux ne se trompait pas, mais de tous les écrivains "1002+ "que la France a produits, sans excepter Voltaire lui-même, imprégné de "1003+ "l'esprit anglais par son séjour à Londres, c'est incontestablement "1004+ "Molière ou Poquelin qui reproduit avec l'exactitude la plus vive et la "1005+ "plus complète le fond du génie français."1006+ )1007+ content = text.encode("cp1252")1008+ response = httpx.Response(200, content=content, default_encoding="cp1252")1009+1010+ assert response.status_code == 2001011+ assert response.reason_phrase == "OK"1012+ assert response.encoding == "cp1252"1013+ assert response.text == textmodified:tests/test_decoders.py+6 added-5 removed
1 import zlib2 3+import chardet4 import pytest5 6 import httpx7 from httpx._compat import brotli176 unmodified lines184 ((b"Accented: \xd6sterreich abcdefghijklmnopqrstuvwxyz", b""), "iso-8859-1"),185 ],186 )187 @pytest.mark.asyncio187-async def test_text_decoder(data, encoding):188+async def test_text_decoder_with_autodetect(data, encoding):189 async def iterator():190 nonlocal data191 for chunk in data:192 yield chunk193 194+ def autodetect(content):195+ return chardet.detect(content).get("encoding")196+197 # Accessing `.text` on a read response.194- response = httpx.Response(195- 200,196- content=iterator(),197- )198+ response = httpx.Response(200, content=iterator(), default_encoding=autodetect)199 await response.aread()200 assert response.text == (b"".join(data)).decode(encoding)201 202 # Streaming `.aiter_text` iteratively.156 unmodified linesmodified:README_chinese.md-1 removed
127 unmodified lines128 * `httpcore` - The underlying transport implementation for `httpx`.129 * `h11` - HTTP/1.1 support.130 * `h2` - HTTP/2 support. *(Optional, with `httpx[http2]`)*131 * `certifi` - SSL certificates.132-* `charset_normalizer` - Charset auto-detection.132 * `rfc3986` - URL parsing & normalization.133 * `idna` - Internationalized domain name support.134 * `sniffio` - Async library autodetection.135 * `rich` - Rich terminal support. *(Optional, with `httpx[cli]`)*9 unmodified linesmodified:README.md-1 removed
126 unmodified lines127 128 * `httpcore` - The underlying transport implementation for `httpx`.129 * `h11` - HTTP/1.1 support.130 * `certifi` - SSL certificates.131-* `charset_normalizer` - Charset auto-detection.131 * `rfc3986` - URL parsing & normalization.132 * `idna` - Internationalized domain name support.133 * `sniffio` - Async library autodetection.134 15 unmodified linesmodified:requirements.txt+4 added-1 removed
2 unmodified lines3 # needs to pass with the latest version of the packages.4 # Reference: https://github.com/encode/httpx/pull/1721#discussion_r6612415885 -e .[brotli,cli,http2,socks]6 7-charset-normalizer==2.0.67+# Optional charset auto-detection8+# Used in our test cases9+chardet==4.0.010+types-chardet==4.0.411 12 # Documentation13 mkdocs==1.3.014 mkautodoc==0.1.024 unmodified linesmodified:setup.py-1 removed
55 unmodified lines56 include_package_data=True,57 zip_safe=False,58 install_requires=[59 "certifi",60- "charset_normalizer",60 "sniffio",61 "rfc3986[idna2008]>=1.3,<2",62 "httpcore>=0.15.0,<0.16.0",63 ],34 unmodified lines