Skip to content
Myr

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

authored by Tom Christie · committed by GitHub · parent 940d61b · Browse files · 11 files+245 added−54 removed
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

11 files+245 added−54 removed

modified:docs/advanced.md+82 added
143 unmodified lines
144```145146For a list of all available client parameters, see the [`Client`](api.md#client) API reference.147148---149150## Character set encodings and auto-detection151152When accessing `response.text`, we need to decode the response bytes into a unicode text representation.153154By default `httpx` will use `"charset"` information included in the response `Content-Type` header to determine how the response bytes should be decoded into text.155156In 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.157158### Using the default encoding159160To understand this better let's start by looking at the default behaviour for text decoding...161162```python163import httpx164# Instantiate a client with the default configuration.165client = httpx.Client()166# Using the client...167response = client.get(...)168print(response.encoding) # This will either print the charset given in169 # the Content-Type charset, or else "utf-8".170print(response.text) # The text will either be decoded with the Content-Type171 # charset, or using "utf-8".172```173174This 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.175176### Using an explicit encoding177178In 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.179180```python181import httpx182# Instantiate a client with a Japanese character set as the default encoding.183client = httpx.Client(default_encoding="shift-jis")184# Using the client...185response = client.get(...)186print(response.encoding) # This will either print the charset given in187 # the Content-Type charset, or else "shift-jis".188print(response.text) # The text will either be decoded with the Content-Type189 # charset, or using "shift-jis".190```191192### Using character set auto-detection193194In 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.195196To 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.197198There are two widely used Python packages which both handle this functionality:199200* [`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.202203Let's take a look at installing autodetection using one of these packages...204205 ```shell206$ pip install httpx207$ pip install chardet208 ```209210Once `chardet` is installed, we can configure a client to use character-set autodetection.211212```python213import httpx214import chardet215216def autodetect(content):217 return chardet.detect(content).get("encoding")218219# Using a client with character-set autodetection enabled.220client = httpx.Client(default_encoding=autodetect)221response = client.get(...)222print(response.encoding) # This will either print the charset given in223 # the Content-Type charset, or else the auto-detected224 # character set.225print(response.text)226```227228---229230## Calling into Python Web Apps231232You can configure an `httpx` client to call directly into a Python web application using the WSGI protocol.233
1026 unmodified lines
modified:docs/index.md-1 removed
modified:httpx/_client.py+14 added
166 unmodified lines
167 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_hooks174175 self._base_url = self._enforce_trailing_slash(URL(base_url))
9 unmodified lines
185 "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.UNOPENED192193 @property
418 unmodified lines
612 * **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 """620621 def __init__(622 self,
18 unmodified lines
641 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 lines
654 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 )660661 if http2:662 try:
345 unmodified lines
1008 response.stream = BoundSyncStream(1009 response.stream, response=response, timer=timer1010 )1011 self.cookies.extract_cookies(response)1012 response.default_encoding = self._default_encoding10131014 status = f"{response.status_code} {response.reason_phrase}"1015 response_line = f"{response.http_version} {status}"1016 logger.debug(
316 unmodified lines
1333 * **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 """13411342 def __init__(1343 self,
18 unmodified lines
1362 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 lines
1375 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 )13811382 if http2:1383 try:
336 unmodified lines
1720 response.stream = BoundAsyncStream(1721 response.stream, response=response, timer=timer1722 )1723 self.cookies.extract_cookies(response)1724 response.default_encoding = self._default_encoding17251726 status = f"{response.status_code} {response.reason_phrase}"1727 response_line = f"{response.http_version} {status}"1728 logger.debug(
272 unmodified lines
modified:httpx/_models.py+11 added-19 removed
5 unmodified lines
6import urllib.request7from collections.abc import MutableMapping8from http.cookiejar import Cookie, CookieJar910import charset_normalizer1110from ._content import ByteStream, UnattachedStream, encode_request, encode_response11from ._decoders import (12 SUPPORTED_DECODERS,13 ByteChunker,
428 unmodified lines
442 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 lines
459460 self.is_closed = False461 self.is_stream_consumed = False462463 self.default_encoding = default_encoding464465 if stream is None:466 headers, stream = encode_response(content, text, html, json)467 self._prepare(headers)468 self.stream = stream
100 unmodified lines
569 The priority for determining this is given by...570571 * `.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._encoding586587 @encoding.setter588 def encoding(self, value: str) -> None:
13 unmodified lines
602 return None603604 return params["charset"].strip("'\"")605601 @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.encoding613606 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 lines
modified:tests/client/test_client.py+61 added-1 removed
1import typing2from datetime import timedelta34import chardet5import pytest67import httpx8910def autodetect(content):11 return chardet.detect(content).get("encoding")121314def test_get(server):15 url = server.url16 with httpx.Client(http2=True) as http:17 response = http.get(url)
1 unmodified line
19 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 lines
402 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"406407408def 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 )421422 def cp1252_but_no_content_type(request):423 content = text.encode("ISO-8859-1")424 return httpx.Response(200, content=content)425426 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")429430 assert response.status_code == 200431 assert response.reason_phrase == "OK"432 assert response.encoding == "ISO-8859-1"433 assert response.text == text434435436def 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 )448449 def cp1252_but_no_content_type(request):450 content = text.encode("ISO-8859-1")451 return httpx.Response(200, content=content)452453 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")456457 assert response.status_code == 200458 assert response.reason_phrase == "OK"459 assert response.encoding == "ISO-8859-1"460 assert response.text == text
modified:tests/models/test_responses.py+67 added-24 removed
1import json2import pickle34import chardet5import pytest67import httpx8from httpx._compat import brotli
14 unmodified lines
23 yield b"Hello, "24 yield b"world!"252627def autodetect(content):28 return chardet.detect(content).get("encoding")293031def test_response():32 response = httpx.Response(33 200,34 content=b"Hello, world!",
133 unmodified lines
168 assert response.text == "Latin 1: ÿ"169 assert response.encoding == "latin-1"170171167def test_response_autodetect_encoding():172def 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"183184180def test_response_fallback_to_autodetect():185def 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 line
193 content=content,194 headers=headers,195 )196 assert response.text == "おはようございます。"192 assert response.encoding is None197 assert response.encoding == "utf-8"198199200def test_response_no_charset_with_ascii_content():201 """
7 unmodified lines
209 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!"215216217def test_response_no_charset_with_utf8_content():
8 unmodified lines
226 content=content,227 headers=headers,228 )229 assert response.text == "Unicode Snowman: ☃"225 assert response.encoding is None230 assert response.encoding == "utf-8"231232233def 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 None245246247def 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 None259260261def 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"273274275def test_response_set_explicit_encoding():276 headers = {
28 unmodified lines
305 )306307 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_closed311312 content = response.read()313
6 unmodified lines
320 response = httpx.Response(200)321322 assert response.status_code == 200323 assert response.text == ""325 assert response.encoding is None324 assert response.encoding == "utf-8"325 assert response.is_closed326327 content = response.read()328
10 unmodified lines
339 )340341 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_closed345346 content = await response.aread()347
7 unmodified lines
355 response = httpx.Response(200)356357 assert response.status_code == 200358 assert response.text == ""360 assert response.encoding is None359 assert response.encoding == "utf-8"360 assert response.is_closed361362 content = await response.aread()363
602 unmodified lines
966 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 == 13970971972def 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)987988 assert response.status_code == 200989 assert response.reason_phrase == "OK"990 assert response.encoding == "ISO-8859-1"991 assert response.text == text992993994def 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")10091010 assert response.status_code == 2001011 assert response.reason_phrase == "OK"1012 assert response.encoding == "cp1252"1013 assert response.text == text
modified:tests/test_decoders.py+6 added-5 removed
1import zlib23import chardet4import pytest56import httpx7from httpx._compat import brotli
176 unmodified lines
184 ((b"Accented: \xd6sterreich abcdefghijklmnopqrstuvwxyz", b""), "iso-8859-1"),185 ],186)187@pytest.mark.asyncio187async def test_text_decoder(data, encoding):188async def test_text_decoder_with_autodetect(data, encoding):189 async def iterator():190 nonlocal data191 for chunk in data:192 yield chunk193194 def autodetect(content):195 return chardet.detect(content).get("encoding")196197 # 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)201202 # Streaming `.aiter_text` iteratively.
156 unmodified lines
modified:README_chinese.md-1 removed
127 unmodified lines
128* `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 lines
modified:README.md-1 removed
126 unmodified lines
127128* `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 lines
modified:requirements.txt+4 added-1 removed
2 unmodified lines
3# 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]67charset-normalizer==2.0.67# Optional charset auto-detection8# Used in our test cases9chardet==4.0.010types-chardet==4.0.41112# Documentation13mkdocs==1.3.014mkautodoc==0.1.0
24 unmodified lines
modified:setup.py-1 removed
55 unmodified lines
56 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