Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize import time by deferring SSL context creation #252

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 20 additions & 5 deletions src/requests/adapters.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,16 +77,31 @@ def SOCKSProxyManager(*args, **kwargs):
try:
import ssl # noqa: F401

_preloaded_ssl_context = create_urllib3_context()
_preloaded_ssl_context.load_verify_locations(
extract_zipped_paths(DEFAULT_CA_BUNDLE_PATH)
)
_preloaded_ssl_context = None
except ImportError:
# Bypass default SSLContext creation when Python
# interpreter isn't built with the ssl module.
_preloaded_ssl_context = None


def _get_preloaded_ssl_context():
"""Create a new ``SSLContext`` with loaded default certificate bundle.

This method should not be called from user code, and is only
exposed for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
"""
global _preloaded_ssl_context

if _preloaded_ssl_context is None:
_preloaded_ssl_context = create_urllib3_context()
_preloaded_ssl_context.load_verify_locations(
extract_zipped_paths(DEFAULT_CA_BUNDLE_PATH)
)

return _preloaded_ssl_context


def _urllib3_request_context(
request: "PreparedRequest",
verify: "bool | str | None",
Expand All @@ -111,7 +126,7 @@ def _urllib3_request_context(
if verify is False:
cert_reqs = "CERT_NONE"
elif verify is True and should_use_default_ssl_context:
pool_kwargs["ssl_context"] = _preloaded_ssl_context
pool_kwargs["ssl_context"] = _get_preloaded_ssl_context()
elif isinstance(verify, str):
if not os.path.isdir(verify):
pool_kwargs["ca_certs"] = verify
Expand Down