Switch LGPL'd chardet for MIT licensed charset_normalizer (#5797)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Although using the (non-vendored) chardet library is fine for requests itself, but using a LGPL dependency the story is a lot less clear for downstream projects, particularly ones that might like to bundle requests (and thus chardet) in to a single binary -- think something similar to what docker-compose is doing. By including an LGPL'd module it is no longer clear if the resulting artefact must also be LGPL'd. By changing out this dependency for one under MIT we remove all license ambiguity. As an "escape hatch" I have made the code so that it will use chardet first if it is installed, but we no longer depend upon it directly, although there is a new extra added, `requests[lgpl]`. This should minimize the impact to users, and give them an escape hatch if charset_normalizer turns out to be not as good. (In my non-exhaustive tests it detects the same encoding as chartdet in every case I threw at it) Co-authored-by: Jarek Potiuk <jarek@potiuk.com>
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Jarek Potiuk <jarek@potiuk.com>
Diff stats
10 files+118 added−26 removed
- other:+118 added−26 removed
Provenance
- Commit
2ed84f5- Tree
5afa602- Author
Ash Berlin-Taylor <ash_github@firemirror.com>- Committer
GitHub <noreply@github.com>- Parent
33d448e
10 files changed+118 added−26 removed
modified:docs/user/advanced.rst+15 added-3 removed
695 unmodified lines696 697 When you receive a response, Requests makes a guess at the encoding to698 use for decoding the response when you access the :attr:`Response.text699 <requests.Response.text>` attribute. Requests will first check for an700-encoding in the HTTP header, and if none is present, will use `chardet701-<https://pypi.org/project/chardet/>`_ to attempt to guess the encoding.700+encoding in the HTTP header, and if none is present, will use701+`charset_normalizer <https://pypi.org/project/charset_normalizer/>`_702+or `chardet <https://github.com/chardet/chardet>`_ to attempt to703+guess the encoding.704 705+If ``chardet`` is installed, ``requests`` uses it, however for python3706+``chardet`` is no longer a mandatory dependency. The ``chardet``707+library is an LGPL-licenced dependency and some users of requests708+cannot depend on mandatory LGPL-licensed dependencies.709+710+When you install ``request`` without specifying ``[use_chardet_on_py3]]`` extra,711+and ``chardet`` is not already installed, ``requests`` uses ``charset-normalizer``712+(MIT-licensed) to guess the encoding. For Python 2, ``requests`` uses only713+``chardet`` and is a mandatory dependency there.714+703-The only time Requests will not do this is if no explicit charset715+The only time Requests will not guess the encoding is if no explicit charset716 is present in the HTTP headers **and** the ``Content-Type``717 header contains ``text``. In this situation, `RFC 2616718 <https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1>`_ specifies719 that the default charset must be ``ISO-8859-1``. Requests follows the371 unmodified linesmodified:requests/__init__.py+26 added-11 removed
39 unmodified lines40 :license: Apache 2.0, see LICENSE for more details.41 """42 43 import urllib344-import chardet44 import warnings45 from .exceptions import RequestsDependencyWarning46 47+try:48+ from charset_normalizer import __version__ as charset_normalizer_version49+except ImportError:50+ charset_normalizer_version = None51 52+try:53+ from chardet import __version__ as chardet_version54+except ImportError:55+ chardet_version = None56+49-def check_compatibility(urllib3_version, chardet_version):57+def check_compatibility(urllib3_version, chardet_version, charset_normalizer_version):58 urllib3_version = urllib3_version.split('.')59 assert urllib3_version != ['dev'] # Verify urllib3 isn't installed from git.60 61 # Sometimes, urllib3 only reports its version as 16.1.7 unmodified lines69 assert major == 170 assert minor >= 2171 assert minor <= 2672 73+ # Check charset_normalizer for compatibility.65- # Check chardet for compatibility.66- major, minor, patch = chardet_version.split('.')[:3]67- major, minor, patch = int(major), int(minor), int(patch)68- # chardet >= 3.0.2, < 5.0.069- assert (3, 0, 2) <= (major, minor, patch) < (5, 0, 0)74+ if chardet_version:75+ major, minor, patch = chardet_version.split('.')[:3]76+ major, minor, patch = int(major), int(minor), int(patch)77+ # chardet_version >= 3.0.2, < 5.0.078+ assert (3, 0, 2) <= (major, minor, patch) < (5, 0, 0)79+ elif charset_normalizer_version:80+ major, minor, patch = charset_normalizer_version.split('.')[:3]81+ major, minor, patch = int(major), int(minor), int(patch)82+ # charset_normalizer >= 2.0.0 < 3.0.083+ assert (2, 0, 0) <= (major, minor, patch) < (3, 0, 0)84+ else:85+ raise Exception("You need either charset_normalizer or chardet installed")86 71-87 def _check_cryptography(cryptography_version):88 # cryptography < 1.3.489 try:90 cryptography_version = list(map(int, cryptography_version.split('.')))5 unmodified lines96 warnings.warn(warning, RequestsDependencyWarning)97 98 # Check imported dependencies for compatibility.99 try:85- check_compatibility(urllib3.__version__, chardet.__version__)100+ check_compatibility(urllib3.__version__, chardet_version, charset_normalizer_version)101 except (AssertionError, ValueError):87- warnings.warn("urllib3 ({}) or chardet ({}) doesn't match a supported "88- "version!".format(urllib3.__version__, chardet.__version__),102+ warnings.warn("urllib3 ({}) or chardet ({})/charset_normalizer ({}) doesn't match a supported "103+ "version!".format(urllib3.__version__, chardet_version, charset_normalizer_version),104 RequestsDependencyWarning)105 106 # Attempt to enable urllib3's fallback for SNI support107 # if the standard library doesn't support SNI or the45 unmodified linesmodified:requests/compat.py+4 added-1 removed
6 unmodified lines7 This module handles import compatibility issues between Python 2 and8 Python 3.9 """10 11+try:11-import chardet12+ import chardet13+except ImportError:14+ import charset_normalizer as chardet15 16 import sys17 18 # -------57 unmodified linesmodified:requests/help.py+18 added-2 removed
6 unmodified lines7 import ssl8 9 import idna10 import urllib311-import chardet11 12 from . import __version__ as requests_version13 14 try:15+ import charset_normalizer16+except ImportError:17+ charset_normalizer = None18+19+try:20+ import chardet21+except ImportError:22+ chardet = None23+24+try:25 from urllib3.contrib import pyopenssl26 except ImportError:27 pyopenssl = None28 OpenSSL = None50 unmodified lines79 }80 81 implementation_info = _implementation()82 urllib3_info = {'version': urllib3.__version__}83+ charset_normalizer_info = {'version': None}84+ chardet_info = {'version': None}85+ if charset_normalizer:86+ charset_normalizer_info = {'version': charset_normalizer.__version__}87+ if chardet:74- chardet_info = {'version': chardet.__version__}88+ chardet_info = {'version': chardet.__version__}89 90 pyopenssl_info = {91 'version': None,92 'openssl_version': '',19 unmodified lines112 'platform': platform_info,113 'implementation': implementation_info,114 'system_ssl': system_ssl_info,115 'using_pyopenssl': pyopenssl is not None,116+ 'using_charset_normalizer': chardet is None,117 'pyOpenSSL': pyopenssl_info,118 'urllib3': urllib3_info,119 'chardet': chardet_info,120+ 'charset_normalizer': charset_normalizer_info,121 'cryptography': cryptography_info,122 'idna': idna_info,123 'requests': {124 'version': requests_version,11 unmodified linesmodified:requests/models.py+3 added-3 removed
729 unmodified lines730 return self._next731 732 @property733 def apparent_encoding(self):734- """The apparent encoding, provided by the chardet library."""734+ """The apparent encoding, provided by the charset_normalizer or chardet libraries."""735 return chardet.detect(self.content)['encoding']736 737 def iter_content(self, chunk_size=1, decode_unicode=False):738 """Iterates over the response data. When stream=True is set on the105 unmodified lines844 def text(self):845 """Content of the response, in unicode.846 847 If Response.encoding is None, encoding will be guessed using848- ``chardet``.848+ ``charset_normalizer`` or ``chardet``.849 850 The encoding of the response content is determined based solely on HTTP851 headers, following RFC 2616 to the letter. If you can take advantage of852 non-HTTP knowledge to make a better guess at the encoding, you should39 unmodified lines892 893 if not self.encoding and self.content and len(self.content) > 3:894 # No encoding set. JSON RFC 4627 section 3 states we should expect895 # UTF-8, -16 or -32. Detect which one to use; If the detection or896- # decoding fails, fall back to `self.text` (using chardet to make896+ # decoding fails, fall back to `self.text` (using charset_normalizer to make897 # a best guess).898 encoding = guess_json_utf(self.content)899 if encoding is not None:900 try:66 unmodified linesmodified:requests/packages.py+13 added-1 removed
1 import sys2 3+try:4+ import chardet5+except ImportError:6+ import charset_normalizer as chardet7+ import warnings8+9+ warnings.filterwarnings('ignore', 'Trying to detect', module='charset_normalizer')10+11 # This code exists for backwards compatibility reasons.12 # I don't like it either. Just look the other way. :)13 6-for package in ('urllib3', 'idna', 'chardet'):14+for package in ('urllib3', 'idna'):15 locals()[package] = __import__(package)16 # This traversal is apparently necessary such that the identities are17 # preserved (requests.packages.urllib3.* is urllib3.*)18 for mod in list(sys.modules):19 if mod == package or mod.startswith(package + '.'):20 sys.modules['requests.packages.' + mod] = sys.modules[mod]21 22+target = chardet.__name__23+for mod in list(sys.modules):24+ if mod == target or mod.startswith(target + '.'):25+ sys.modules['requests.packages.' + target.replace(target, 'chardet')] = sys.modules[mod]26 # Kinda cool, though, right?modified:.gitignore+6 added
21 unmodified lines22 .eggs/23 24 .workon25 26+# in case you work with IntelliJ/PyCharm27+.idea28+*.iml29+.python-version30+31+32 t.py33 34 t2.py35 dist2 unmodified linesmodified:HISTORY.md+16 added-1 removed
4 unmodified lines5 ---6 7 - \[Short description of non-trivial change.\]8 9+**Dependencies**10+11+- Instead of `chardet`, use the MIT-licensed `charset_normalizer` for Python312+ to remove license ambiguity for projects bundling requests. If `chardet`13+ is already installed on your machine it will be used instead of `charset_normalizer`14+ to keep backwards compatibility.15+16+ You can also install `chardet` while installing requests by17+ specifying `[use_chardet_on_py3]` extra as follows:18+19+ ```shell20+ pip install "requests[use_chardet_on_py3]"21+ ```22+23+ Python2 still depends upon the `chardet` module.24+25 2.25.1 (2020-12-16)26 -------------------27 28 **Bugfixes**1693 unmodified lines1722 ------------------1723 1724 - Frustration1725 - Conception1710-modified:setup.py+3 added-1 removed
39 unmodified lines40 41 packages = ['requests']42 43 requires = [44- 'chardet>=3.0.2,<5',44+ 'charset_normalizer~=2.0.0; python_version >= "3"',45+ 'chardet>=3.0.2,<5; python_version < "3"',46 'idna>=2.5,<3',47 'urllib3>=1.21.1,<1.27',48 'certifi>=2017.4.17'49 53 unmodified lines103 extras_require={104 'security': ['pyOpenSSL >= 0.14', 'cryptography>=1.3.4'],105 'socks': ['PySocks>=1.5.6, !=1.5.7'],106 'socks:sys_platform == "win32" and python_version == "2.7"': ['win_inet_pton'],107+ 'use_chardet_on_py3': ['chardet>=3.0.2,<5']108 },109 project_urls={110 'Documentation': 'https://requests.readthedocs.io',111 'Source': 'https://github.com/psf/requests',2 unmodified linesmodified:tox.ini+14 added-3 removed
1 [tox]2-envlist = py27,py35,py36,py37,py382+envlist = py{27,35,36,37,38}-{default,use_chardet_on_py3}3 4 [testenv]5-5+deps = -rrequirements-dev.txt6+extras =7+ security8+ socks9 commands =7- python setup.py test10+ pytest tests11+12+[testenv:default]13+14+[testenv:use_chardet_on_py3]15+extras =16+ security17+ socks18+ use_chardet_on_py3