Skip to content
Myr

Graceful upgrade path for 0.28. (#3394)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Tom Christie · committed by GitHub · parent 41597ad · Browse files · 11 files+155 added−434 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

11 files+155 added−434 removed

  • tests:+12 added−33 removed
  • other:+143 added−401 removed

11 files+155 added−434 removed

modified:docs/advanced/ssl.md+42 added-140 removed
modified:docs/contributing.md+3 added-6 removed
208 unmodified lines
209[proxy section](https://www.python-httpx.org/advanced/proxies/#http-proxies) and210the [SSL certificates section](https://www.python-httpx.org/advanced/ssl/),211this is where our previously generated `client.pem` comes in:212213```python214ctx = ssl.create_default_context(cafile="/path/to/client.pem")215client = httpx.Client(proxy="http://127.0.0.1:8080/", verify=ctx)216```214import httpx217216with httpx.Client(proxy="http://127.0.0.1:8080/", verify="/path/to/client.pem") as client:217 response = client.get("https://example.org")218 print(response.status_code) # should print 200219```220218Note, however, that HTTPS requests will only succeed to the host specified219in the SSL/TLS certificate we generated, HTTPS requests to other hosts will220raise an error like:221
11 unmodified lines
modified:httpx/_transports/default.py+5 added-19 removed
33 unmodified lines
34 import ssl # pragma: no cover3536 import httpx # pragma: no cover3738from .._config import DEFAULT_LIMITS, Limits, Proxy, SSLContext, create_ssl_context38from .._config import DEFAULT_LIMITS, Limits, Proxy, create_ssl_context39from .._exceptions import (40 ConnectError,41 ConnectTimeout,42 LocalProtocolError,
91 unmodified lines
134135class HTTPTransport(BaseTransport):136 def __init__(137 self,138 ssl_context: ssl.SSLContext | None = None,138 verify: ssl.SSLContext | bool = True,139 http1: bool = True,140 http2: bool = False,141 limits: Limits = DEFAULT_LIMITS,142 proxy: ProxyTypes | None = None,143 uds: str | None = None,144 local_address: str | None = None,145 retries: int = 0,146 socket_options: typing.Iterable[SOCKET_OPTION] | None = None,147 # Deprecated...148 verify: typing.Any = None,149 cert: typing.Any = None,147 ) -> None:148 import httpcore149150 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)151 ssl_context = create_ssl_context(verify=verify)157 else:158 ssl_context = ssl_context or SSLContext()152153 if proxy is None:154 self._pool = httpcore.ConnectionPool(155 ssl_context=ssl_context,
120 unmodified lines
276277class AsyncHTTPTransport(AsyncBaseTransport):278 def __init__(279 self,287 ssl_context: ssl.SSLContext | None = None,280 verify: ssl.SSLContext | bool = True,281 http1: bool = True,282 http2: bool = False,283 limits: Limits = DEFAULT_LIMITS,284 proxy: ProxyTypes | None = None,285 uds: str | None = None,286 local_address: str | None = None,287 retries: int = 0,288 socket_options: typing.Iterable[SOCKET_OPTION] | None = None,296 # Deprecated...297 verify: typing.Any = None,298 cert: typing.Any = None,289 ) -> None:290 import httpcore291292 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)293 ssl_context = create_ssl_context(verify=verify)306 else:307 ssl_context = ssl_context or SSLContext()294295 if proxy is None:296 self._pool = httpcore.AsyncConnectionPool(297 ssl_context=ssl_context,
105 unmodified lines
modified:httpx/__init__.py-1 removed
79 unmodified lines
80 "RequestError",81 "RequestNotRead",82 "Response",83 "ResponseNotRead",84 "SSLContext",84 "stream",85 "StreamClosed",86 "StreamConsumed",87 "StreamError",
18 unmodified lines
modified:httpx/_api.py+25 added-66 removed
1from __future__ import annotations23import ssl3import typing4from contextlib import contextmanager56from ._client import Client
11 unmodified lines
18 TimeoutTypes,19)20from ._urls import URL2122if typing.TYPE_CHECKING:23 import ssl # pragma: no cover242526__all__ = [27 "delete",28 "get",29 "head",
20 unmodified lines
50 auth: AuthTypes | None = None,51 proxy: ProxyTypes | None = None,52 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,53 follow_redirects: bool = False,51 ssl_context: ssl.SSLContext | None = None,54 verify: ssl.SSLContext | bool = True,55 trust_env: bool = True,53 # Deprecated in favor of `ssl_context`...54 verify: typing.Any = None,55 cert: typing.Any = None,56) -> Response:57 """58 Sends an HTTP request.59
21 unmodified lines
81 * **proxy** - *(optional)* A proxy URL where all the traffic should be routed.82 * **timeout** - *(optional)* The timeout configuration to use when sending83 the request.84 * **follow_redirects** - *(optional)* Enables or disables HTTP redirects.85 * **ssl_context** - *(optional)* An SSL certificate used by the requested host86 to authenticate the client.85 * **verify** - *(optional)* Either `True` to use an SSL context with the86 default CA bundle, `False` to disable verification, or an instance of87 `ssl.SSLContext` to use a custom context.88 * **trust_env** - *(optional)* Enables or disables usage of environment89 variables for configuration.9091 **Returns:** `Response`
9 unmodified lines
101 """102 with Client(103 cookies=cookies,104 proxy=proxy,104 ssl_context=ssl_context,105 verify=verify,106 timeout=timeout,107 trust_env=trust_env,107 verify=verify,108 cert=cert,108 ) as client:109 return client.request(110 method=method,111 url=url,
23 unmodified lines
135 auth: AuthTypes | None = None,136 proxy: ProxyTypes | None = None,137 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,138 follow_redirects: bool = False,140 ssl_context: ssl.SSLContext | None = None,139 verify: ssl.SSLContext | bool = True,140 trust_env: bool = True,142 # Deprecated in favor of `ssl_context`...143 verify: typing.Any = None,144 cert: typing.Any = None,141) -> typing.Iterator[Response]:142 """143 Alternative to `httpx.request()` that streams the response body144 instead of loading it into memory at once.
6 unmodified lines
151 """152 with Client(153 cookies=cookies,154 proxy=proxy,159 ssl_context=ssl_context,155 verify=verify,156 timeout=timeout,157 trust_env=trust_env,162 verify=verify,163 cert=cert,158 ) as client:159 with client.stream(160 method=method,161 url=url,
17 unmodified lines
179 cookies: CookieTypes | None = None,180 auth: AuthTypes | None = None,181 proxy: ProxyTypes | None = None,182 follow_redirects: bool = False,189 ssl_context: ssl.SSLContext | None = None,183 verify: ssl.SSLContext | bool = True,184 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,185 trust_env: bool = True,192 # Deprecated in favor of `ssl_context`...193 verify: typing.Any = None,194 cert: typing.Any = None,186) -> Response:187 """188 Sends a `GET` request.189
10 unmodified lines
200 cookies=cookies,201 auth=auth,202 proxy=proxy,203 follow_redirects=follow_redirects,213 ssl_context=ssl_context,204 verify=verify,205 timeout=timeout,206 trust_env=trust_env,216 verify=verify,217 cert=cert,207 )208209210def options(
4 unmodified lines
215 cookies: CookieTypes | None = None,216 auth: AuthTypes | None = None,217 proxy: ProxyTypes | None = None,218 follow_redirects: bool = False,230 ssl_context: ssl.SSLContext | None = None,219 verify: ssl.SSLContext | bool = True,220 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,221 trust_env: bool = True,233 # Deprecated in favor of `ssl_context`...234 verify: typing.Any = None,235 cert: typing.Any = None,222) -> Response:223 """224 Sends an `OPTIONS` request.225
10 unmodified lines
236 cookies=cookies,237 auth=auth,238 proxy=proxy,239 follow_redirects=follow_redirects,254 ssl_context=ssl_context,240 verify=verify,241 timeout=timeout,242 trust_env=trust_env,257 verify=verify,258 cert=cert,243 )244245246def head(
4 unmodified lines
251 cookies: CookieTypes | None = None,252 auth: AuthTypes | None = None,253 proxy: ProxyTypes | None = None,254 follow_redirects: bool = False,271 ssl_context: ssl.SSLContext | None = None,255 verify: ssl.SSLContext | bool = True,256 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,257 trust_env: bool = True,274 # Deprecated in favor of `ssl_context`...275 verify: typing.Any = None,276 cert: typing.Any = None,258) -> Response:259 """260 Sends a `HEAD` request.261
10 unmodified lines
272 cookies=cookies,273 auth=auth,274 proxy=proxy,275 follow_redirects=follow_redirects,295 ssl_context=ssl_context,276 verify=verify,277 timeout=timeout,278 trust_env=trust_env,298 verify=verify,299 cert=cert,279 )280281282def post(
8 unmodified lines
291 cookies: CookieTypes | None = None,292 auth: AuthTypes | None = None,293 proxy: ProxyTypes | None = None,294 follow_redirects: bool = False,316 ssl_context: ssl.SSLContext | None = None,295 verify: ssl.SSLContext | bool = True,296 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,297 trust_env: bool = True,319 # Deprecated in favor of `ssl_context`...320 verify: typing.Any = None,321 cert: typing.Any = None,298) -> Response:299 """300 Sends a `POST` request.301
11 unmodified lines
313 cookies=cookies,314 auth=auth,315 proxy=proxy,316 follow_redirects=follow_redirects,341 ssl_context=ssl_context,317 verify=verify,318 timeout=timeout,319 trust_env=trust_env,344 verify=verify,345 cert=cert,320 )321322323def put(
8 unmodified lines
332 cookies: CookieTypes | None = None,333 auth: AuthTypes | None = None,334 proxy: ProxyTypes | None = None,335 follow_redirects: bool = False,362 ssl_context: ssl.SSLContext | None = None,336 verify: ssl.SSLContext | bool = True,337 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,338 trust_env: bool = True,365 # Deprecated in favor of `ssl_context`...366 verify: typing.Any = None,367 cert: typing.Any = None,339) -> Response:340 """341 Sends a `PUT` request.342
11 unmodified lines
354 cookies=cookies,355 auth=auth,356 proxy=proxy,357 follow_redirects=follow_redirects,387 ssl_context=ssl_context,358 verify=verify,359 timeout=timeout,360 trust_env=trust_env,390 verify=verify,391 cert=cert,361 )362363364def patch(
8 unmodified lines
373 cookies: CookieTypes | None = None,374 auth: AuthTypes | None = None,375 proxy: ProxyTypes | None = None,376 follow_redirects: bool = False,408 ssl_context: ssl.SSLContext | None = None,377 verify: ssl.SSLContext | bool = True,378 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,379 trust_env: bool = True,411 # Deprecated in favor of `ssl_context`...412 verify: typing.Any = None,413 cert: typing.Any = None,380) -> Response:381 """382 Sends a `PATCH` request.383
11 unmodified lines
395 cookies=cookies,396 auth=auth,397 proxy=proxy,398 follow_redirects=follow_redirects,433 ssl_context=ssl_context,399 verify=verify,400 timeout=timeout,401 trust_env=trust_env,436 verify=verify,437 cert=cert,402 )403404405def delete(
5 unmodified lines
411 auth: AuthTypes | None = None,412 proxy: ProxyTypes | None = None,413 follow_redirects: bool = False,414 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,451 ssl_context: ssl.SSLContext | None = None,415 verify: ssl.SSLContext | bool = True,416 trust_env: bool = True,453 # Deprecated in favor of `ssl_context`...454 verify: typing.Any = None,455 cert: typing.Any = None,417) -> Response:418 """419 Sends a `DELETE` request.420
10 unmodified lines
431 cookies=cookies,432 auth=auth,433 proxy=proxy,434 follow_redirects=follow_redirects,474 ssl_context=ssl_context,435 verify=verify,436 timeout=timeout,437 trust_env=trust_env,477 verify=verify,478 cert=cert,438 )
modified:httpx/_client.py+23 added-60 removed
1 unmodified line
23import datetime4import enum5import logging6import ssl6import time7import typing8import warnings9from contextlib import asynccontextmanager, contextmanager
41 unmodified lines
51 is_https_redirect,52 same_origin,53)5455if typing.TYPE_CHECKING:56 import ssl # pragma: no cover5758__all__ = ["USE_CLIENT_DEFAULT", "AsyncClient", "Client"]5960# The type annotation for @classmethod and context managers here follows PEP 48461# https://www.python.org/dev/peps/pep-0484/#annotating-instance-and-class-methods
523 unmodified lines
585 * **headers** - *(optional)* Dictionary of HTTP headers to include when586 sending requests.587 * **cookies** - *(optional)* Dictionary of Cookie items to include when588 sending requests.587 * **ssl_context** - *(optional)* An SSL certificate used by the requested host588 to authenticate the client.589 * **verify** - *(optional)* Either `True` to use an SSL context with the590 default CA bundle, `False` to disable verification, or an instance of591 `ssl.SSLContext` to use a custom context.592 * **http2** - *(optional)* A boolean indicating if HTTP/2 support should be593 enabled. Defaults to `False`.594 * **proxy** - *(optional)* A proxy URL where all the traffic should be routed.595 * **proxies** - *(optional)* A dictionary mapping proxy keys to proxy
20 unmodified lines
616 auth: AuthTypes | None = None,617 params: QueryParamTypes | None = None,618 headers: HeaderTypes | None = None,619 cookies: CookieTypes | None = None,617 ssl_context: ssl.SSLContext | None = None,620 verify: ssl.SSLContext | bool = True,621 http1: bool = True,622 http2: bool = False,623 proxy: ProxyTypes | None = None,624 mounts: None | (typing.Mapping[str, BaseTransport | None]) = None,
5 unmodified lines
630 base_url: URL | str = "",631 transport: BaseTransport | None = None,632 trust_env: bool = True,633 default_encoding: str | typing.Callable[[bytes], str] = "utf-8",631 # Deprecated in favor of `ssl_context`...632 verify: typing.Any = None,633 cert: typing.Any = None,634 ) -> None:635 super().__init__(636 auth=auth,637 params=params,
20 unmodified lines
658 allow_env_proxies = trust_env and transport is None659 proxy_map = self._get_proxy_map(proxy, allow_env_proxies)660661 self._transport = self._init_transport(662 ssl_context=ssl_context,662 verify=verify,663 http1=http1,664 http2=http2,665 limits=limits,666 transport=transport,667 trust_env=trust_env,668 # Deprecated in favor of ssl_context...669 verify=verify,670 cert=cert,667 )668 self._mounts: dict[URLPattern, BaseTransport | None] = {669 URLPattern(key): None670 if proxy is None671 else self._init_proxy_transport(672 proxy,677 ssl_context=ssl_context,673 verify=verify,674 http1=http1,675 http2=http2,676 limits=limits,681 # Deprecated in favor of ssl_context...682 verify=verify,683 cert=cert,677 )678 for key, proxy in proxy_map.items()679 }680 if mounts is not None:
4 unmodified lines
685 self._mounts = dict(sorted(self._mounts.items()))686687 def _init_transport(688 self,696 ssl_context: ssl.SSLContext | None = None,689 verify: ssl.SSLContext | bool = True,690 http1: bool = True,691 http2: bool = False,692 limits: Limits = DEFAULT_LIMITS,693 transport: BaseTransport | None = None,701 trust_env: bool = True,702 # Deprecated in favor of `ssl_context`...703 verify: typing.Any = None,704 cert: typing.Any = None,694 ) -> BaseTransport:695 if transport is not None:696 return transport697698 return HTTPTransport(710 ssl_context=ssl_context,699 verify=verify,700 http1=http1,701 http2=http2,702 limits=limits,714 verify=verify,715 cert=cert,703 )704705 def _init_proxy_transport(706 self,707 proxy: Proxy,721 ssl_context: ssl.SSLContext | None = None,708 verify: ssl.SSLContext | bool = True,709 http1: bool = True,710 http2: bool = False,711 limits: Limits = DEFAULT_LIMITS,725 trust_env: bool = True,726 # Deprecated in favor of `ssl_context`...727 verify: typing.Any = None,728 cert: typing.Any = None,712 ) -> BaseTransport:713 return HTTPTransport(731 ssl_context=ssl_context,714 verify=verify,715 http1=http1,716 http2=http2,717 limits=limits,718 proxy=proxy,736 verify=verify,737 cert=cert,719 )720721 def _transport_for_url(self, url: URL) -> BaseTransport:722 """
565 unmodified lines
1288 * **headers** - *(optional)* Dictionary of HTTP headers to include when1289 sending requests.1290 * **cookies** - *(optional)* Dictionary of Cookie items to include when1291 sending requests.1311 * **ssl_context** - *(optional)* An SSL certificate used by the requested host1312 to authenticate the client.1292 * **verify** - *(optional)* Either `True` to use an SSL context with the1293 default CA bundle, `False` to disable verification, or an instance of1294 `ssl.SSLContext` to use a custom context.1295 * **http2** - *(optional)* A boolean indicating if HTTP/2 support should be1296 enabled. Defaults to `False`.1297 * **proxy** - *(optional)* A proxy URL where all the traffic should be routed.1298 * **timeout** - *(optional)* The timeout configuration to use when sending
18 unmodified lines
1317 auth: AuthTypes | None = None,1318 params: QueryParamTypes | None = None,1319 headers: HeaderTypes | None = None,1320 cookies: CookieTypes | None = None,1339 ssl_context: ssl.SSLContext | None = None,1321 verify: ssl.SSLContext | bool = True,1322 http1: bool = True,1323 http2: bool = False,1324 proxy: ProxyTypes | None = None,1325 mounts: None | (typing.Mapping[str, AsyncBaseTransport | None]) = None,
5 unmodified lines
1331 base_url: URL | str = "",1332 transport: AsyncBaseTransport | None = None,1333 trust_env: bool = True,1334 default_encoding: str | typing.Callable[[bytes], str] = "utf-8",1353 # Deprecated in favor of `ssl_context`...1354 verify: typing.Any = None,1355 cert: typing.Any = None,1335 ) -> None:1336 super().__init__(1337 auth=auth,1338 params=params,
20 unmodified lines
1359 allow_env_proxies = trust_env and transport is None1360 proxy_map = self._get_proxy_map(proxy, allow_env_proxies)13611362 self._transport = self._init_transport(1384 ssl_context=ssl_context,1363 verify=verify,1364 http1=http1,1365 http2=http2,1366 limits=limits,1367 transport=transport,1389 # Deprecated in favor of ssl_context1390 verify=verify,1391 cert=cert,1368 )13691370 self._mounts: dict[URLPattern, AsyncBaseTransport | None] = {1371 URLPattern(key): None1372 if proxy is None1373 else self._init_proxy_transport(1374 proxy,1399 ssl_context=ssl_context,1375 verify=verify,1376 http1=http1,1377 http2=http2,1378 limits=limits,1403 # Deprecated in favor of `ssl_context`...1404 verify=verify,1405 cert=cert,1379 )1380 for key, proxy in proxy_map.items()1381 }1382 if mounts is not None:
3 unmodified lines
1386 self._mounts = dict(sorted(self._mounts.items()))13871388 def _init_transport(1389 self,1417 ssl_context: ssl.SSLContext | None = None,1390 verify: ssl.SSLContext | bool = True,1391 http1: bool = True,1392 http2: bool = False,1393 limits: Limits = DEFAULT_LIMITS,1394 transport: AsyncBaseTransport | None = None,1422 # Deprecated in favor of `ssl_context`...1423 verify: typing.Any = None,1424 cert: typing.Any = None,1395 ) -> AsyncBaseTransport:1396 if transport is not None:1397 return transport13981399 return AsyncHTTPTransport(1430 ssl_context=ssl_context,1400 verify=verify,1401 http1=http1,1402 http2=http2,1403 limits=limits,1434 verify=verify,1435 cert=cert,1404 )14051406 def _init_proxy_transport(1407 self,1408 proxy: Proxy,1441 ssl_context: ssl.SSLContext | None = None,1409 verify: ssl.SSLContext | bool = True,1410 http1: bool = True,1411 http2: bool = False,1412 limits: Limits = DEFAULT_LIMITS,1445 # Deprecated in favor of `ssl_context`...1446 verify: typing.Any = None,1447 cert: typing.Any = None,1413 ) -> AsyncBaseTransport:1414 return AsyncHTTPTransport(1450 ssl_context=ssl_context,1415 verify=verify,1416 http1=http1,1417 http2=http2,1418 limits=limits,1419 proxy=proxy,1455 verify=verify,1456 cert=cert,1420 )14211422 def _transport_for_url(self, url: URL) -> AsyncBaseTransport:1423 """
544 unmodified lines
modified:httpx/_config.py+12 added-100 removed
1from __future__ import annotations23import os3import ssl5import sys4import typing7import warnings56from ._models import Headers7from ._types import HeaderTypes, TimeoutTypes8from ._urls import URL913__all__ = ["Limits", "Proxy", "SSLContext", "Timeout", "create_ssl_context"]10__all__ = ["Limits", "Proxy", "Timeout", "create_ssl_context"]111213class UnsetType:14 pass # pragma: no cover
1 unmodified line
1617UNSET = UnsetType()181923def create_ssl_context(24 verify: typing.Any = None,25 cert: typing.Any = None,26 trust_env: bool = True,27 http2: bool = False,28) -> ssl.SSLContext: # pragma: nocover29 # The `create_ssl_context` helper function is now deprecated30 # in favour of `httpx.SSLContext()`.31 if isinstance(verify, bool):32 ssl_context: ssl.SSLContext = SSLContext(verify=verify)33 warnings.warn(34 "The verify=<bool> parameter is deprecated since 0.28.0. "35 "Use `ssl_context=httpx.SSLContext(verify=<bool>)`."36 )37 elif isinstance(verify, str):38 warnings.warn(39 "The verify=<str> parameter is deprecated since 0.28.0. "40 "Use `ssl_context=httpx.SSLContext()` and `.load_verify_locations()`."41 )42 ssl_context = SSLContext()43 if os.path.isfile(verify):44 ssl_context.load_verify_locations(cafile=verify)45 elif os.path.isdir(verify):46 ssl_context.load_verify_locations(capath=verify)47 elif isinstance(verify, ssl.SSLContext):48 warnings.warn(49 "The verify=<ssl context> parameter is deprecated since 0.28.0. "50 "Use `ssl_context = httpx.SSLContext()`."51 )52 ssl_context = verify53 else:54 warnings.warn(55 "`create_ssl_context()` is deprecated since 0.28.0."56 "Use `ssl_context = httpx.SSLContext()`."57 )58 ssl_context = SSLContext()20def create_ssl_context(verify: ssl.SSLContext | bool = True) -> ssl.SSLContext:21 import ssl2260 if cert is not None:61 warnings.warn(62 "The `cert=<...>` parameter is deprecated since 0.28.0. "63 "Use `ssl_context = httpx.SSLContext()` and `.load_cert_chain()`."64 )65 if isinstance(cert, str):66 ssl_context.load_cert_chain(cert)67 else:68 ssl_context.load_cert_chain(*cert)23 import certifi2425 if verify is True:26 return ssl.create_default_context(cafile=certifi.where())27 elif verify is False:28 ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)29 ssl_context.check_hostname = False30 ssl_context.verify_mode = ssl.CERT_NONE70 return ssl_context31 return ssl_context3233 return verify3473class SSLContext(ssl.SSLContext):74 def __init__(75 self,76 verify: bool = True,77 ) -> None:78 import certifi3580 # 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__()84 self._verify = verify8586 # Our SSL setup here is similar to the stdlib `ssl.create_default_context()`87 # implementation, except with `certifi` used for certificate verification.88 if not verify:89 self.check_hostname = False90 self.verify_mode = ssl.CERT_NONE91 return9293 self.verify_mode = ssl.CERT_REQUIRED94 self.check_hostname = True9596 # Use stricter verify flags where possible.97 if hasattr(ssl, "VERIFY_X509_PARTIAL_CHAIN"): # pragma: nocover98 self.verify_flags |= ssl.VERIFY_X509_PARTIAL_CHAIN99 if hasattr(ssl, "VERIFY_X509_STRICT"): # pragma: nocover100 self.verify_flags |= ssl.VERIFY_X509_STRICT101102 # Default to `certifi` for certificiate verification.103 self.load_verify_locations(cafile=certifi.where())104105 # OpenSSL keylog file support.106 if hasattr(self, "keylog_filename"):107 keylogfile = os.environ.get("SSLKEYLOGFILE")108 if keylogfile and not sys.flags.ignore_environment:109 self.keylog_filename = keylogfile110111 def __repr__(self) -> str:112 class_name = self.__class__.__name__113 return f"<{class_name}(verify={self._verify!r})>"114115 def __new__(116 cls,117 protocol: ssl._SSLMethod = ssl.PROTOCOL_TLS_CLIENT,118 *args: typing.Any,119 **kwargs: typing.Any,120 ) -> "SSLContext":121 return super().__new__(cls, protocol, *args, **kwargs)12212336class Timeout:37 """38 Timeout configuration.39
173 unmodified lines
modified:httpx/_main.py+1 added-5 removed
13 unmodified lines
14import rich.syntax15import rich.table1617from ._client import Client18from ._config import SSLContext18from ._exceptions import RequestError19from ._models import Response20from ._status_codes import codes21
452 unmodified lines
474 """475 if not method:476 method = "POST" if content or data or files or json else "GET"477479 ssl_context = SSLContext(verify=verify)478 try:481 with Client(482 proxy=proxy, timeout=timeout, http2=http2, ssl_context=ssl_context483 ) as client:479 with Client(proxy=proxy, timeout=timeout, http2=http2, verify=verify) as client:480 with client.stream(481 method,482 url,483 params=list(params),
23 unmodified lines
modified:httpx/_urls.py+16 added
398 unmodified lines
399 )400401 return f"{self.__class__.__name__}({url!r})"402403 @property404 def raw(self) -> tuple[bytes, bytes, int, bytes]: # pragma: nocover405 import collections406 import warnings407408 warnings.warn("URL.raw is deprecated.")409 RawURL = collections.namedtuple(410 "RawURL", ["raw_scheme", "raw_host", "port", "raw_path"]411 )412 return RawURL(413 raw_scheme=self.raw_scheme,414 raw_host=self.raw_host,415 port=self.port,416 raw_path=self.raw_path,417 )418419420class QueryParams(typing.Mapping[str, str]):421 """422 URL query parameters, as a multi-dict.423 """
218 unmodified lines
modified:tests/test_config.py+12 added-33 removed
7 unmodified lines
8import httpx91011def test_load_ssl_config():12 context = httpx.SSLContext()12 context = httpx.create_ssl_context()13 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED14 assert context.check_hostname is True151617def test_load_ssl_config_verify_non_existing_file():18 with pytest.raises(IOError):19 context = httpx.SSLContext()19 context = httpx.create_ssl_context()20 context.load_verify_locations(cafile="/path/to/nowhere")212223def test_load_ssl_with_keylog(monkeypatch: typing.Any) -> None:24 monkeypatch.setenv("SSLKEYLOGFILE", "test")25 context = httpx.SSLContext()25 context = httpx.create_ssl_context()26 assert context.keylog_filename == "test"272829def test_load_ssl_config_verify_existing_file():30 context = httpx.SSLContext()30 context = httpx.create_ssl_context()31 context.load_verify_locations(capath=certifi.where())32 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED33 assert context.check_hostname is True343536def test_load_ssl_config_verify_directory():37 context = httpx.SSLContext()37 context = httpx.create_ssl_context()38 context.load_verify_locations(capath=Path(certifi.where()).parent)39 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED40 assert context.check_hostname is True414243def test_load_ssl_config_cert_and_key(cert_pem_file, cert_private_key_file):44 context = httpx.SSLContext()44 context = httpx.create_ssl_context()45 context.load_cert_chain(cert_pem_file, cert_private_key_file)46 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED47 assert context.check_hostname is True48
1 unmodified line
50@pytest.mark.parametrize("password", [b"password", "password"])51def test_load_ssl_config_cert_and_encrypted_key(52 cert_pem_file, cert_encrypted_private_key_file, password53):54 context = httpx.SSLContext()54 context = httpx.create_ssl_context()55 context.load_cert_chain(cert_pem_file, cert_encrypted_private_key_file, password)56 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED57 assert context.check_hostname is True58
1 unmodified line
60def test_load_ssl_config_cert_and_key_invalid_password(61 cert_pem_file, cert_encrypted_private_key_file62):63 with pytest.raises(ssl.SSLError):64 context = httpx.SSLContext()64 context = httpx.create_ssl_context()65 context.load_cert_chain(66 cert_pem_file, cert_encrypted_private_key_file, "password1"67 )686970def test_load_ssl_config_cert_without_key_raises(cert_pem_file):71 with pytest.raises(ssl.SSLError):72 context = httpx.SSLContext()72 context = httpx.create_ssl_context()73 context.load_cert_chain(cert_pem_file)747576def test_load_ssl_config_no_verify():77 context = httpx.SSLContext(verify=False)77 context = httpx.create_ssl_context(verify=False)78 assert context.verify_mode == ssl.VerifyMode.CERT_NONE79 assert context.check_hostname is False808182def test_SSLContext_with_get_request(server, cert_pem_file):83 context = httpx.SSLContext()83 context = httpx.create_ssl_context()84 context.load_verify_locations(cert_pem_file)85 response = httpx.get(server.url, ssl_context=context)85 response = httpx.get(server.url, verify=context)86 assert response.status_code == 200878889def test_SSLContext_repr():90 ssl_context = httpx.SSLContext()9192 assert repr(ssl_context) == "<SSLContext(verify=True)>"939489def test_limits_repr():90 limits = httpx.Limits(max_connections=100)91 expected = (92 "Limits(max_connections=100, max_keepalive_connections=None,"
88 unmodified lines
181182def test_invalid_proxy_scheme():183 with pytest.raises(ValueError):184 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+16 added-4 removed
4 unmodified lines
5The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).67## [Unreleased]89This release introduces an `httpx.SSLContext()` class and `ssl_context` parameter.9The 0.28 release includes a limited set of backwards incompatible changes.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)11**Backwards incompatible changes**:1213SSL configuration has been significantly simplified.1415* The `verify` argument no longer accepts string arguments.16* The `cert` argument has now been removed.17* The `SSL_CERT_FILE` and `SSL_CERT_DIR` environment variables are no longer automatically used.1819For users of the standard `verify=True` or `verify=False` cases this should require no changes.2021For information on configuring more complex SSL cases, please see the [SSL documentation](docs/advanced/ssl.md).2223**The following changes are also included**:2425* The undocumented `URL.raw` property has now been deprecated, and will raise warnings.26* The deprecated `proxies` argument has now been removed.27* The deprecated `app` argument has now been removed.15* The `URL.raw` property has now been removed.28* Ensure JSON request bodies are compact. (#3363)29* Review URL percent escape sets, based on WHATWG spec. (#3371, #3373)30* Ensure `certifi` and `httpcore` are only imported if required. (#3377)31* Treat `socks5h` as a valid proxy scheme. (#3178)
1096 unmodified lines