Skip to content
Myr

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

7 files+75 added−26 removed

modified:httpx/_transports/default.py+36 added-20 removed
25 unmodified lines
2627from __future__ import annotations2829import contextlib30import ssl30import typing31from types import TracebackType3234import httpcore33if typing.TYPE_CHECKING:34 import ssl # pragma: no cover3536 import httpx # pragma: no cover3738from .._config import DEFAULT_LIMITS, Limits, Proxy, SSLContext, create_ssl_context39from .._exceptions import (40 ConnectError,41 ConnectTimeout,
25 unmodified lines
67]6869__all__ = ["AsyncHTTPTransport", "HTTPTransport"]7071HTTPCORE_EXC_MAP: dict[type[Exception], type[httpx.HTTPError]] = {}727374def _load_httpcore_exceptions() -> dict[type[Exception], type[httpx.HTTPError]]:75 import httpcore7677 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 }939495@contextlib.contextmanager96def 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 = None
13 unmodified lines
117 message = str(exc)118 raise mapped_exc(message) from exc11912093HTTPCORE_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}109110121class ResponseStream(SyncByteStream):122 def __init__(self, httpcore_stream: typing.Iterable[bytes]) -> None:123 self._httpcore_stream = httpcore_stream124
22 unmodified lines
147 # Deprecated...148 verify: typing.Any = None,149 cert: typing.Any = None,150 ) -> None:151 import httpcore152153 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 lines
236 self,237 request: Request,238 ) -> Response:239 assert isinstance(request.stream, SyncByteStream)240 import httpcore241242 req = httpcore.Request(243 method=request.method,244 url=httpcore.URL(
51 unmodified lines
296 # Deprecated...297 verify: typing.Any = None,298 cert: typing.Any = None,299 ) -> None:300 import httpcore301302 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 lines
385 self,386 request: Request,387 ) -> Response:388 assert isinstance(request.stream, AsyncByteStream)389 import httpcore390391 req = httpcore.Request(392 method=request.method,393 url=httpcore.URL(
23 unmodified lines
modified: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 lines
5import sys6import typing7import warnings89import certifi109from ._models import Headers10from ._types import HeaderTypes, TimeoutTypes11from ._urls import URL12
61 unmodified lines
74 def __init__(75 self,76 verify: bool = True,77 ) -> None:78 import certifi7980 # 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 lines
modified:httpx/_main.py+3 added-1 removed
4 unmodified lines
5import sys6import typing78import click9import httpcore9import pygments.lexers10import pygments.util11import rich.console12import rich.markup
6 unmodified lines
19from ._exceptions import RequestError20from ._models import Response21from ._status_codes import codes2223if typing.TYPE_CHECKING:24 import httpcore # pragma: no cover252627def print_help() -> None:28 console = rich.console.Console()2930 console.print("[bold]HTTPX :butterfly:", justify="center")
480 unmodified lines
modified:tests/test_api.py+15 added
83 unmodified lines
8485def test_get_invalid_url():86 with pytest.raises(httpx.UnsupportedProtocol):87 httpx.get("invalid://example.org")888990# check that httpcore isn't imported until we do a request91def test_httpcore_lazy_loading(server):92 import sys9394 # 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 httpx99100 assert "httpcore" not in sys.modules101 _response = httpx.get(server.url)102 assert "httpcore" in sys.modules
modified:tests/test_config.py+15 added
186 unmodified lines
187188def test_invalid_proxy_scheme():189 with pytest.raises(ValueError):190 httpx.Proxy("invalid://example.com")191192193def test_certifi_lazy_loading():194 global httpx, certifi195 import sys196197 del sys.modules["httpx"]198 del sys.modules["certifi"]199 del httpx200 del certifi201 import httpx202203 assert "certifi" not in sys.modules204 _context = httpx.SSLContext()205 assert "certifi" in sys.modules
modified:CHANGELOG.md+3 added-2 removed
2 unmodified lines
3All notable changes to this project will be documented in this file.45The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).67## Version 0.28.07## [Unreleased]89Version 0.28.0 introduces an `httpx.SSLContext()` class and `ssl_context` parameter.9This release introduces an `httpx.SSLContext()` class and `ssl_context` parameter.1011* 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)1920## 0.27.2 (27th August, 2024)2122### Fixed
1091 unmodified lines