Merge branch 'main' of github.com:psf/requests into 3.13
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Thomas Grainger · committed by Thomas Grainger · parents 2e14522, f12ccbe · Browse files · 10 files·+169 added−66 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+169 added−66 removed
- tests:+24 added−17 removed
- other:+145 added−49 removed
Provenance
- Commit
0f5ef1b- Tree
518085d- Author
Thomas Grainger <tagrain@gmail.com>- Committer
Thomas Grainger <tagrain@gmail.com>- Parent 1
2e14522- Parent 2
f12ccbe
10 files changed+169 added−66 removed
modified:.github/workflows/codeql-analysis.yml+3 added-3 removed
43 unmodified lines444546474848495051522 unmodified lines555657585959606162635 unmodified lines69707172737343 unmodified lines if: ${{ github.event_name == 'pull_request' }}
# Initializes the CodeQL tools for scanning. - name: Initialize CodeQL uses: github/codeql-action/init@df5a14dc28094dc936e103b37d749c6628682b60 # v3.25.0 uses: github/codeql-action/init@eb055d739abdc2e8de2e5f4ba1a8b246daa779aa # v3.26.0 with: languages: "python" # If you wish to specify custom queries, you can do so here or in a config file. # By default, queries listed here will override any specified in a config file.2 unmodified lines
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # If this step fails, then you should remove it and run the build manually (see below) - name: Autobuild uses: github/codeql-action/autobuild@df5a14dc28094dc936e103b37d749c6628682b60 # v3.25.0 uses: github/codeql-action/autobuild@eb055d739abdc2e8de2e5f4ba1a8b246daa779aa # v3.26.0
# ℹ️ Command-line programs to run using the OS shell. # 📚 https://git.io/JvXDl
5 unmodified lines # make bootstrap # make release
- name: Perform CodeQL Analysis uses: github/codeql-action/analyze@df5a14dc28094dc936e103b37d749c6628682b60 # v3.25.0 uses: github/codeql-action/analyze@eb055d739abdc2e8de2e5f4ba1a8b246daa779aa # v3.26.0modified:.github/workflows/lint.yml+1 added-1 removed
11 unmodified lines1213141516161718192011 unmodified lines
steps: - uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # v4.1.0 - name: Set up Python uses: actions/setup-python@82c7e631bb3cdc910f68e0081d67478d79c6982d # v5.1.0 uses: actions/setup-python@f677139bbe7f9c59b41e40162b753c062f5d49a3 # v5.2.0 with: python-version: "3.x" - name: Run pre-commit uses: pre-commit/action@646c83fcd040023954eafda54b4db0192ce70507 # v3.0.0modified:.github/workflows/run-tests.yml+22 added-2 removed
25 unmodified lines2627282930303132333411 unmodified lines464748495050515253545556575859606162636465666768697071727374757677787925 unmodified lines
steps: - uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # v4.1.0 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@82c7e631bb3cdc910f68e0081d67478d79c6982d # v5.1.0 uses: actions/setup-python@f677139bbe7f9c59b41e40162b753c062f5d49a3 # v5.2.0 with: python-version: ${{ matrix.python-version }} cache: 'pip' - name: Install dependencies11 unmodified lines
steps: - uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 - name: 'Set up Python 3.8' uses: actions/setup-python@82c7e631bb3cdc910f68e0081d67478d79c6982d uses: actions/setup-python@f677139bbe7f9c59b41e40162b753c062f5d49a3 with: python-version: '3.8' - name: Install dependencies run: | make python -m pip uninstall -y "charset_normalizer" "chardet" - name: Run tests run: | make ci
urllib3: name: 'urllib3 1.x' runs-on: 'ubuntu-latest' strategy: fail-fast: true
steps: - uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 - name: 'Set up Python 3.8' uses: actions/setup-python@f677139bbe7f9c59b41e40162b753c062f5d49a3 with: python-version: '3.8' - name: Install dependencies run: | make python -m pip install "urllib3<2" - name: Run tests run: | make cimodified:src/requests/__version__.py+2 added-2 removed
3 unmodified lines4 5 __title__ = "requests"6 __description__ = "Python HTTP for Humans."7 __url__ = "https://requests.readthedocs.io"8-__version__ = "2.32.2"9-__build__ = 0x0232028+__version__ = "2.32.3"9+__build__ = 0x02320310 __author__ = "Kenneth Reitz"11 __author_email__ = "me@kennethreitz.org"12 __license__ = "Apache-2.0"13 __copyright__ = "Copyright Kenneth Reitz"1 unmodified linemodified:src/requests/adapters.py+92 added-14 removed
71 unmodified lines72 DEFAULT_POOLSIZE = 1073 DEFAULT_RETRIES = 074 DEFAULT_POOL_TIMEOUT = None75 76-_preloaded_ssl_context = create_urllib3_context()77-_preloaded_ssl_context.load_verify_locations(78- extract_zipped_paths(DEFAULT_CA_BUNDLE_PATH)79-)76 77+try:78+ import ssl # noqa: F40179 80+ _preloaded_ssl_context = create_urllib3_context()81+ _preloaded_ssl_context.load_verify_locations(82+ extract_zipped_paths(DEFAULT_CA_BUNDLE_PATH)83+ )84+except ImportError:85+ # Bypass default SSLContext creation when Python86+ # interpreter isn't built with the ssl module.87+ _preloaded_ssl_context = None88+89+90 def _urllib3_request_context(91 request: "PreparedRequest",92 verify: "bool | str | None",93 client_cert: "typing.Tuple[str, str] | str | None",94+ poolmanager: "PoolManager",95 ) -> "(typing.Dict[str, typing.Any], typing.Dict[str, typing.Any])":96 host_params = {}97 pool_kwargs = {}98 parsed_request_url = urlparse(request.url)99 scheme = parsed_request_url.scheme.lower()100 port = parsed_request_url.port101+102+ # Determine if we have and should use our default SSLContext103+ # to optimize performance on standard requests.104+ poolmanager_kwargs = getattr(poolmanager, "connection_pool_kw", {})105+ has_poolmanager_ssl_context = poolmanager_kwargs.get("ssl_context")106+ should_use_default_ssl_context = (107+ _preloaded_ssl_context is not None and not has_poolmanager_ssl_context108+ )109+110 cert_reqs = "CERT_REQUIRED"111 if verify is False:112 cert_reqs = "CERT_NONE"95- elif verify is True:113+ elif verify is True and should_use_default_ssl_context:114 pool_kwargs["ssl_context"] = _preloaded_ssl_context115 elif isinstance(verify, str):116 if not os.path.isdir(verify):117 pool_kwargs["ca_certs"] = verify274 unmodified lines392 response.connection = self393 394 return response395 396+ def build_connection_pool_key_attributes(self, request, verify, cert=None):397+ """Build the PoolKey attributes used by urllib3 to return a connection.398+399+ This looks at the PreparedRequest, the user-specified verify value,400+ and the value of the cert parameter to determine what PoolKey values401+ to use to select a connection from a given urllib3 Connection Pool.402+403+ The SSL related pool key arguments are not consistently set. As of404+ this writing, use the following to determine what keys may be in that405+ dictionary:406+407+ * If ``verify`` is ``True``, ``"ssl_context"`` will be set and will be the408+ default Requests SSL Context409+ * If ``verify`` is ``False``, ``"ssl_context"`` will not be set but410+ ``"cert_reqs"`` will be set411+ * If ``verify`` is a string, (i.e., it is a user-specified trust bundle)412+ ``"ca_certs"`` will be set if the string is not a directory recognized413+ by :py:func:`os.path.isdir`, otherwise ``"ca_certs_dir"`` will be414+ set.415+ * If ``"cert"`` is specified, ``"cert_file"`` will always be set. If416+ ``"cert"`` is a tuple with a second item, ``"key_file"`` will also417+ be present418+419+ To override these settings, one may subclass this class, call this420+ method and use the above logic to change parameters as desired. For421+ example, if one wishes to use a custom :py:class:`ssl.SSLContext` one422+ must both set ``"ssl_context"`` and based on what else they require,423+ alter the other keys to ensure the desired behaviour.424+425+ :param request:426+ The PreparedReqest being sent over the connection.427+ :type request:428+ :class:`~requests.models.PreparedRequest`429+ :param verify:430+ Either a boolean, in which case it controls whether431+ we verify the server's TLS certificate, or a string, in which case it432+ must be a path to a CA bundle to use.433+ :param cert:434+ (optional) Any user-provided SSL certificate for client435+ authentication (a.k.a., mTLS). This may be a string (i.e., just436+ the path to a file which holds both certificate and key) or a437+ tuple of length 2 with the certificate file path and key file438+ path.439+ :returns:440+ A tuple of two dictionaries. The first is the "host parameters"441+ portion of the Pool Key including scheme, hostname, and port. The442+ second is a dictionary of SSLContext related parameters.443+ """444+ return _urllib3_request_context(request, verify, cert, self.poolmanager)445+446 def get_connection_with_tls_context(self, request, verify, proxies=None, cert=None):447 """Returns a urllib3 connection for the given request and TLS settings.448 This should not be called from user code, and is only exposed for use449 when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.450 383- :param request: The :class:`PreparedRequest <PreparedRequest>` object384- to be sent over the connection.385- :param verify: Either a boolean, in which case it controls whether386- we verify the server's TLS certificate, or a string, in which case it387- must be a path to a CA bundle to use.388- :param proxies: (optional) The proxies dictionary to apply to the request.389- :param cert: (optional) Any user-provided SSL certificate to be trusted.390- :rtype: urllib3.ConnectionPool451+ :param request:452+ The :class:`PreparedRequest <PreparedRequest>` object to be sent453+ over the connection.454+ :param verify:455+ Either a boolean, in which case it controls whether we verify the456+ server's TLS certificate, or a string, in which case it must be a457+ path to a CA bundle to use.458+ :param proxies:459+ (optional) The proxies dictionary to apply to the request.460+ :param cert:461+ (optional) Any user-provided SSL certificate to be used for client462+ authentication (a.k.a., mTLS).463+ :rtype:464+ urllib3.ConnectionPool465 """466 proxy = select_proxy(request.url, proxies)467 try:394- host_params, pool_kwargs = _urllib3_request_context(request, verify, cert)468+ host_params, pool_kwargs = self.build_connection_pool_key_attributes(469+ request,470+ verify,471+ cert,472+ )473 except ValueError as e:474 raise InvalidURL(e, request=request)475 if proxy:476 proxy = prepend_scheme_if_needed(proxy, "http")243 unmodified linesmodified:src/requests/compat.py+12 added
8 unmodified lines9 10 import importlib11 import sys12 13+# -------14+# urllib315+# -------16+from urllib3 import __version__ as urllib3_version17+18+# Detect which major version of urllib3 is being used.19+try:20+ is_urllib3_1 = int(urllib3_version.split(".")[0]) == 121+except (TypeError, AttributeError):22+ # If we can't discern a version, prefer old functionality.23+ is_urllib3_1 = True24+25 # -------------------26 # Character Detection27 # -------------------28 78 unmodified linesmodified:src/requests/utils.py+4 added-1 removed
36 unmodified lines37 bytes,38 getproxies,39 getproxies_environment,40 integer_types,41+ is_urllib3_1,42 )43 from .compat import parse_http_list as _parse_list_header44 from .compat import (45 proxy_bypass,90 unmodified lines136 def super_len(o):137 total_length = None138 current_position = 0139 139- if isinstance(o, str):140+ if not is_urllib3_1 and isinstance(o, str):141+ # urllib3 2.x+ treats all strings as utf-8 instead142+ # of latin-1 (iso-8859-1) like http.client.143 o = o.encode("utf-8")144 145 if hasattr(o, "__len__"):146 total_length = len(o)953 unmodified linesmodified:tests/test_requests.py+24 added-17 removed
23 unmodified lines24 MutableMapping,25 builtin_str,26 cookielib,27 getproxies,28+ is_urllib3_1,29 urlparse,30 )31 from requests.cookies import cookiejar_from_dict, morsel_to_cookie32 from requests.exceptions import (1777 unmodified lines1810 p = req.prepare()1811 1812 assert p.headers["Content-Length"] == length1813 1813- def test_content_length_for_bytes_data(self, httpbin):1814- data = "This is a string containing multi-byte UTF-8 ☃️"1815- encoded_data = data.encode("utf-8")1816- length = str(len(encoded_data))1817- req = requests.Request("POST", httpbin("post"), data=encoded_data)1818- p = req.prepare()1819-1820- assert p.headers["Content-Length"] == length1821-1822- def test_content_length_for_string_data_counts_bytes(self, httpbin):1823- data = "This is a string containing multi-byte UTF-8 ☃️"1824- length = str(len(data.encode("utf-8")))1825- req = requests.Request("POST", httpbin("post"), data=data)1826- p = req.prepare()1827-1828- assert p.headers["Content-Length"] == length1829-1814 def test_nonhttp_schemes_dont_check_URLs(self):1815 test_urls = (1816 "data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==",1817 "file:///etc/passwd",1131 unmodified lines2949 2950 assert client_cert is not None2951 2952 2953+def test_content_length_for_bytes_data(httpbin):2954+ data = "This is a string containing multi-byte UTF-8 ☃️"2955+ encoded_data = data.encode("utf-8")2956+ length = str(len(encoded_data))2957+ req = requests.Request("POST", httpbin("post"), data=encoded_data)2958+ p = req.prepare()2959+2960+ assert p.headers["Content-Length"] == length2961+2962+2963+@pytest.mark.skipif(2964+ is_urllib3_1,2965+ reason="urllib3 2.x encodes all strings to utf-8, urllib3 1.x uses latin-1",2966+)2967+def test_content_length_for_string_data_counts_bytes(httpbin):2968+ data = "This is a string containing multi-byte UTF-8 ☃️"2969+ length = str(len(data.encode("utf-8")))2970+ req = requests.Request("POST", httpbin("post"), data=data)2971+ p = req.prepare()2972+2973+ assert p.headers["Content-Length"] == length2974+2975+2976 def test_json_decode_errors_are_serializable_deserializable():2977 json_decode_error = requests.exceptions.JSONDecodeError(2978 "Extra data",2979 '{"responseCode":["706"],"data":null}{"responseCode":["706"],"data":null}',4 unmodified linesmodified:HISTORY.md+9 added
4 unmodified lines5 ---6 7 - \[Short description of non-trivial change.\]8 9+2.32.3 (2024-05-29)10+-------------------11+12+**Bugfixes**13+- Fixed bug breaking the ability to specify custom SSLContexts in sub-classes of14+ HTTPAdapter. (#6716)15+- Fixed issue where Requests started failing to run on Python versions compiled16+ without the `ssl` module. (#6724)17+18 2.32.2 (2024-05-21)19 -------------------20 21 **Deprecations**1961 unmodified linesmodified:setup.py-26 removed
2 unmodified lines3 import sys4 from codecs import open5 6 from setuptools import setup7-from setuptools.command.test import test as TestCommand7 8 CURRENT_PYTHON = sys.version_info[:2]9 REQUIRED_PYTHON = (3, 8)10 15 unmodified lines26 )27 sys.exit(1)28 29 31-class PyTest(TestCommand):32- user_options = [("pytest-args=", "a", "Arguments to pass into py.test")]33-34- def initialize_options(self):35- TestCommand.initialize_options(self)36- try:37- from multiprocessing import cpu_count38-39- self.pytest_args = ["-n", str(cpu_count()), "--boxed"]40- except (ImportError, NotImplementedError):41- self.pytest_args = ["-n", "1", "--boxed"]42-43- def finalize_options(self):44- TestCommand.finalize_options(self)45- self.test_args = []46- self.test_suite = True47-48- def run_tests(self):49- import pytest50-51- errno = pytest.main(self.pytest_args)52- sys.exit(errno)53-54-30 # 'setup.py publish' shortcut.31 if sys.argv[-1] == "publish":32 os.system("python setup.py sdist bdist_wheel")33 os.system("twine upload dist/*")58 unmodified lines92 "Programming Language :: Python :: Implementation :: PyPy",93 "Topic :: Internet :: WWW/HTTP",94 "Topic :: Software Development :: Libraries",95 ],121- cmdclass={"test": PyTest},96 tests_require=test_requirements,97 extras_require={98 "security": [],99 "socks": ["PySocks>=1.5.6, !=1.5.7"],7 unmodified lines