Skip to content
Myr

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

10 files+169 added−66 removed

modified:.github/workflows/codeql-analysis.yml+3 added-3 removed
modified:.github/workflows/lint.yml+1 added-1 removed
modified:.github/workflows/run-tests.yml+22 added-2 removed
modified:src/requests/__version__.py+2 added-2 removed
3 unmodified lines
45__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 line
modified:src/requests/adapters.py+92 added-14 removed
71 unmodified lines
72DEFAULT_POOLSIZE = 1073DEFAULT_RETRIES = 074DEFAULT_POOL_TIMEOUT = None7576_preloaded_ssl_context = create_urllib3_context()77_preloaded_ssl_context.load_verify_locations(78 extract_zipped_paths(DEFAULT_CA_BUNDLE_PATH)79)7677try:78 import ssl # noqa: F4017980 _preloaded_ssl_context = create_urllib3_context()81 _preloaded_ssl_context.load_verify_locations(82 extract_zipped_paths(DEFAULT_CA_BUNDLE_PATH)83 )84except ImportError:85 # Bypass default SSLContext creation when Python86 # interpreter isn't built with the ssl module.87 _preloaded_ssl_context = None888990def _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.port101102 # 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 )109110 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"] = verify
274 unmodified lines
392 response.connection = self393394 return response395396 def build_connection_pool_key_attributes(self, request, verify, cert=None):397 """Build the PoolKey attributes used by urllib3 to return a connection.398399 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.402403 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:406407 * 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 present418419 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.424425 :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)445446 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>`.450383 :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 lines
modified:src/requests/compat.py+12 added
8 unmodified lines
910import importlib11import sys1213# -------14# urllib315# -------16from urllib3 import __version__ as urllib3_version1718# Detect which major version of urllib3 is being used.19try:20 is_urllib3_1 = int(urllib3_version.split(".")[0]) == 121except (TypeError, AttributeError):22 # If we can't discern a version, prefer old functionality.23 is_urllib3_1 = True2425# -------------------26# Character Detection27# -------------------28
78 unmodified lines
modified:src/requests/utils.py+4 added-1 removed
36 unmodified lines
37 bytes,38 getproxies,39 getproxies_environment,40 integer_types,41 is_urllib3_1,42)43from .compat import parse_http_list as _parse_list_header44from .compat import (45 proxy_bypass,
90 unmodified lines
136def super_len(o):137 total_length = None138 current_position = 0139139 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")144145 if hasattr(o, "__len__"):146 total_length = len(o)
953 unmodified lines
modified:tests/test_requests.py+24 added-17 removed
23 unmodified lines
24 MutableMapping,25 builtin_str,26 cookielib,27 getproxies,28 is_urllib3_1,29 urlparse,30)31from requests.cookies import cookiejar_from_dict, morsel_to_cookie32from requests.exceptions import (
1777 unmodified lines
1810 p = req.prepare()18111812 assert p.headers["Content-Length"] == length18131813 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()18191820 assert p.headers["Content-Length"] == length18211822 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()18271828 assert p.headers["Content-Length"] == length18291814 def test_nonhttp_schemes_dont_check_URLs(self):1815 test_urls = (1816 "data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==",1817 "file:///etc/passwd",
1131 unmodified lines
29492950 assert client_cert is not None295129522953def 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()29592960 assert p.headers["Content-Length"] == length296129622963@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)2967def 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()29722973 assert p.headers["Content-Length"] == length297429752976def 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 lines
modified:HISTORY.md+9 added
4 unmodified lines
5---67- \[Short description of non-trivial change.\]892.32.3 (2024-05-29)10-------------------1112**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)17182.32.2 (2024-05-21)19-------------------2021**Deprecations**
1961 unmodified lines
modified:setup.py-26 removed
2 unmodified lines
3import sys4from codecs import open56from setuptools import setup7from setuptools.command.test import test as TestCommand78CURRENT_PYTHON = sys.version_info[:2]9REQUIRED_PYTHON = (3, 8)10
15 unmodified lines
26 )27 sys.exit(1)282931class PyTest(TestCommand):32 user_options = [("pytest-args=", "a", "Arguments to pass into py.test")]3334 def initialize_options(self):35 TestCommand.initialize_options(self)36 try:37 from multiprocessing import cpu_count3839 self.pytest_args = ["-n", str(cpu_count()), "--boxed"]40 except (ImportError, NotImplementedError):41 self.pytest_args = ["-n", "1", "--boxed"]4243 def finalize_options(self):44 TestCommand.finalize_options(self)45 self.test_args = []46 self.test_suite = True4748 def run_tests(self):49 import pytest5051 errno = pytest.main(self.pytest_args)52 sys.exit(errno)535430# 'setup.py publish' shortcut.31if sys.argv[-1] == "publish":32 os.system("python setup.py sdist bdist_wheel")33 os.system("twine upload dist/*")
58 unmodified lines
92 "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