Skip to content
Myr

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>

authored by Ash Berlin-Taylor · committed by GitHub · parent 33d448e · Browse files · 10 files+118 added−26 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: Jarek Potiuk <jarek@potiuk.com>

Diff stats

10 files+118 added−26 removed

  • other:+118 added−26 removed

10 files+118 added−26 removed

modified:docs/user/advanced.rst+15 added-3 removed
695 unmodified lines
696697When you receive a response, Requests makes a guess at the encoding to698use for decoding the response when you access the :attr:`Response.text699<requests.Response.text>` attribute. Requests will first check for an700encoding in the HTTP header, and if none is present, will use `chardet701<https://pypi.org/project/chardet/>`_ to attempt to guess the encoding.700encoding in the HTTP header, and if none is present, will use701`charset_normalizer <https://pypi.org/project/charset_normalizer/>`_702or `chardet <https://github.com/chardet/chardet>`_ to attempt to703guess the encoding.704705If ``chardet`` is installed, ``requests`` uses it, however for python3706``chardet`` is no longer a mandatory dependency. The ``chardet``707library is an LGPL-licenced dependency and some users of requests708cannot depend on mandatory LGPL-licensed dependencies.709710When you install ``request`` without specifying ``[use_chardet_on_py3]]`` extra,711and ``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.714703The only time Requests will not do this is if no explicit charset715The only time Requests will not guess the encoding is if no explicit charset716is present in the HTTP headers **and** the ``Content-Type``717header contains ``text``. In this situation, `RFC 2616718<https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1>`_ specifies719that the default charset must be ``ISO-8859-1``. Requests follows the
371 unmodified lines
modified:requests/__init__.py+26 added-11 removed
39 unmodified lines
40:license: Apache 2.0, see LICENSE for more details.41"""4243import urllib344import chardet44import warnings45from .exceptions import RequestsDependencyWarning4647try:48 from charset_normalizer import __version__ as charset_normalizer_version49except ImportError:50 charset_normalizer_version = None5152try:53 from chardet import __version__ as chardet_version54except ImportError:55 chardet_version = None5649def check_compatibility(urllib3_version, chardet_version):57def 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.6061 # Sometimes, urllib3 only reports its version as 16.1.
7 unmodified lines
69 assert major == 170 assert minor >= 2171 assert minor <= 267273 # 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")867187def _check_cryptography(cryptography_version):88 # cryptography < 1.3.489 try:90 cryptography_version = list(map(int, cryptography_version.split('.')))
5 unmodified lines
96 warnings.warn(warning, RequestsDependencyWarning)9798# Check imported dependencies for compatibility.99try:85 check_compatibility(urllib3.__version__, chardet.__version__)100 check_compatibility(urllib3.__version__, chardet_version, charset_normalizer_version)101except (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)105106# Attempt to enable urllib3's fallback for SNI support107# if the standard library doesn't support SNI or the
45 unmodified lines
modified:requests/compat.py+4 added-1 removed
6 unmodified lines
7This module handles import compatibility issues between Python 2 and8Python 3.9"""1011try:11import chardet12 import chardet13except ImportError:14 import charset_normalizer as chardet1516import sys1718# -------
57 unmodified lines
modified:requests/help.py+18 added-2 removed
6 unmodified lines
7import ssl89import idna10import urllib311import chardet1112from . import __version__ as requests_version1314try:15 import charset_normalizer16except ImportError:17 charset_normalizer = None1819try:20 import chardet21except ImportError:22 chardet = None2324try:25 from urllib3.contrib import pyopenssl26except ImportError:27 pyopenssl = None28 OpenSSL = None
50 unmodified lines
79 }8081 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__}8990 pyopenssl_info = {91 'version': None,92 'openssl_version': '',
19 unmodified lines
112 '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 lines
modified:requests/models.py+3 added-3 removed
729 unmodified lines
730 return self._next731732 @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']736737 def iter_content(self, chunk_size=1, decode_unicode=False):738 """Iterates over the response data. When stream=True is set on the
105 unmodified lines
844 def text(self):845 """Content of the response, in unicode.846847 If Response.encoding is None, encoding will be guessed using848 ``chardet``.848 ``charset_normalizer`` or ``chardet``.849850 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 should
39 unmodified lines
892893 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 lines
modified:requests/packages.py+13 added-1 removed
1import sys23try:4 import chardet5except ImportError:6 import charset_normalizer as chardet7 import warnings89 warnings.filterwarnings('ignore', 'Trying to detect', module='charset_normalizer')1011# This code exists for backwards compatibility reasons.12# I don't like it either. Just look the other way. :)136for package in ('urllib3', 'idna', 'chardet'):14for 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]2122target = chardet.__name__23for 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 lines
22.eggs/2324.workon2526# in case you work with IntelliJ/PyCharm27.idea28*.iml29.python-version303132t.py3334t2.py35dist
2 unmodified lines
modified:HISTORY.md+16 added-1 removed
4 unmodified lines
5---67- \[Short description of non-trivial change.\]89**Dependencies**1011- 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.1516 You can also install `chardet` while installing requests by17 specifying `[use_chardet_on_py3]` extra as follows:1819 ```shell20 pip install "requests[use_chardet_on_py3]"21 ```2223 Python2 still depends upon the `chardet` module.24252.25.1 (2020-12-16)26-------------------2728**Bugfixes**
1693 unmodified lines
1722------------------17231724- Frustration1725- Conception1710
modified:setup.py+3 added-1 removed
39 unmodified lines
4041packages = ['requests']4243requires = [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 lines
103 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 lines
modified:tox.ini+14 added-3 removed
1[tox]2envlist = py27,py35,py36,py37,py382envlist = py{27,35,36,37,38}-{default,use_chardet_on_py3}34[testenv]55deps = -rrequirements-dev.txt6extras =7 security8 socks9commands =7 python setup.py test10 pytest tests1112[testenv:default]1314[testenv:use_chardet_on_py3]15extras =16 security17 socks18 use_chardet_on_py3