made dependencies on certifi and httpcore only load when required (#3377)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Joe Marshall · committed by GitHub · parent eeb5e3c · Browse files · 7 files·+75 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: Tom Christie <tom@tomchristie.com>
Diff stats
7 files+75 added−26 removed
- tests:+30 added−0 removed
- other:+45 added−26 removed
Provenance
- Commit
e9cabc8- Tree
80355d8- Author
Joe Marshall <joe.marshall@nottingham.ac.uk>- Committer
GitHub <noreply@github.com>- Parent
eeb5e3c
7 files changed+75 added−26 removed
modified:httpx/_transports/default.py+36 added-20 removed
25 unmodified lines26 27 from __future__ import annotations28 29 import contextlib30-import ssl30 import typing31 from types import TracebackType32 34-import httpcore33+if typing.TYPE_CHECKING:34+ import ssl # pragma: no cover35 36+ import httpx # pragma: no cover37+38 from .._config import DEFAULT_LIMITS, Limits, Proxy, SSLContext, create_ssl_context39 from .._exceptions import (40 ConnectError,41 ConnectTimeout,25 unmodified lines67 ]68 69 __all__ = ["AsyncHTTPTransport", "HTTPTransport"]70 71+HTTPCORE_EXC_MAP: dict[type[Exception], type[httpx.HTTPError]] = {}72 73+74+def _load_httpcore_exceptions() -> dict[type[Exception], type[httpx.HTTPError]]:75+ import httpcore76+77+ return {78+ httpcore.TimeoutException: TimeoutException,79+ httpcore.ConnectTimeout: ConnectTimeout,80+ httpcore.ReadTimeout: ReadTimeout,81+ httpcore.WriteTimeout: WriteTimeout,82+ httpcore.PoolTimeout: PoolTimeout,83+ httpcore.NetworkError: NetworkError,84+ httpcore.ConnectError: ConnectError,85+ httpcore.ReadError: ReadError,86+ httpcore.WriteError: WriteError,87+ httpcore.ProxyError: ProxyError,88+ httpcore.UnsupportedProtocol: UnsupportedProtocol,89+ httpcore.ProtocolError: ProtocolError,90+ httpcore.LocalProtocolError: LocalProtocolError,91+ httpcore.RemoteProtocolError: RemoteProtocolError,92+ }93+94+95 @contextlib.contextmanager96 def map_httpcore_exceptions() -> typing.Iterator[None]:97+ global HTTPCORE_EXC_MAP98+ if len(HTTPCORE_EXC_MAP) == 0:99+ HTTPCORE_EXC_MAP = _load_httpcore_exceptions()100 try:101 yield102 except Exception as exc:103 mapped_exc = None13 unmodified lines117 message = str(exc)118 raise mapped_exc(message) from exc119 120 93-HTTPCORE_EXC_MAP = {94- httpcore.TimeoutException: TimeoutException,95- httpcore.ConnectTimeout: ConnectTimeout,96- httpcore.ReadTimeout: ReadTimeout,97- httpcore.WriteTimeout: WriteTimeout,98- httpcore.PoolTimeout: PoolTimeout,99- httpcore.NetworkError: NetworkError,100- httpcore.ConnectError: ConnectError,101- httpcore.ReadError: ReadError,102- httpcore.WriteError: WriteError,103- httpcore.ProxyError: ProxyError,104- httpcore.UnsupportedProtocol: UnsupportedProtocol,105- httpcore.ProtocolError: ProtocolError,106- httpcore.LocalProtocolError: LocalProtocolError,107- httpcore.RemoteProtocolError: RemoteProtocolError,108-}109-110-121 class ResponseStream(SyncByteStream):122 def __init__(self, httpcore_stream: typing.Iterable[bytes]) -> None:123 self._httpcore_stream = httpcore_stream124 22 unmodified lines147 # Deprecated...148 verify: typing.Any = None,149 cert: typing.Any = None,150 ) -> None:151+ import httpcore152+153 proxy = Proxy(url=proxy) if isinstance(proxy, (str, URL)) else proxy154 if verify is not None or cert is not None: # pragma: nocover155 # Deprecated...156 ssl_context = create_ssl_context(verify, cert)79 unmodified lines236 self,237 request: Request,238 ) -> Response:239 assert isinstance(request.stream, SyncByteStream)240+ import httpcore241 242 req = httpcore.Request(243 method=request.method,244 url=httpcore.URL(51 unmodified lines296 # Deprecated...297 verify: typing.Any = None,298 cert: typing.Any = None,299 ) -> None:300+ import httpcore301+302 proxy = Proxy(url=proxy) if isinstance(proxy, (str, URL)) else proxy303 if verify is not None or cert is not None: # pragma: nocover304 # Deprecated...305 ssl_context = create_ssl_context(verify, cert)79 unmodified lines385 self,386 request: Request,387 ) -> Response:388 assert isinstance(request.stream, AsyncByteStream)389+ import httpcore390 391 req = httpcore.Request(392 method=request.method,393 url=httpcore.URL(23 unmodified linesmodified:httpx/__version__.py+1 added-1 removed
1 __title__ = "httpx"2 __description__ = "A next generation HTTP client, for Python 3."3-__version__ = "0.28.0"3+__version__ = "0.27.2"modified:httpx/_config.py+2 added-2 removed
4 unmodified lines5 import sys6 import typing7 import warnings8 9-import certifi10-9 from ._models import Headers10 from ._types import HeaderTypes, TimeoutTypes11 from ._urls import URL12 61 unmodified lines74 def __init__(75 self,76 verify: bool = True,77 ) -> None:78+ import certifi79+80 # ssl.SSLContext sets OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION,81 # OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE and OP_SINGLE_ECDH_USE82 # by default. (from `ssl.create_default_context`)83 super().__init__()217 unmodified linesmodified:httpx/_main.py+3 added-1 removed
4 unmodified lines5 import sys6 import typing7 8 import click9-import httpcore9 import pygments.lexers10 import pygments.util11 import rich.console12 import rich.markup6 unmodified lines19 from ._exceptions import RequestError20 from ._models import Response21 from ._status_codes import codes22 23+if typing.TYPE_CHECKING:24+ import httpcore # pragma: no cover25 26+27 def print_help() -> None:28 console = rich.console.Console()29 30 console.print("[bold]HTTPX :butterfly:", justify="center")480 unmodified linesmodified:tests/test_api.py+15 added
83 unmodified lines84 85 def test_get_invalid_url():86 with pytest.raises(httpx.UnsupportedProtocol):87 httpx.get("invalid://example.org")88+89+90+# check that httpcore isn't imported until we do a request91+def test_httpcore_lazy_loading(server):92+ import sys93+94+ # unload our module if it is already loaded95+ if "httpx" in sys.modules:96+ del sys.modules["httpx"]97+ del sys.modules["httpcore"]98+ import httpx99+100+ assert "httpcore" not in sys.modules101+ _response = httpx.get(server.url)102+ assert "httpcore" in sys.modulesmodified:tests/test_config.py+15 added
186 unmodified lines187 188 def test_invalid_proxy_scheme():189 with pytest.raises(ValueError):190 httpx.Proxy("invalid://example.com")191+192+193+def test_certifi_lazy_loading():194+ global httpx, certifi195+ import sys196+197+ del sys.modules["httpx"]198+ del sys.modules["certifi"]199+ del httpx200+ del certifi201+ import httpx202+203+ assert "certifi" not in sys.modules204+ _context = httpx.SSLContext()205+ assert "certifi" in sys.modulesmodified:CHANGELOG.md+3 added-2 removed
2 unmodified lines3 All notable changes to this project will be documented in this file.4 5 The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).6 7-## Version 0.28.07+## [Unreleased]8 9-Version 0.28.0 introduces an `httpx.SSLContext()` class and `ssl_context` parameter.9+This release introduces an `httpx.SSLContext()` class and `ssl_context` parameter.10 11 * Added `httpx.SSLContext` class and `ssl_context` parameter. (#3022, #3335)12 * The `verify` and `cert` arguments have been deprecated and will now raise warnings. (#3022, #3335)13 * The deprecated `proxies` argument has now been removed.14 * The deprecated `app` argument has now been removed.15 * The `URL.raw` property has now been removed.16 * Ensure JSON request bodies are compact. (#3363)17 * Review URL percent escape sets, based on WHATWG spec. (#3371, #3373)18+* Ensure `certifi` and `httpcore` are only imported if required. (#3377)19 20 ## 0.27.2 (27th August, 2024)21 22 ### Fixed1091 unmodified lines