Introduce new `SSLContext` API & escalate deprecations. (#3319)
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 3f76571 · Browse files · 29 files·+527 added−941 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: Kar Petrosyan <92274156+karpetrosyan@users.noreply.github.com>
- Co-authored-by: T-256 <132141463+T-256@users.noreply.github.com>
- Co-authored-by: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com>
Diff stats
29 files+527 added−941 removed
- tests:+44 added−270 removed
- other:+483 added−671 removed
Provenance
- Commit
8e36f2b- Tree
4c318be- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
3f76571
29 files changed+527 added−941 removed
modified:.github/workflows/test-suite.yml+1 added-1 removed
3 unmodified lines456788910111222 unmodified lines3 unmodified lineson: push: branches: ["master"] pull_request: branches: ["master", 'version*'] branches: ["master", "version-*"]
jobs: tests: name: "Python ${{ matrix.python-version }}"22 unmodified linesmodified:.github/CONTRIBUTING.md+3 added-2 removed
209 unmodified lines210 211 ```212 import httpx213 214-proxies = {"all": "http://127.0.0.1:8080/"}214+ssl_context = httpx.SSLContext()215+ssl_context.load_verify_locations("/path/to/client.pem")216 216-with httpx.Client(proxies=proxies, verify="/path/to/client.pem") as client:217+with httpx.Client(proxy="http://127.0.0.1:8080/", ssl_context=ssl_context) as client:218 response = client.get("https://example.org")219 print(response.status_code) # should print 200220 ```221 15 unmodified linesmodified:docs/advanced/ssl.md+147 added-48 removed
12334556778910119101213121415161718192021152223241819202122252627282930312632333435362937383940323334414243444546474849505137383952535455565758435960454661626364656667684869707172737475767778795180815382838485868788899091555692939495969798991001011021031041055910610761108109631101111126667681131141151161171181191207112112212374757612412512612712812913079131132133134135136137828384138139140141142143144145146147871481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871889495189190191979899192193194195196197198199When making a request over HTTPS, HTTPX needs to verify the identity of the requested host. To do this, it uses a bundle of SSL certificates (a.k.a. CA bundle) delivered by a trusted certificate authority (CA).
## Changing the verification defaults### Enabling and disabling verification
By default, HTTPX uses the CA bundle provided by [Certifi](https://pypi.org/project/certifi/). This is what you want in most cases, even though some advanced situations may require you to use a different set of certificates.By default httpx will verify HTTPS connections, and raise an error for invalid SSL cases...
If you'd like to use a custom CA bundle, you can use the `verify` parameter.```pycon>>> httpx.get("https://expired.badssl.com/")httpx.ConnectError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:997)```
```pythonimport httpxVerification is configured through [the SSL Context API](https://docs.python.org/3/library/ssl.html#ssl-contexts).
r = httpx.get("https://example.org", verify="path/to/client.pem")```pycon>>> context = httpx.SSLContext()>>> context<SSLContext(verify=True)>>>> httpx.get("https://www.example.com", ssl_context=context)httpx.ConnectError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:997)```
Alternatively, you can pass a standard library `ssl.SSLContext`.You can use this to disable verification completely and allow insecure requests...
```pycon>>> import ssl>>> import httpx>>> context = ssl.create_default_context()>>> context.load_verify_locations(cafile="/tmp/client.pem")>>> httpx.get('https://example.org', verify=context)>>> context = httpx.SSLContext(verify=False)>>> context<SSLContext(verify=False)>>>> httpx.get("https://expired.badssl.com/", ssl_context=context)<Response [200 OK]>```
We also include a helper function for creating properly configured `SSLContext` instances.### Configuring client instances
If you're using a `Client()` instance you should pass any SSL context when instantiating the client.
```pycon>>> context = httpx.create_ssl_context()>>> context = httpx.SSLContext()>>> client = httpx.Client(ssl_context=context)```
The `create_ssl_context` function accepts the same set of SSL configuration arguments(`trust_env`, `verify`, `cert` and `http2` arguments)as `httpx.Client` or `httpx.AsyncClient`The `client.get(...)` method and other request methods on a `Client` instance *do not* support changing the SSL settings on a per-request basis.
If you need different SSL settings in different cases you should use more than one client instance, with different settings on each. Each client will then be using an isolated connection pool with a specific fixed SSL configuration on all connections within that pool.
### Configuring certificate stores
By default, HTTPX uses the CA bundle provided by [Certifi](https://pypi.org/project/certifi/).
You can load additional certificate verification using the [`.load_verify_locations()`](https://docs.python.org/3/library/ssl.html#ssl.SSLContext.load_verify_locations) API:
```pycon>>> import httpx>>> context = httpx.create_ssl_context(verify="/tmp/client.pem")>>> httpx.get('https://example.org', verify=context)>>> context = httpx.SSLContext()>>> context.load_verify_locations(cafile="path/to/certs.pem")>>> client = httpx.Client(ssl_context=context)>>> client.get("https://www.example.com")<Response [200 OK]>```
Or you can also disable the SSL verification entirely, which is _not_ recommended.Or by providing an certificate directory:
```pythonimport httpx```pycon>>> context = httpx.SSLContext()>>> context.load_verify_locations(capath="path/to/certs")>>> client = httpx.Client(ssl_context=context)>>> client.get("https://www.example.com")<Response [200 OK]>```
r = httpx.get("https://example.org", verify=False)### Client side certificates
You can also specify a local cert to use as a client-side certificate, using the [`.load_cert_chain()`](https://docs.python.org/3/library/ssl.html#ssl.SSLContext.load_cert_chain) API:
```pycon>>> context = httpx.SSLContext()>>> context.load_cert_chain(certfile="path/to/client.pem")>>> httpx.get("https://example.org", ssl_context=ssl_context)<Response [200 OK]>```
## SSL configuration on client instancesOr including a keyfile...
If you're using a `Client()` instance, then you should pass any SSL settings when instantiating the client.```pycon>>> context = httpx.SSLContext()>>> context.load_cert_chain( certfile="path/to/client.pem", keyfile="path/to/client.key" )>>> httpx.get("https://example.org", ssl_context=context)<Response [200 OK]>```
```pythonclient = httpx.Client(verify=False)Or including a keyfile and password...
```pycon>>> context = httpx.SSLContext(cert=cert)>>> context = httpx.SSLContext()>>> context.load_cert_chain( certfile="path/to/client.pem", keyfile="path/to/client.key" password="password" )>>> httpx.get("https://example.org", ssl_context=context)<Response [200 OK]>```
The `client.get(...)` method and other request methods *do not* support changing the SSL settings on a per-request basis. If you need different SSL settings in different cases you should use more that one client instance, with different settings on each. Each client will then be using an isolated connection pool with a specific fixed SSL configuration on all connections within that pool.### Using alternate SSL contexts
## Client Side CertificatesYou can also use an alternate `ssl.SSLContext` instances.
You can also specify a local cert to use as a client-side certificate, either a path to an SSL certificate file, or two-tuple of (certificate file, key file), or a three-tuple of (certificate file, key file, password)For example, [using the `truststore` package](https://truststore.readthedocs.io/)...
```pythoncert = "path/to/client.pem"client = httpx.Client(cert=cert)response = client.get("https://example.org")import sslimport truststoreimport httpx
ssl_context = truststore.SSLContext(ssl.PROTOCOL_TLS_CLIENT)client = httpx.Client(ssl_context=ssl_context)```
Alternatively...Or working [directly with Python's standard library](https://docs.python.org/3/library/ssl.html)...
```pythoncert = ("path/to/client.pem", "path/to/client.key")client = httpx.Client(cert=cert)response = client.get("https://example.org")import sslimport httpx
ssl_context = ssl.create_default_context()client = httpx.Client(ssl_context=ssl_context)```
Or...### Working with `SSL_CERT_FILE` and `SSL_CERT_DIR`
Unlike `requests`, the `httpx` package does not automatically pull in [the environment variables `SSL_CERT_FILE` or `SSL_CERT_DIR`](https://www.openssl.org/docs/manmaster/man3/SSL_CTX_set_default_verify_paths.html). If you want to use these they need to be enabled explicitly.
For example...
```pythoncert = ("path/to/client.pem", "path/to/client.key", "password")client = httpx.Client(cert=cert)response = client.get("https://example.org")context = httpx.SSLContext()
# Use `SSL_CERT_FILE` or `SSL_CERT_DIR` if configured.if os.environ.get("SSL_CERT_FILE") or os.environ.get("SSL_CERT_DIR"): context.load_verify_locations( cafile=os.environ.get("SSL_CERT_FILE"), capath=os.environ.get("SSL_CERT_DIR"), )```
## Making HTTPS requests to a local server## `SSLKEYLOGFILE`
Valid values: a filename
If this environment variable is set, TLS keys will be appended to the specified file, creating it if it doesn't exist, whenever key material is generated or received. The keylog file is designed for debugging purposes only.
Support for `SSLKEYLOGFILE` requires Python 3.8 and OpenSSL 1.1.1 or newer.
Example:
```python# test_script.pyimport httpx
with httpx.Client() as client: r = client.get("https://google.com")```
```consoleSSLKEYLOGFILE=test.log python test_script.pycat test.log# TLS secrets log file, generated by OpenSSL / PythonSERVER_HANDSHAKE_TRAFFIC_SECRET XXXXEXPORTER_SECRET XXXXSERVER_TRAFFIC_SECRET_0 XXXXCLIENT_HANDSHAKE_TRAFFIC_SECRET XXXXCLIENT_TRAFFIC_SECRET_0 XXXXSERVER_HANDSHAKE_TRAFFIC_SECRET XXXXEXPORTER_SECRET XXXXSERVER_TRAFFIC_SECRET_0 XXXXCLIENT_HANDSHAKE_TRAFFIC_SECRET XXXXCLIENT_TRAFFIC_SECRET_0 XXXX```
### Making HTTPS requests to a local server
When making requests to local servers, such as a development server running on `localhost`, you will typically be using unencrypted HTTP connections.
If you do need to make HTTPS connections to a local server, for example to test an HTTPS-only service, you will need to create and use your own certificates. Here's one way to do it:
1. Use [trustme](https://github.com/python-trio/trustme) to generate a pair of server key/cert files, and a client cert file.1. Pass the server key/cert files when starting your local server. (This depends on the particular web server you're using. For example, [Uvicorn](https://www.uvicorn.org) provides the `--ssl-keyfile` and `--ssl-certfile` options.)1. Tell HTTPX to use the certificates stored in `client.pem`:2. Pass the server key/cert files when starting your local server. (This depends on the particular web server you're using. For example, [Uvicorn](https://www.uvicorn.org) provides the `--ssl-keyfile` and `--ssl-certfile` options.)3. Tell HTTPX to use the certificates stored in `client.pem`:
```pythonclient = httpx.Client(verify="/tmp/client.pem")response = client.get("https://localhost:8000")```pycon>>> import httpx>>> context = httpx.SSLContext()>>> context.load_verify_locations(cafile="/tmp/client.pem")>>> r = httpx.get("https://localhost:8000", ssl_context=context)>>> rResponse <200 OK>```modified:docs/compatibility.md+1 added-3 removed
169 unmodified lines170 Also note that `requests.Session.request(...)` allows a `proxies=...` parameter, whereas `httpx.Client.request(...)` does not allow `mounts=...`.171 172 ## SSL configuration173 174-When using a `Client` instance, the `trust_env`, `verify`, and `cert` arguments should always be passed on client instantiation, rather than passed to the request method.174+When using a `Client` instance, the ssl configurations should always be passed on client instantiation, rather than passed to the request method.175 176 If you need more than one different SSL configuration, you should use different client instances for each SSL configuration.177 178-Requests supports `REQUESTS_CA_BUNDLE` which points to either a file or a directory. HTTPX supports the `SSL_CERT_FILE` (for a file) and `SSL_CERT_DIR` (for a directory) OpenSSL variables instead.179-178 ## Request body on HTTP methods179 180 The HTTP `GET`, `DELETE`, `HEAD`, and `OPTIONS` methods are specified as not supporting a request body. To stay in line with this, the `.get`, `.delete`, `.head` and `.options` functions do not support `content`, `files`, `data`, or `json` arguments.181 47 unmodified linesmodified:docs/environment_variables.md-60 removed
6 unmodified lines7 * Using the top-level API, such as `httpx.get("<url>", trust_env=False)`.8 9 Here is a list of environment variables that HTTPX recognizes and what function they serve:10 11-## `SSLKEYLOGFILE`12-13-Valid values: a filename14-15-If this environment variable is set, TLS keys will be appended to the specified file, creating it if it doesn't exist, whenever key material is generated or received. The keylog file is designed for debugging purposes only.16-17-Support for `SSLKEYLOGFILE` requires Python 3.8 and OpenSSL 1.1.1 or newer.18-19-Example:20-21-```python22-# test_script.py23-import httpx24-25-with httpx.AsyncClient() as client:26- r = client.get("https://google.com")27-```28-29-```console30-SSLKEYLOGFILE=test.log python test_script.py31-cat test.log32-# TLS secrets log file, generated by OpenSSL / Python33-SERVER_HANDSHAKE_TRAFFIC_SECRET XXXX34-EXPORTER_SECRET XXXX35-SERVER_TRAFFIC_SECRET_0 XXXX36-CLIENT_HANDSHAKE_TRAFFIC_SECRET XXXX37-CLIENT_TRAFFIC_SECRET_0 XXXX38-SERVER_HANDSHAKE_TRAFFIC_SECRET XXXX39-EXPORTER_SECRET XXXX40-SERVER_TRAFFIC_SECRET_0 XXXX41-CLIENT_HANDSHAKE_TRAFFIC_SECRET XXXX42-CLIENT_TRAFFIC_SECRET_0 XXXX43-```44-45-## `SSL_CERT_FILE`46-47-Valid values: a filename48-49-If this environment variable is set then HTTPX will load50-CA certificate from the specified file instead of the default51-location.52-53-Example:54-55-```console56-SSL_CERT_FILE=/path/to/ca-certs/ca-bundle.crt python -c "import httpx; httpx.get('https://example.com')"57-```58-59-## `SSL_CERT_DIR`60-61-Valid values: a directory following an [OpenSSL specific layout](https://www.openssl.org/docs/manmaster/man3/SSL_CTX_load_verify_locations.html).62-63-If this environment variable is set and the directory follows an [OpenSSL specific layout](https://www.openssl.org/docs/manmaster/man3/SSL_CTX_load_verify_locations.html) (ie. you ran `c_rehash`) then HTTPX will load CA certificates from this directory instead of the default location.64-65-Example:66-67-```console68-SSL_CERT_DIR=/path/to/ca-certs/ python -c "import httpx; httpx.get('https://example.com')"69-```70-11 ## Proxies12 13 The environment variables documented below are used as a convention by various HTTP tooling, including:14 39 unmodified linesmodified:docs/logging.md+19 added-19 removed
18 unmodified lines19 20 Will send debug level output to the console, or wherever `stdout` is directed too...21 22 ```23-DEBUG [2023-03-16 14:36:20] httpx - load_ssl_context verify=True cert=None trust_env=True http2=False24-DEBUG [2023-03-16 14:36:20] httpx - load_verify_locations cafile='/Users/tomchristie/GitHub/encode/httpx/venv/lib/python3.10/site-packages/certifi/cacert.pem'25-DEBUG [2023-03-16 14:36:20] httpcore - connection.connect_tcp.started host='www.example.com' port=443 local_address=None timeout=5.026-DEBUG [2023-03-16 14:36:20] httpcore - connection.connect_tcp.complete return_value=<httpcore.backends.sync.SyncStream object at 0x1068fd270>27-DEBUG [2023-03-16 14:36:20] httpcore - connection.start_tls.started ssl_context=<ssl.SSLContext object at 0x10689aa40> server_hostname='www.example.com' timeout=5.028-DEBUG [2023-03-16 14:36:20] httpcore - connection.start_tls.complete return_value=<httpcore.backends.sync.SyncStream object at 0x1068fd240>29-DEBUG [2023-03-16 14:36:20] httpcore - http11.send_request_headers.started request=<Request [b'GET']>30-DEBUG [2023-03-16 14:36:20] httpcore - http11.send_request_headers.complete31-DEBUG [2023-03-16 14:36:20] httpcore - http11.send_request_body.started request=<Request [b'GET']>32-DEBUG [2023-03-16 14:36:20] httpcore - http11.send_request_body.complete33-DEBUG [2023-03-16 14:36:20] httpcore - http11.receive_response_headers.started request=<Request [b'GET']>34-DEBUG [2023-03-16 14:36:21] httpcore - http11.receive_response_headers.complete return_value=(b'HTTP/1.1', 200, b'OK', [(b'Content-Encoding', b'gzip'), (b'Accept-Ranges', b'bytes'), (b'Age', b'507675'), (b'Cache-Control', b'max-age=604800'), (b'Content-Type', b'text/html; charset=UTF-8'), (b'Date', b'Thu, 16 Mar 2023 14:36:21 GMT'), (b'Etag', b'"3147526947+ident"'), (b'Expires', b'Thu, 23 Mar 2023 14:36:21 GMT'), (b'Last-Modified', b'Thu, 17 Oct 2019 07:18:26 GMT'), (b'Server', b'ECS (nyb/1D2E)'), (b'Vary', b'Accept-Encoding'), (b'X-Cache', b'HIT'), (b'Content-Length', b'648')])35-INFO [2023-03-16 14:36:21] httpx - HTTP Request: GET https://www.example.com "HTTP/1.1 200 OK"36-DEBUG [2023-03-16 14:36:21] httpcore - http11.receive_response_body.started request=<Request [b'GET']>37-DEBUG [2023-03-16 14:36:21] httpcore - http11.receive_response_body.complete38-DEBUG [2023-03-16 14:36:21] httpcore - http11.response_closed.started39-DEBUG [2023-03-16 14:36:21] httpcore - http11.response_closed.complete40-DEBUG [2023-03-16 14:36:21] httpcore - connection.close.started41-DEBUG [2023-03-16 14:36:21] httpcore - connection.close.complete23+DEBUG [2024-09-28 17:27:40] httpx - load_ssl_context verify=True cert=None24+DEBUG [2024-09-28 17:27:40] httpx - load_verify_locations cafile='/Users/karenpetrosyan/oss/karhttpx/.venv/lib/python3.9/site-packages/certifi/cacert.pem'25+DEBUG [2024-09-28 17:27:40] httpcore.connection - connect_tcp.started host='www.example.com' port=443 local_address=None timeout=5.0 socket_options=None26+DEBUG [2024-09-28 17:27:41] httpcore.connection - connect_tcp.complete return_value=<httpcore._backends.sync.SyncStream object at 0x101f1e8e0>27+DEBUG [2024-09-28 17:27:41] httpcore.connection - start_tls.started ssl_context=SSLContext(verify=True) server_hostname='www.example.com' timeout=5.028+DEBUG [2024-09-28 17:27:41] httpcore.connection - start_tls.complete return_value=<httpcore._backends.sync.SyncStream object at 0x1020f49a0>29+DEBUG [2024-09-28 17:27:41] httpcore.http11 - send_request_headers.started request=<Request [b'GET']>30+DEBUG [2024-09-28 17:27:41] httpcore.http11 - send_request_headers.complete31+DEBUG [2024-09-28 17:27:41] httpcore.http11 - send_request_body.started request=<Request [b'GET']>32+DEBUG [2024-09-28 17:27:41] httpcore.http11 - send_request_body.complete33+DEBUG [2024-09-28 17:27:41] httpcore.http11 - receive_response_headers.started request=<Request [b'GET']>34+DEBUG [2024-09-28 17:27:41] httpcore.http11 - receive_response_headers.complete return_value=(b'HTTP/1.1', 200, b'OK', [(b'Content-Encoding', b'gzip'), (b'Accept-Ranges', b'bytes'), (b'Age', b'407727'), (b'Cache-Control', b'max-age=604800'), (b'Content-Type', b'text/html; charset=UTF-8'), (b'Date', b'Sat, 28 Sep 2024 13:27:42 GMT'), (b'Etag', b'"3147526947+gzip"'), (b'Expires', b'Sat, 05 Oct 2024 13:27:42 GMT'), (b'Last-Modified', b'Thu, 17 Oct 2019 07:18:26 GMT'), (b'Server', b'ECAcc (dcd/7D43)'), (b'Vary', b'Accept-Encoding'), (b'X-Cache', b'HIT'), (b'Content-Length', b'648')])35+INFO [2024-09-28 17:27:41] httpx - HTTP Request: GET https://www.example.com "HTTP/1.1 200 OK"36+DEBUG [2024-09-28 17:27:41] httpcore.http11 - receive_response_body.started request=<Request [b'GET']>37+DEBUG [2024-09-28 17:27:41] httpcore.http11 - receive_response_body.complete38+DEBUG [2024-09-28 17:27:41] httpcore.http11 - response_closed.started39+DEBUG [2024-09-28 17:27:41] httpcore.http11 - response_closed.complete40+DEBUG [2024-09-28 17:27:41] httpcore.connection - close.started41+DEBUG [2024-09-28 17:27:41] httpcore.connection - close.complete42 ```43 44 Logging output includes information from both the high-level `httpx` logger, and the network-level `httpcore` logger, which can be configured separately.45 38 unmodified linesmodified:httpx/_transports/asgi.py+19 added-6 removed
1 from __future__ import annotations2 3 import typing4 5-import sniffio6-5 from .._models import Request, Response6 from .._types import AsyncByteStream7 from .base import AsyncBaseTransport8 16 unmodified lines25 26 __all__ = ["ASGITransport"]27 28 29+def is_running_trio() -> bool:30+ try:31+ # sniffio is a dependency of trio.32+33+ # See https://github.com/python-trio/trio/issues/280234+ import sniffio35+36+ if sniffio.current_async_library() == "trio":37+ return True38+ except ImportError: # pragma: nocover39+ pass40+41+ return False42+43+44 def create_event() -> Event:32- if sniffio.current_async_library() == "trio":45+ if is_running_trio():46 import trio47 48 return trio.Event()36- else:37- import asyncio49 39- return asyncio.Event()50+ import asyncio51 52+ return asyncio.Event()53 54+55 class ASGIResponseStream(AsyncByteStream):56 def __init__(self, body: list[bytes]) -> None:57 self._body = body58 129 unmodified linesmodified:httpx/_transports/default.py+21 added-10 removed
25 unmodified lines26 27 from __future__ import annotations28 29 import contextlib30+import ssl31 import typing32 from types import TracebackType33 34 import httpcore35 35-from .._config import DEFAULT_LIMITS, Limits, Proxy, create_ssl_context36+from .._config import DEFAULT_LIMITS, Limits, Proxy, SSLContext, create_ssl_context37 from .._exceptions import (38 ConnectError,39 ConnectTimeout,40 LocalProtocolError,9 unmodified lines50 WriteError,51 WriteTimeout,52 )53 from .._models import Request, Response53-from .._types import AsyncByteStream, CertTypes, ProxyTypes, SyncByteStream, VerifyTypes54+from .._types import AsyncByteStream, ProxyTypes, SyncByteStream55 from .._urls import URL56 from .base import AsyncBaseTransport, BaseTransport57 58 T = typing.TypeVar("T", bound="HTTPTransport")65 unmodified lines124 125 class HTTPTransport(BaseTransport):126 def __init__(127 self,127- verify: VerifyTypes = True,128- cert: CertTypes | None = None,128+ ssl_context: ssl.SSLContext | None = None,129 http1: bool = True,130 http2: bool = False,131 limits: Limits = DEFAULT_LIMITS,132- trust_env: bool = True,132 proxy: ProxyTypes | None = None,133 uds: str | None = None,134 local_address: str | None = None,135 retries: int = 0,136 socket_options: typing.Iterable[SOCKET_OPTION] | None = None,137+ # Deprecated...138+ verify: typing.Any = None,139+ cert: typing.Any = None,140 ) -> None:139- ssl_context = create_ssl_context(verify=verify, cert=cert, trust_env=trust_env)141 proxy = Proxy(url=proxy) if isinstance(proxy, (str, URL)) else proxy142+ if verify is not None or cert is not None: # pragma: nocover143+ # Deprecated...144+ ssl_context = create_ssl_context(verify, cert)145+ else:146+ ssl_context = ssl_context or SSLContext()147 148 if proxy is None:149 self._pool = httpcore.ConnectionPool(150 ssl_context=ssl_context,119 unmodified lines270 271 class AsyncHTTPTransport(AsyncBaseTransport):272 def __init__(273 self,268- verify: VerifyTypes = True,269- cert: CertTypes | None = None,274+ ssl_context: ssl.SSLContext | None = None,275 http1: bool = True,276 http2: bool = False,277 limits: Limits = DEFAULT_LIMITS,273- trust_env: bool = True,278 proxy: ProxyTypes | None = None,279 uds: str | None = None,280 local_address: str | None = None,281 retries: int = 0,282 socket_options: typing.Iterable[SOCKET_OPTION] | None = None,283+ # Deprecated...284+ verify: typing.Any = None,285+ cert: typing.Any = None,286 ) -> None:280- ssl_context = create_ssl_context(verify=verify, cert=cert, trust_env=trust_env)287 proxy = Proxy(url=proxy) if isinstance(proxy, (str, URL)) else proxy288+ if verify is not None or cert is not None: # pragma: nocover289+ # Deprecated...290+ ssl_context = create_ssl_context(verify, cert)291+ else:292+ ssl_context = ssl_context or SSLContext()293 294 if proxy is None:295 self._pool = httpcore.AsyncConnectionPool(296 ssl_context=ssl_context,104 unmodified linesmodified:httpx/__init__.py+1 added
79 unmodified lines80 "RequestError",81 "RequestNotRead",82 "Response",83 "ResponseNotRead",84+ "SSLContext",85 "stream",86 "StreamClosed",87 "StreamConsumed",88 "StreamError",18 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.27.2"3+__version__ = "0.28.0"modified:httpx/_api.py+66 added-66 removed
1 from __future__ import annotations2 3+import ssl4 import typing5 from contextlib import contextmanager6 7 from ._client import Client8 from ._config import DEFAULT_TIMEOUT_CONFIG9 from ._models import Response10 from ._types import (11 AuthTypes,11- CertTypes,12 CookieTypes,13 HeaderTypes,14- ProxiesTypes,14 ProxyTypes,15 QueryParamTypes,16 RequestContent,17 RequestData,18 RequestFiles,19 TimeoutTypes,21- VerifyTypes,20 )21 from ._urls import URL22 23 __all__ = [21 unmodified lines45 headers: HeaderTypes | None = None,46 cookies: CookieTypes | None = None,47 auth: AuthTypes | None = None,48 proxy: ProxyTypes | None = None,51- proxies: ProxiesTypes | None = None,49 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,50 follow_redirects: bool = False,54- verify: VerifyTypes = True,55- cert: CertTypes | None = None,51+ ssl_context: ssl.SSLContext | None = None,52 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 18 unmodified lines78 request.79 * **auth** - *(optional)* An authentication class to use when sending the80 request.81 * **proxy** - *(optional)* A proxy URL where all the traffic should be routed.83- * **proxies** - *(optional)* A dictionary mapping proxy keys to proxy URLs.82 * **timeout** - *(optional)* The timeout configuration to use when sending83 the request.84 * **follow_redirects** - *(optional)* Enables or disables HTTP redirects.87- * **verify** - *(optional)* SSL certificates (a.k.a CA bundle) used to88- verify the identity of requested hosts. Either `True` (default CA bundle),89- a path to an SSL certificate file, an `ssl.SSLContext`, or `False`90- (which will disable verification).91- * **cert** - *(optional)* An SSL certificate used by the requested host92- to authenticate the client. Either a path to an SSL certificate file, or85+ * **ssl_context** - *(optional)* An SSL certificate used by the requested host86+ to authenticate the client.93- two-tuple of (certificate file, key file), or a three-tuple of (certificate94- file, key file, password).87 * **trust_env** - *(optional)* Enables or disables usage of environment88 variables for configuration.89 90 **Returns:** `Response`9 unmodified lines100 """101 with Client(102 cookies=cookies,103 proxy=proxy,112- proxies=proxies,113- cert=cert,114- verify=verify,104+ ssl_context=ssl_context,105 timeout=timeout,106 trust_env=trust_env,107+ verify=verify,108+ cert=cert,109 ) as client:110 return client.request(111 method=method,112 url=url,21 unmodified lines134 headers: HeaderTypes | None = None,135 cookies: CookieTypes | None = None,136 auth: AuthTypes | None = None,137 proxy: ProxyTypes | None = None,146- proxies: ProxiesTypes | None = None,138 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,139 follow_redirects: bool = False,149- verify: VerifyTypes = True,150- cert: CertTypes | None = None,140+ ssl_context: ssl.SSLContext | None = None,141 trust_env: bool = True,142+ # Deprecated in favor of `ssl_context`...143+ verify: typing.Any = None,144+ cert: typing.Any = None,145 ) -> typing.Iterator[Response]:146 """147 Alternative to `httpx.request()` that streams the response body148 instead of loading it into memory at once.6 unmodified lines155 """156 with Client(157 cookies=cookies,158 proxy=proxy,166- proxies=proxies,167- cert=cert,168- verify=verify,159+ ssl_context=ssl_context,160 timeout=timeout,161 trust_env=trust_env,162+ verify=verify,163+ cert=cert,164 ) as client:165 with client.stream(166 method=method,167 url=url,16 unmodified lines184 headers: HeaderTypes | None = None,185 cookies: CookieTypes | None = None,186 auth: AuthTypes | None = None,187 proxy: ProxyTypes | None = None,195- proxies: ProxiesTypes | None = None,188 follow_redirects: bool = False,197- cert: CertTypes | None = None,198- verify: VerifyTypes = True,189+ ssl_context: ssl.SSLContext | None = None,190 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,191 trust_env: bool = True,192+ # Deprecated in favor of `ssl_context`...193+ verify: typing.Any = None,194+ cert: typing.Any = None,195 ) -> Response:196 """197 Sends a `GET` request.198 9 unmodified lines208 headers=headers,209 cookies=cookies,210 auth=auth,211 proxy=proxy,218- proxies=proxies,212 follow_redirects=follow_redirects,220- cert=cert,221- verify=verify,213+ ssl_context=ssl_context,214 timeout=timeout,215 trust_env=trust_env,216+ verify=verify,217+ cert=cert,218 )219 220 221 def options(3 unmodified lines225 headers: HeaderTypes | None = None,226 cookies: CookieTypes | None = None,227 auth: AuthTypes | None = None,228 proxy: ProxyTypes | None = None,235- proxies: ProxiesTypes | None = None,229 follow_redirects: bool = False,237- cert: CertTypes | None = None,238- verify: VerifyTypes = True,230+ ssl_context: ssl.SSLContext | None = None,231 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,232 trust_env: bool = True,233+ # Deprecated in favor of `ssl_context`...234+ verify: typing.Any = None,235+ cert: typing.Any = None,236 ) -> Response:237 """238 Sends an `OPTIONS` request.239 9 unmodified lines249 headers=headers,250 cookies=cookies,251 auth=auth,252 proxy=proxy,258- proxies=proxies,253 follow_redirects=follow_redirects,260- cert=cert,261- verify=verify,254+ ssl_context=ssl_context,255 timeout=timeout,256 trust_env=trust_env,257+ verify=verify,258+ cert=cert,259 )260 261 262 def head(3 unmodified lines266 headers: HeaderTypes | None = None,267 cookies: CookieTypes | None = None,268 auth: AuthTypes | None = None,269 proxy: ProxyTypes | None = None,275- proxies: ProxiesTypes | None = None,270 follow_redirects: bool = False,277- cert: CertTypes | None = None,278- verify: VerifyTypes = True,271+ ssl_context: ssl.SSLContext | None = None,272 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,273 trust_env: bool = True,274+ # Deprecated in favor of `ssl_context`...275+ verify: typing.Any = None,276+ cert: typing.Any = None,277 ) -> Response:278 """279 Sends a `HEAD` request.280 9 unmodified lines290 headers=headers,291 cookies=cookies,292 auth=auth,293 proxy=proxy,298- proxies=proxies,294 follow_redirects=follow_redirects,300- cert=cert,301- verify=verify,295+ ssl_context=ssl_context,296 timeout=timeout,297 trust_env=trust_env,298+ verify=verify,299+ cert=cert,300 )301 302 303 def post(7 unmodified lines311 headers: HeaderTypes | None = None,312 cookies: CookieTypes | None = None,313 auth: AuthTypes | None = None,314 proxy: ProxyTypes | None = None,319- proxies: ProxiesTypes | None = None,315 follow_redirects: bool = False,321- cert: CertTypes | None = None,322- verify: VerifyTypes = True,316+ ssl_context: ssl.SSLContext | None = None,317 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,318 trust_env: bool = True,319+ # Deprecated in favor of `ssl_context`...320+ verify: typing.Any = None,321+ cert: typing.Any = None,322 ) -> Response:323 """324 Sends a `POST` request.325 10 unmodified lines336 headers=headers,337 cookies=cookies,338 auth=auth,339 proxy=proxy,343- proxies=proxies,340 follow_redirects=follow_redirects,345- cert=cert,346- verify=verify,341+ ssl_context=ssl_context,342 timeout=timeout,343 trust_env=trust_env,344+ verify=verify,345+ cert=cert,346 )347 348 349 def put(7 unmodified lines357 headers: HeaderTypes | None = None,358 cookies: CookieTypes | None = None,359 auth: AuthTypes | None = None,360 proxy: ProxyTypes | None = None,364- proxies: ProxiesTypes | None = None,361 follow_redirects: bool = False,366- cert: CertTypes | None = None,367- verify: VerifyTypes = True,362+ ssl_context: ssl.SSLContext | None = None,363 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,364 trust_env: bool = True,365+ # Deprecated in favor of `ssl_context`...366+ verify: typing.Any = None,367+ cert: typing.Any = None,368 ) -> Response:369 """370 Sends a `PUT` request.371 10 unmodified lines382 headers=headers,383 cookies=cookies,384 auth=auth,385 proxy=proxy,388- proxies=proxies,386 follow_redirects=follow_redirects,390- cert=cert,391- verify=verify,387+ ssl_context=ssl_context,388 timeout=timeout,389 trust_env=trust_env,390+ verify=verify,391+ cert=cert,392 )393 394 395 def patch(7 unmodified lines403 headers: HeaderTypes | None = None,404 cookies: CookieTypes | None = None,405 auth: AuthTypes | None = None,406 proxy: ProxyTypes | None = None,409- proxies: ProxiesTypes | None = None,407 follow_redirects: bool = False,411- cert: CertTypes | None = None,412- verify: VerifyTypes = True,408+ ssl_context: ssl.SSLContext | None = None,409 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,410 trust_env: bool = True,411+ # Deprecated in favor of `ssl_context`...412+ verify: typing.Any = None,413+ cert: typing.Any = None,414 ) -> Response:415 """416 Sends a `PATCH` request.417 10 unmodified lines428 headers=headers,429 cookies=cookies,430 auth=auth,431 proxy=proxy,433- proxies=proxies,432 follow_redirects=follow_redirects,435- cert=cert,436- verify=verify,433+ ssl_context=ssl_context,434 timeout=timeout,435 trust_env=trust_env,436+ verify=verify,437+ cert=cert,438 )439 440 441 def delete(3 unmodified lines445 headers: HeaderTypes | None = None,446 cookies: CookieTypes | None = None,447 auth: AuthTypes | None = None,448 proxy: ProxyTypes | None = None,450- proxies: ProxiesTypes | None = None,449 follow_redirects: bool = False,452- cert: CertTypes | None = None,453- verify: VerifyTypes = True,450 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,451+ ssl_context: ssl.SSLContext | None = None,452 trust_env: bool = True,453+ # Deprecated in favor of `ssl_context`...454+ verify: typing.Any = None,455+ cert: typing.Any = None,456 ) -> Response:457 """458 Sends a `DELETE` request.459 9 unmodified lines469 headers=headers,470 cookies=cookies,471 auth=auth,472 proxy=proxy,473- proxies=proxies,473 follow_redirects=follow_redirects,475- cert=cert,476- verify=verify,474+ ssl_context=ssl_context,475 timeout=timeout,476 trust_env=trust_env,477+ verify=verify,478+ cert=cert,479 )modified:httpx/_client.py+79 added-140 removed
1 unmodified line2 3 import datetime4 import enum5 import logging6+import ssl7+import time8 import typing9 import warnings10 from contextlib import asynccontextmanager, contextmanager11 from types import TracebackType16 unmodified lines28 request_context,29 )30 from ._models import Cookies, Headers, Request, Response31 from ._status_codes import codes30-from ._transports.asgi import ASGITransport32 from ._transports.base import AsyncBaseTransport, BaseTransport33 from ._transports.default import AsyncHTTPTransport, HTTPTransport33-from ._transports.wsgi import WSGITransport34 from ._types import (35 AsyncByteStream,36 AuthTypes,37- CertTypes,37 CookieTypes,38 HeaderTypes,40- ProxiesTypes,39 ProxyTypes,40 QueryParamTypes,41 RequestContent,42 RequestData,43 RequestExtensions,44 RequestFiles,45 SyncByteStream,46 TimeoutTypes,49- VerifyTypes,47 )48 from ._urls import URL, QueryParams49 from ._utils import (53- Timer,50 URLPattern,51 get_environment_proxies,52 is_https_redirect,53 same_origin,58 unmodified lines112 ensures the `response.elapsed` is set once the response is closed.113 """114 115 def __init__(120- self, stream: SyncByteStream, response: Response, timer: Timer116+ self, stream: SyncByteStream, response: Response, start: float117 ) -> None:118 self._stream = stream119 self._response = response124- self._timer = timer120+ self._start = start121 122 def __iter__(self) -> typing.Iterator[bytes]:123 for chunk in self._stream:124 yield chunk125 126 def close(self) -> None:131- seconds = self._timer.sync_elapsed()132- self._response.elapsed = datetime.timedelta(seconds=seconds)127+ elapsed = time.perf_counter() - self._start128+ self._response.elapsed = datetime.timedelta(seconds=elapsed)129 self._stream.close()130 131 132 class BoundAsyncStream(AsyncByteStream):2 unmodified lines135 ensures the `response.elapsed` is set once the response is closed.136 """137 138 def __init__(143- self, stream: AsyncByteStream, response: Response, timer: Timer139+ self, stream: AsyncByteStream, response: Response, start: float140 ) -> None:141 self._stream = stream142 self._response = response147- self._timer = timer143+ self._start = start144 145 async def __aiter__(self) -> typing.AsyncIterator[bytes]:146 async for chunk in self._stream:147 yield chunk148 149 async def aclose(self) -> None:154- seconds = await self._timer.async_elapsed()155- self._response.elapsed = datetime.timedelta(seconds=seconds)150+ elapsed = time.perf_counter() - self._start151+ self._response.elapsed = datetime.timedelta(seconds=elapsed)152 await self._stream.aclose()153 154 155 EventHook = typing.Callable[..., typing.Any]50 unmodified lines206 return url207 return url.copy_with(raw_path=url.raw_path + b"/")208 209 def _get_proxy_map(214- self, proxies: ProxiesTypes | None, allow_env_proxies: bool210+ self, proxy: ProxyTypes | None, allow_env_proxies: bool211 ) -> dict[str, Proxy | None]:216- if proxies is None:212+ if proxy is None:213 if allow_env_proxies:214 return {215 key: None if url is None else Proxy(url=url)216 for key, url in get_environment_proxies().items()217 }218 return {}223- if isinstance(proxies, dict):224- new_proxies = {}225- for key, value in proxies.items():226- proxy = Proxy(url=value) if isinstance(value, (str, URL)) else value227- new_proxies[str(key)] = proxy228- return new_proxies219 else:230- proxy = Proxy(url=proxies) if isinstance(proxies, (str, URL)) else proxies220+ proxy = Proxy(url=proxy) if isinstance(proxy, (str, URL)) else proxy221 return {"all://": proxy}222 223 @property224 def timeout(self) -> Timeout:358 unmodified lines583 * **headers** - *(optional)* Dictionary of HTTP headers to include when584 sending requests.585 * **cookies** - *(optional)* Dictionary of Cookie items to include when586 sending requests.597- * **verify** - *(optional)* SSL certificates (a.k.a CA bundle) used to598- verify the identity of requested hosts. Either `True` (default CA bundle),599- a path to an SSL certificate file, an `ssl.SSLContext`, or `False`600- (which will disable verification).601- * **cert** - *(optional)* An SSL certificate used by the requested host602- to authenticate the client. Either a path to an SSL certificate file, or587+ * **ssl_context** - *(optional)* An SSL certificate used by the requested host588+ to authenticate the client.603- two-tuple of (certificate file, key file), or a three-tuple of (certificate604- file, key file, password).589 * **http2** - *(optional)* A boolean indicating if HTTP/2 support should be590 enabled. Defaults to `False`.591 * **proxy** - *(optional)* A proxy URL where all the traffic should be routed.592 * **proxies** - *(optional)* A dictionary mapping proxy keys to proxy6 unmodified lines599 * **base_url** - *(optional)* A URL to use as the base when building600 request URLs.601 * **transport** - *(optional)* A transport class to use for sending requests602 over the network.619- * **app** - *(optional)* An WSGI application to send requests to,620- rather than sending actual network requests.603 * **trust_env** - *(optional)* Enables or disables usage of environment604 variables for configuration.605 * **default_encoding** - *(optional)* The default encoding to use for decoding606 response text, if no charset information is included in a response Content-Type6 unmodified lines613 auth: AuthTypes | None = None,614 params: QueryParamTypes | None = None,615 headers: HeaderTypes | None = None,616 cookies: CookieTypes | None = None,635- verify: VerifyTypes = True,636- cert: CertTypes | None = None,617+ ssl_context: ssl.SSLContext | None = None,618 http1: bool = True,619 http2: bool = False,620 proxy: ProxyTypes | None = None,640- proxies: ProxiesTypes | None = None,621 mounts: None | (typing.Mapping[str, BaseTransport | None]) = None,622 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,623 follow_redirects: bool = False,624 limits: Limits = DEFAULT_LIMITS,625 max_redirects: int = DEFAULT_MAX_REDIRECTS,626 event_hooks: None | (typing.Mapping[str, list[EventHook]]) = None,627 base_url: URL | str = "",628 transport: BaseTransport | None = None,649- app: typing.Callable[..., typing.Any] | None = None,629 trust_env: bool = True,630 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,16 unmodified lines654 "Using http2=True, but the 'h2' package is not installed. "655 "Make sure to install httpx using `pip install httpx[http2]`."656 ) from None657 676- if proxies:677- message = (678- "The 'proxies' argument is now deprecated."679- " Use 'proxy' or 'mounts' instead."680- )681- warnings.warn(message, DeprecationWarning)682- if proxy:683- raise RuntimeError("Use either `proxy` or 'proxies', not both.")658+ allow_env_proxies = trust_env and transport is None659+ proxy_map = self._get_proxy_map(proxy, allow_env_proxies)660 685- if app:686- message = (687- "The 'app' shortcut is now deprecated."688- " Use the explicit style 'transport=WSGITransport(app=...)' instead."689- )690- warnings.warn(message, DeprecationWarning)691-692- allow_env_proxies = trust_env and app is None and transport is None693- proxy_map = self._get_proxy_map(proxies or proxy, allow_env_proxies)694-661 self._transport = self._init_transport(696- verify=verify,697- cert=cert,662+ ssl_context=ssl_context,663 http1=http1,664 http2=http2,665 limits=limits,666 transport=transport,702- app=app,667 trust_env=trust_env,668+ # Deprecated in favor of ssl_context...669+ verify=verify,670+ cert=cert,671 )672 self._mounts: dict[URLPattern, BaseTransport | None] = {673 URLPattern(key): None674 if proxy is None675 else self._init_proxy_transport(676 proxy,710- verify=verify,711- cert=cert,677+ ssl_context=ssl_context,678 http1=http1,679 http2=http2,680 limits=limits,715- trust_env=trust_env,681+ # Deprecated in favor of ssl_context...682+ verify=verify,683+ cert=cert,684 )685 for key, proxy in proxy_map.items()686 }687 if mounts is not None:4 unmodified lines692 self._mounts = dict(sorted(self._mounts.items()))693 694 def _init_transport(695 self,728- verify: VerifyTypes = True,729- cert: CertTypes | None = None,696+ ssl_context: ssl.SSLContext | None = None,697 http1: bool = True,698 http2: bool = False,699 limits: Limits = DEFAULT_LIMITS,700 transport: BaseTransport | None = None,734- app: typing.Callable[..., typing.Any] | None = None,701 trust_env: bool = True,702+ # Deprecated in favor of `ssl_context`...703+ verify: typing.Any = None,704+ cert: typing.Any = None,705 ) -> BaseTransport:706 if transport is not None:707 return transport708 740- if app is not None:741- return WSGITransport(app=app)742-709 return HTTPTransport(744- verify=verify,745- cert=cert,710+ ssl_context=ssl_context,711 http1=http1,712 http2=http2,713 limits=limits,749- trust_env=trust_env,714+ verify=verify,715+ cert=cert,716 )717 718 def _init_proxy_transport(719 self,720 proxy: Proxy,755- verify: VerifyTypes = True,756- cert: CertTypes | None = None,721+ ssl_context: ssl.SSLContext | None = None,722 http1: bool = True,723 http2: bool = False,724 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,729 ) -> BaseTransport:730 return HTTPTransport(763- verify=verify,764- cert=cert,731+ ssl_context=ssl_context,732 http1=http1,733 http2=http2,734 limits=limits,768- trust_env=trust_env,735 proxy=proxy,736+ verify=verify,737+ cert=cert,738 )739 740 def _transport_for_url(self, url: URL) -> BaseTransport:741 """44 unmodified lines786 "Setting per-request cookies=<...> is being deprecated, because "787 "the expected behaviour on cookie persistence is ambiguous. Set "788 "cookies directly on the client instance instead."789 )822- warnings.warn(message, DeprecationWarning)790+ warnings.warn(message, DeprecationWarning, stacklevel=2)791 792 request = self.build_request(793 method=method,794 url=url,187 unmodified lines982 """983 Sends a single request, without handling any redirections.984 """985 transport = self._transport_for_url(request.url)1018- timer = Timer()1019- timer.sync_start()986+ start = time.perf_counter()987 988 if not isinstance(request.stream, SyncByteStream):989 raise RuntimeError(990 "Attempted to send an async request with a sync Client instance."5 unmodified lines996 assert isinstance(response.stream, SyncByteStream)997 998 response.request = request999 response.stream = BoundSyncStream(1033- response.stream, response=response, timer=timer1000+ response.stream, response=response, start=start1001 )1002 self.cookies.extract_cookies(response)1003 response.default_encoding = self._default_encoding1004 302 unmodified lines1307 * **headers** - *(optional)* Dictionary of HTTP headers to include when1308 sending requests.1309 * **cookies** - *(optional)* Dictionary of Cookie items to include when1310 sending requests.1344- * **verify** - *(optional)* SSL certificates (a.k.a CA bundle) used to1345- verify the identity of requested hosts. Either `True` (default CA bundle),1346- a path to an SSL certificate file, an `ssl.SSLContext`, or `False`1347- (which will disable verification).1348- * **cert** - *(optional)* An SSL certificate used by the requested host1349- to authenticate the client. Either a path to an SSL certificate file, or1311+ * **ssl_context** - *(optional)* An SSL certificate used by the requested host1312+ to authenticate the client.1350- two-tuple of (certificate file, key file), or a three-tuple of (certificate1351- file, key file, password).1313 * **http2** - *(optional)* A boolean indicating if HTTP/2 support should be1314 enabled. Defaults to `False`.1315 * **proxy** - *(optional)* A proxy URL where all the traffic should be routed.1355- * **proxies** - *(optional)* A dictionary mapping HTTP protocols to proxy1356- URLs.1316 * **timeout** - *(optional)* The timeout configuration to use when sending1317 requests.1318 * **limits** - *(optional)* The limits configuration to use.1319 * **max_redirects** - *(optional)* The maximum number of redirect responses1 unmodified line1321 * **base_url** - *(optional)* A URL to use as the base when building1322 request URLs.1323 * **transport** - *(optional)* A transport class to use for sending requests1324 over the network.1366- * **app** - *(optional)* An ASGI application to send requests to,1367- rather than sending actual network requests.1325 * **trust_env** - *(optional)* Enables or disables usage of environment1326 variables for configuration.1327 * **default_encoding** - *(optional)* The default encoding to use for decoding1328 response text, if no charset information is included in a response Content-Type6 unmodified lines1335 auth: AuthTypes | None = None,1336 params: QueryParamTypes | None = None,1337 headers: HeaderTypes | None = None,1338 cookies: CookieTypes | None = None,1382- verify: VerifyTypes = True,1383- cert: CertTypes | None = None,1339+ ssl_context: ssl.SSLContext | None = None,1340 http1: bool = True,1341 http2: bool = False,1342 proxy: ProxyTypes | None = None,1387- proxies: ProxiesTypes | None = None,1343 mounts: None | (typing.Mapping[str, AsyncBaseTransport | None]) = None,1344 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,1345 follow_redirects: bool = False,1346 limits: Limits = DEFAULT_LIMITS,1347 max_redirects: int = DEFAULT_MAX_REDIRECTS,1348 event_hooks: None | (typing.Mapping[str, list[EventHook]]) = None,1349 base_url: URL | str = "",1350 transport: AsyncBaseTransport | None = None,1396- app: typing.Callable[..., typing.Any] | None = None,1351 trust_env: bool = True,1352 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,1356 ) -> None:1357 super().__init__(1358 auth=auth,1359 params=params,16 unmodified lines1376 "Using http2=True, but the 'h2' package is not installed. "1377 "Make sure to install httpx using `pip install httpx[http2]`."1378 ) from None1379 1423- if proxies:1424- message = (1425- "The 'proxies' argument is now deprecated."1426- " Use 'proxy' or 'mounts' instead."1427- )1428- warnings.warn(message, DeprecationWarning)1429- if proxy:1430- raise RuntimeError("Use either `proxy` or 'proxies', not both.")1380+ allow_env_proxies = trust_env and transport is None1381+ proxy_map = self._get_proxy_map(proxy, allow_env_proxies)1382 1432- if app:1433- message = (1434- "The 'app' shortcut is now deprecated."1435- " Use the explicit style 'transport=ASGITransport(app=...)' instead."1436- )1437- warnings.warn(message, DeprecationWarning)1438-1439- allow_env_proxies = trust_env and app is None and transport is None1440- proxy_map = self._get_proxy_map(proxies or proxy, allow_env_proxies)1441-1383 self._transport = self._init_transport(1443- verify=verify,1444- cert=cert,1384+ ssl_context=ssl_context,1385 http1=http1,1386 http2=http2,1387 limits=limits,1388 transport=transport,1449- app=app,1450- trust_env=trust_env,1389+ # Deprecated in favor of ssl_context1390+ verify=verify,1391+ cert=cert,1392 )1393 1394 self._mounts: dict[URLPattern, AsyncBaseTransport | None] = {1395 URLPattern(key): None1396 if proxy is None1397 else self._init_proxy_transport(1398 proxy,1458- verify=verify,1459- cert=cert,1399+ ssl_context=ssl_context,1400 http1=http1,1401 http2=http2,1402 limits=limits,1463- trust_env=trust_env,1403+ # Deprecated in favor of `ssl_context`...1404+ verify=verify,1405+ cert=cert,1406 )1407 for key, proxy in proxy_map.items()1408 }1409 if mounts is not None:3 unmodified lines1413 self._mounts = dict(sorted(self._mounts.items()))1414 1415 def _init_transport(1416 self,1475- verify: VerifyTypes = True,1476- cert: CertTypes | None = None,1417+ ssl_context: ssl.SSLContext | None = None,1418 http1: bool = True,1419 http2: bool = False,1420 limits: Limits = DEFAULT_LIMITS,1421 transport: AsyncBaseTransport | None = None,1481- app: typing.Callable[..., typing.Any] | None = None,1482- trust_env: bool = True,1422+ # Deprecated in favor of `ssl_context`...1423+ verify: typing.Any = None,1424+ cert: typing.Any = None,1425 ) -> AsyncBaseTransport:1426 if transport is not None:1427 return transport1428 1487- if app is not None:1488- return ASGITransport(app=app)1489-1429 return AsyncHTTPTransport(1491- verify=verify,1492- cert=cert,1430+ ssl_context=ssl_context,1431 http1=http1,1432 http2=http2,1433 limits=limits,1496- trust_env=trust_env,1434+ verify=verify,1435+ cert=cert,1436 )1437 1438 def _init_proxy_transport(1439 self,1440 proxy: Proxy,1502- verify: VerifyTypes = True,1503- cert: CertTypes | None = None,1441+ ssl_context: ssl.SSLContext | None = None,1442 http1: bool = True,1443 http2: bool = False,1444 limits: Limits = DEFAULT_LIMITS,1507- trust_env: bool = True,1445+ # Deprecated in favor of `ssl_context`...1446+ verify: typing.Any = None,1447+ cert: typing.Any = None,1448 ) -> AsyncBaseTransport:1449 return AsyncHTTPTransport(1510- verify=verify,1511- cert=cert,1450+ ssl_context=ssl_context,1451 http1=http1,1452 http2=http2,1453 limits=limits,1515- trust_env=trust_env,1454 proxy=proxy,1455+ verify=verify,1456+ cert=cert,1457 )1458 1459 def _transport_for_url(self, url: URL) -> AsyncBaseTransport:1460 """45 unmodified lines1506 "Setting per-request cookies=<...> is being deprecated, because "1507 "the expected behaviour on cookie persistence is ambiguous. Set "1508 "cookies directly on the client instance instead."1509 )1570- warnings.warn(message, DeprecationWarning)1510+ warnings.warn(message, DeprecationWarning, stacklevel=2)1511 1512 request = self.build_request(1513 method=method,1514 url=url,188 unmodified lines1703 """1704 Sends a single request, without handling any redirections.1705 """1706 transport = self._transport_for_url(request.url)1767- timer = Timer()1768- await timer.async_start()1707+ start = time.perf_counter()1708 1709 if not isinstance(request.stream, AsyncByteStream):1710 raise RuntimeError(1711 "Attempted to send an sync request with an AsyncClient instance."4 unmodified lines1716 1717 assert isinstance(response.stream, AsyncByteStream)1718 response.request = request1719 response.stream = BoundAsyncStream(1781- response.stream, response=response, timer=timer1720+ response.stream, response=response, start=start1721 )1722 self.cookies.extract_cookies(response)1723 response.default_encoding = self._default_encoding1724 280 unmodified linesdeleted:httpx/_compat.py-63 removed
1-"""2-The _compat module is used for code which requires branching between different3-Python environments. It is excluded from the code coverage checks.4-"""5-6-import re7-import ssl8-import sys9-from types import ModuleType10-from typing import Optional11-12-# Brotli support is optional13-# The C bindings in `brotli` are recommended for CPython.14-# The CFFI bindings in `brotlicffi` are recommended for PyPy and everything else.15-try:16- import brotlicffi as brotli17-except ImportError: # pragma: no cover18- try:19- import brotli20- except ImportError:21- brotli = None22-23-# Zstandard support is optional24-zstd: Optional[ModuleType] = None25-try:26- import zstandard as zstd27-except (AttributeError, ImportError, ValueError): # Defensive:28- zstd = None29-else:30- # The package 'zstandard' added the 'eof' property starting31- # in v0.18.0 which we require to ensure a complete and32- # valid zstd stream was fed into the ZstdDecoder.33- # See: https://github.com/urllib3/urllib3/pull/262434- _zstd_version = tuple(35- map(int, re.search(r"^([0-9]+)\.([0-9]+)", zstd.__version__).groups()) # type: ignore[union-attr]36- )37- if _zstd_version < (0, 18): # Defensive:38- zstd = None39-40-41-if sys.version_info >= (3, 10) or ssl.OPENSSL_VERSION_INFO >= (1, 1, 0, 7):42-43- def set_minimum_tls_version_1_2(context: ssl.SSLContext) -> None:44- # The OP_NO_SSL* and OP_NO_TLS* become deprecated in favor of45- # 'SSLContext.minimum_version' from Python 3.7 onwards, however46- # this attribute is not available unless the ssl module is compiled47- # with OpenSSL 1.1.0g or newer.48- # https://docs.python.org/3.10/library/ssl.html#ssl.SSLContext.minimum_version49- # https://docs.python.org/3.7/library/ssl.html#ssl.SSLContext.minimum_version50- context.minimum_version = ssl.TLSVersion.TLSv1_251-52-else:53-54- def set_minimum_tls_version_1_2(context: ssl.SSLContext) -> None:55- # If 'minimum_version' isn't available, we configure these options with56- # the older deprecated variants.57- context.options |= ssl.OP_NO_SSLv258- context.options |= ssl.OP_NO_SSLv359- context.options |= ssl.OP_NO_TLSv160- context.options |= ssl.OP_NO_TLSv1_161-62-63-__all__ = ["brotli", "set_minimum_tls_version_1_2"]modified:httpx/_config.py+84 added-156 removed
1 from __future__ import annotations2 3-import logging3 import os4 import ssl5+import sys6 import typing7-from pathlib import Path7+import warnings8 9 import certifi10 11-from ._compat import set_minimum_tls_version_1_211 from ._models import Headers13-from ._types import CertTypes, HeaderTypes, TimeoutTypes, VerifyTypes12+from ._types import HeaderTypes, TimeoutTypes13 from ._urls import URL15-from ._utils import get_ca_bundle_from_env14 17-__all__ = ["Limits", "Proxy", "Timeout", "create_ssl_context"]15+__all__ = ["Limits", "Proxy", "SSLContext", "Timeout", "create_ssl_context"]16 19-DEFAULT_CIPHERS = ":".join(20- [21- "ECDHE+AESGCM",22- "ECDHE+CHACHA20",23- "DHE+AESGCM",24- "DHE+CHACHA20",25- "ECDH+AESGCM",26- "DH+AESGCM",27- "ECDH+AES",28- "DH+AES",29- "RSA+AESGCM",30- "RSA+AES",31- "!aNULL",32- "!eNULL",33- "!MD5",34- "!DSS",35- ]36-)17 38-39-logger = logging.getLogger("httpx")40-41-18 class UnsetType:19 pass # pragma: no cover20 21 22 UNSET = UnsetType()23 24 25 def create_ssl_context(50- cert: CertTypes | None = None,51- verify: VerifyTypes = True,26+ verify: typing.Any = None,27+ cert: typing.Any = None,28 trust_env: bool = True,29 http2: bool = False,54-) -> ssl.SSLContext:55- return SSLConfig(56- cert=cert, verify=verify, trust_env=trust_env, http2=http257- ).ssl_context30+) -> ssl.SSLContext: # pragma: nocover31+ # The `create_ssl_context` helper function is now deprecated32+ # in favour of `httpx.SSLContext()`.33+ if isinstance(verify, bool):34+ ssl_context: ssl.SSLContext = SSLContext(verify=verify)35+ warnings.warn(36+ "The verify=<bool> parameter is deprecated since 0.28.0. "37+ "Use `ssl_context=httpx.SSLContext(verify=<bool>)`."38+ )39+ elif isinstance(verify, str):40+ warnings.warn(41+ "The verify=<str> parameter is deprecated since 0.28.0. "42+ "Use `ssl_context=httpx.SSLContext()` and `.load_verify_locations()`."43+ )44+ ssl_context = SSLContext()45+ if os.path.isfile(verify):46+ ssl_context.load_verify_locations(cafile=verify)47+ elif os.path.isdir(verify):48+ ssl_context.load_verify_locations(capath=verify)49+ elif isinstance(verify, ssl.SSLContext):50+ warnings.warn(51+ "The verify=<ssl context> parameter is deprecated since 0.28.0. "52+ "Use `ssl_context = httpx.SSLContext()`."53+ )54+ ssl_context = verify55+ else:56+ warnings.warn(57+ "`create_ssl_context()` is deprecated since 0.28.0."58+ "Use `ssl_context = httpx.SSLContext()`."59+ )60+ ssl_context = SSLContext()61 62+ if cert is not None:63+ warnings.warn(64+ "The `cert=<...>` parameter is deprecated since 0.28.0. "65+ "Use `ssl_context = httpx.SSLContext()` and `.load_cert_chain()`."66+ )67+ if isinstance(cert, str):68+ ssl_context.load_cert_chain(cert)69+ else:70+ ssl_context.load_cert_chain(*cert)71 60-class SSLConfig:61- """62- SSL Configuration.63- """72+ return ssl_context73 65- DEFAULT_CA_BUNDLE_PATH = Path(certifi.where())74 75+class SSLContext(ssl.SSLContext):76 def __init__(77 self,69- *,70- cert: CertTypes | None = None,71- verify: VerifyTypes = True,72- trust_env: bool = True,73- http2: bool = False,78+ verify: bool = True,79 ) -> None:75- self.cert = cert76- self.verify = verify77- self.trust_env = trust_env78- self.http2 = http279- self.ssl_context = self.load_ssl_context()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__()84+ self._verify = verify85 81- def load_ssl_context(self) -> ssl.SSLContext:82- logger.debug(83- "load_ssl_context verify=%r cert=%r trust_env=%r http2=%r",84- self.verify,85- self.cert,86- self.trust_env,87- self.http2,88- )86+ # 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+ return92 90- if self.verify:91- return self.load_ssl_context_verify()92- return self.load_ssl_context_no_verify()93+ self.verify_mode = ssl.CERT_REQUIRED94+ self.check_hostname = True95 94- def load_ssl_context_no_verify(self) -> ssl.SSLContext:95- """96- Return an SSL context for unverified connections.97- """98- context = self._create_default_ssl_context()99- context.check_hostname = False100- context.verify_mode = ssl.CERT_NONE101- self._load_client_certs(context)102- return context96+ # 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_STRICT101 104- def load_ssl_context_verify(self) -> ssl.SSLContext:105- """106- Return an SSL context for verified connections.107- """108- if self.trust_env and self.verify is True:109- ca_bundle = get_ca_bundle_from_env()110- if ca_bundle is not None:111- self.verify = ca_bundle102+ # Default to `certifi` for certificiate verification.103+ self.load_verify_locations(cafile=certifi.where())104 113- if isinstance(self.verify, ssl.SSLContext):114- # Allow passing in our own SSLContext object that's pre-configured.115- context = self.verify116- self._load_client_certs(context)117- return context118- elif isinstance(self.verify, bool):119- ca_bundle_path = self.DEFAULT_CA_BUNDLE_PATH120- elif Path(self.verify).exists():121- ca_bundle_path = Path(self.verify)122- else:123- raise IOError(124- "Could not find a suitable TLS CA certificate bundle, "125- "invalid path: {}".format(self.verify)126- )105+ # 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 = keylogfile110 128- context = self._create_default_ssl_context()129- context.verify_mode = ssl.CERT_REQUIRED130- context.check_hostname = True111+ def __repr__(self) -> str:112+ class_name = self.__class__.__name__113+ return f"<{class_name}(verify={self._verify!r})>"114 132- # Signal to server support for PHA in TLS 1.3. Raises an133- # AttributeError if only read-only access is implemented.134- try:135- context.post_handshake_auth = True136- except AttributeError: # pragma: no cover137- pass115+ 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)122 139- # Disable using 'commonName' for SSLContext.check_hostname140- # when the 'subjectAltName' extension isn't available.141- try:142- context.hostname_checks_common_name = False143- except AttributeError: # pragma: no cover144- pass123 146- if ca_bundle_path.is_file():147- cafile = str(ca_bundle_path)148- logger.debug("load_verify_locations cafile=%r", cafile)149- context.load_verify_locations(cafile=cafile)150- elif ca_bundle_path.is_dir():151- capath = str(ca_bundle_path)152- logger.debug("load_verify_locations capath=%r", capath)153- context.load_verify_locations(capath=capath)154-155- self._load_client_certs(context)156-157- return context158-159- def _create_default_ssl_context(self) -> ssl.SSLContext:160- """161- Creates the default SSLContext object that's used for both verified162- and unverified connections.163- """164- context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)165- set_minimum_tls_version_1_2(context)166- context.options |= ssl.OP_NO_COMPRESSION167- context.set_ciphers(DEFAULT_CIPHERS)168-169- if ssl.HAS_ALPN:170- alpn_idents = ["http/1.1", "h2"] if self.http2 else ["http/1.1"]171- context.set_alpn_protocols(alpn_idents)172-173- keylogfile = os.environ.get("SSLKEYLOGFILE")174- if keylogfile and self.trust_env:175- context.keylog_filename = keylogfile176-177- return context178-179- def _load_client_certs(self, ssl_context: ssl.SSLContext) -> None:180- """181- Loads client certificates into our SSLContext object182- """183- if self.cert is not None:184- if isinstance(self.cert, str):185- ssl_context.load_cert_chain(certfile=self.cert)186- elif isinstance(self.cert, tuple) and len(self.cert) == 2:187- ssl_context.load_cert_chain(certfile=self.cert[0], keyfile=self.cert[1])188- elif isinstance(self.cert, tuple) and len(self.cert) == 3:189- ssl_context.load_cert_chain(190- certfile=self.cert[0],191- keyfile=self.cert[1],192- password=self.cert[2],193- )194-195-124 class Timeout:125 """126 Timeout configuration.127 173 unmodified linesmodified:httpx/_content.py+1 added-1 removed
199 unmodified lines200 # However for compat with requests, we *do* still support201 # `data=<bytes...>` usages. We deal with that case here, treating it202 # as if `content=<...>` had been supplied instead.203 message = "Use 'content=<...>' to upload raw bytes/text content."204- warnings.warn(message, DeprecationWarning)204+ warnings.warn(message, DeprecationWarning, stacklevel=2)205 return encode_content(data)206 207 if content is not None:208 return encode_content(content)30 unmodified linesmodified:httpx/_decoders.py+25 added-7 removed
9 unmodified lines10 import io11 import typing12 import zlib13 14-from ._compat import brotli, zstd14 from ._exceptions import DecodingError15 16+# Brotli support is optional17+try:18+ # The C bindings in `brotli` are recommended for CPython.19+ import brotli20+except ImportError: # pragma: no cover21+ try:22+ # The CFFI bindings in `brotlicffi` are recommended for PyPy23+ # and other environments.24+ import brotlicffi as brotli25+ except ImportError:26+ brotli = None27 28+29+# Zstandard support is optional30+try:31+ import zstandard32+except ImportError: # pragma: no cover33+ zstandard = None # type: ignore34+35+36 class ContentDecoder:37 def decode(self, data: bytes) -> bytes:38 raise NotImplementedError() # pragma: no cover39 127 unmodified lines167 """168 169 # inspired by the ZstdDecoder implementation in urllib3170 def __init__(self) -> None:153- if zstd is None: # pragma: no cover171+ if zstandard is None: # pragma: no cover172 raise ImportError(173 "Using 'ZStandardDecoder', ..."174 "Make sure to install httpx using `pip install httpx[zstd]`."175 ) from None176 159- self.decompressor = zstd.ZstdDecompressor().decompressobj()177+ self.decompressor = zstandard.ZstdDecompressor().decompressobj()178 179 def decode(self, data: bytes) -> bytes:162- assert zstd is not None180+ assert zstandard is not None181 output = io.BytesIO()182 try:183 output.write(self.decompressor.decompress(data))184 while self.decompressor.eof and self.decompressor.unused_data:185 unused_data = self.decompressor.unused_data168- self.decompressor = zstd.ZstdDecompressor().decompressobj()186+ self.decompressor = zstandard.ZstdDecompressor().decompressobj()187 output.write(self.decompressor.decompress(unused_data))170- except zstd.ZstdError as exc:188+ except zstandard.ZstdError as exc:189 raise DecodingError(str(exc)) from exc190 return output.getvalue()191 192 def flush(self) -> bytes:191 unmodified lines384 385 386 if brotli is None:387 SUPPORTED_DECODERS.pop("br") # pragma: no cover370-if zstd is None:388+if zstandard is None:389 SUPPORTED_DECODERS.pop("zstd") # pragma: no covermodified:httpx/_main.py+3 added-4 removed
14 unmodified lines15 import rich.syntax16 import rich.table17 18 from ._client import Client19+from ._config import SSLContext20 from ._exceptions import RequestError21 from ._models import Response22 from ._status_codes import codes23 449 unmodified lines473 """474 if not method:475 method = "POST" if content or data or files or json else "GET"476 477+ ssl_context = SSLContext(verify=verify)478 try:479 with Client(478- proxy=proxy,479- timeout=timeout,480- verify=verify,481- http2=http2,480+ proxy=proxy, timeout=timeout, http2=http2, ssl_context=ssl_context481 ) as client:482 with client.stream(483 method,484 url,24 unmodified linesmodified:httpx/_types.py-22 removed
1 """2 Type definitions for type checking purposes.3 """4 5-import ssl5 from http.cookiejar import CookieJar6 from typing import (7 IO,8 TYPE_CHECKING,6 unmodified lines15 Iterator,16 List,17 Mapping,18 MutableMapping,20- NamedTuple,19 Optional,20 Sequence,21 Tuple,22 Union,7 unmodified lines30 31 32 PrimitiveData = Optional[Union[str, int, float, bool]]33 36-RawURL = NamedTuple(37- "RawURL",38- [39- ("raw_scheme", bytes),40- ("raw_host", bytes),41- ("port", Optional[int]),42- ("raw_path", bytes),43- ],44-)45-34 URLTypes = Union["URL", str]35 36 QueryParamTypes = Union[37 "QueryParams",13 unmodified lines51 ]52 53 CookieTypes = Union["Cookies", CookieJar, Dict[str, str], List[Tuple[str, str]]]54 67-CertTypes = Union[68- # certfile69- str,70- # (certfile, keyfile)71- Tuple[str, Optional[str]],72- # (certfile, keyfile, password)73- Tuple[str, Optional[str], Optional[str]],74-]75-VerifyTypes = Union[str, bool, ssl.SSLContext]55 TimeoutTypes = Union[56 Optional[float],57 Tuple[Optional[float], Optional[float], Optional[float], Optional[float]],58 "Timeout",59 ]60 ProxyTypes = Union["URL", str, "Proxy"]82-ProxiesTypes = Union[ProxyTypes, Dict[Union["URL", str], Union[None, ProxyTypes]]]61 62 AuthTypes = Union[63 Tuple[Union[str, bytes], Union[str, bytes]],64 Callable[["Request"], "Request"],50 unmodified linesmodified:httpx/_urls.py+1 added-17 removed
3 unmodified lines4 from urllib.parse import parse_qs, unquote5 6 import idna7 8-from ._types import QueryParamTypes, RawURL8+from ._types import QueryParamTypes9 from ._urlparse import urlencode, urlparse10 from ._utils import primitive_value_to_str11 12 __all__ = ["URL", "QueryParams"]291 unmodified lines304 """305 return unquote(self._uri_reference.fragment or "")306 307 @property308- def raw(self) -> RawURL:309- """310- Provides the (scheme, host, port, target) for the outgoing request.311-312- In older versions of `httpx` this was used in the low-level transport API.313- We no longer use `RawURL`, and this property will be deprecated314- in a future release.315- """316- return RawURL(317- self.raw_scheme,318- self.raw_host,319- self.port,320- self.raw_path,321- )322-323- @property308 def is_absolute_url(self) -> bool:309 """310 Return `True` for absolute URLs such as 'http://example.com/path',311 and `False` for relative URLs such as '/path'.321 unmodified linesmodified:httpx/_utils.py-43 removed
4 unmodified lines5 import ipaddress6 import mimetypes7 import os8 import re9-import time9 import typing11-from pathlib import Path10 from urllib.request import getproxies11 14-import sniffio15-12 from ._types import PrimitiveData13 14 if typing.TYPE_CHECKING: # pragma: no cover15 from ._urls import URL72 unmodified lines88 value = _HTML5_FORM_ENCODING_RE.sub(replacer, value)89 return f'{name}="{value}"'.encode()90 91 96-def get_ca_bundle_from_env() -> str | None:97- if "SSL_CERT_FILE" in os.environ:98- ssl_file = Path(os.environ["SSL_CERT_FILE"])99- if ssl_file.is_file():100- return str(ssl_file)101- if "SSL_CERT_DIR" in os.environ:102- ssl_path = Path(os.environ["SSL_CERT_DIR"])103- if ssl_path.is_dir():104- return str(ssl_path)105- return None106-107-92 def parse_header_links(value: str) -> list[dict[str, str]]:93 """94 Returns a list of parsed link headers, for more info see:95 https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link177 unmodified lines273 274 return length275 276 293-class Timer:294- async def _get_time(self) -> float:295- library = sniffio.current_async_library()296- if library == "trio":297- import trio298-299- return trio.current_time()300- else:301- import asyncio302-303- return asyncio.get_event_loop().time()304-305- def sync_start(self) -> None:306- self.started = time.perf_counter()307-308- async def async_start(self) -> None:309- self.started = await self._get_time()310-311- def sync_elapsed(self) -> float:312- now = time.perf_counter()313- return now - self.started314-315- async def async_elapsed(self) -> float:316- now = await self._get_time()317- return now - self.started318-319-277 class URLPattern:278 """279 A utility class currently used for making lookups against proxy keys...280 119 unmodified linesmodified:tests/client/test_proxies.py+12 added-86 removed
11 unmodified lines12 u = httpx.URL(url)13 return httpcore.URL(scheme=u.raw_scheme, host=u.raw_host, port=u.port, target="/")14 15 16-@pytest.mark.parametrize(17- ["proxies", "expected_proxies"],18- [19- ("http://127.0.0.1", [("all://", "http://127.0.0.1")]),20- ({"all://": "http://127.0.0.1"}, [("all://", "http://127.0.0.1")]),21- (22- {"http://": "http://127.0.0.1", "https://": "https://127.0.0.1"},23- [("http://", "http://127.0.0.1"), ("https://", "https://127.0.0.1")],24- ),25- (httpx.Proxy("http://127.0.0.1"), [("all://", "http://127.0.0.1")]),26- (27- {28- "https://": httpx.Proxy("https://127.0.0.1"),29- "all://": "http://127.0.0.1",30- },31- [("all://", "http://127.0.0.1"), ("https://", "https://127.0.0.1")],32- ),33- ],34-)35-def test_proxies_parameter(proxies, expected_proxies):36- with pytest.warns(DeprecationWarning):37- client = httpx.Client(proxies=proxies)38- client_patterns = [p.pattern for p in client._mounts.keys()]39- client_proxies = list(client._mounts.values())40-41- for proxy_key, url in expected_proxies:42- assert proxy_key in client_patterns43- proxy = client_proxies[client_patterns.index(proxy_key)]44- assert isinstance(proxy, httpx.HTTPTransport)45- assert isinstance(proxy._pool, httpcore.HTTPProxy)46- assert proxy._pool._proxy_url == url_to_origin(url)47-48- assert len(expected_proxies) == len(client._mounts)49-50-51-def test_socks_proxy_deprecated():52- url = httpx.URL("http://www.example.com")53-54- with pytest.warns(DeprecationWarning):55- client = httpx.Client(proxies="socks5://localhost/")56- transport = client._transport_for_url(url)57- assert isinstance(transport, httpx.HTTPTransport)58- assert isinstance(transport._pool, httpcore.SOCKSProxy)59-60- with pytest.warns(DeprecationWarning):61- async_client = httpx.AsyncClient(proxies="socks5://localhost/")62- async_transport = async_client._transport_for_url(url)63- assert isinstance(async_transport, httpx.AsyncHTTPTransport)64- assert isinstance(async_transport._pool, httpcore.AsyncSOCKSProxy)65-66-16 def test_socks_proxy():17 url = httpx.URL("http://www.example.com")18 19 client = httpx.Client(proxy="socks5://localhost/")12 unmodified lines32 33 @pytest.mark.parametrize(34 ["url", "proxies", "expected"],35 [87- ("http://example.com", None, None),36 ("http://example.com", {}, None),37 ("http://example.com", {"https://": PROXY_URL}, None),38 ("http://example.com", {"http://example.net": PROXY_URL}, None),39 # Using "*" should match any domain name.11 unmodified lines51 ("http://wwwexample.com", {"http://*example.com": PROXY_URL}, None),52 # ...53 ("http://example.com:443", {"http://example.com": PROXY_URL}, PROXY_URL),54 ("http://example.com", {"all://": PROXY_URL}, PROXY_URL),107- ("http://example.com", {"all://": PROXY_URL, "http://example.com": None}, None),55 ("http://example.com", {"http://": PROXY_URL}, PROXY_URL),56 ("http://example.com", {"all://example.com": PROXY_URL}, PROXY_URL),57 ("http://example.com", {"http://example.com": PROXY_URL}, PROXY_URL),58 ("http://example.com", {"http://example.com:80": PROXY_URL}, PROXY_URL),25 unmodified lines84 ),85 ],86 )87 def test_transport_for_request(url, proxies, expected):141- if proxies:142- with pytest.warns(DeprecationWarning):143- client = httpx.Client(proxies=proxies)144- else:145- client = httpx.Client(proxies=proxies)88+ mounts = {key: httpx.HTTPTransport(proxy=value) for key, value in proxies.items()}89+ client = httpx.Client(mounts=mounts)90 91 transport = client._transport_for_url(httpx.URL(url))92 93 if expected is None:7 unmodified lines101 @pytest.mark.anyio102 @pytest.mark.network103 async def test_async_proxy_close():104 try:161- with pytest.warns(DeprecationWarning):162- client = httpx.AsyncClient(proxies={"https://": PROXY_URL})105+ transport = httpx.AsyncHTTPTransport(proxy=PROXY_URL)106+ client = httpx.AsyncClient(mounts={"https://": transport})107 await client.get("http://example.com")108 finally:109 await client.aclose()110 111 112 @pytest.mark.network113 def test_sync_proxy_close():114 try:171- with pytest.warns(DeprecationWarning):172- client = httpx.Client(proxies={"https://": PROXY_URL})115+ transport = httpx.HTTPTransport(proxy=PROXY_URL)116+ client = httpx.Client(mounts={"https://": transport})117 client.get("http://example.com")118 finally:119 client.close()120 121 178-def test_unsupported_proxy_scheme_deprecated():179- with pytest.warns(DeprecationWarning), pytest.raises(ValueError):180- httpx.Client(proxies="ftp://127.0.0.1")181-182-122 def test_unsupported_proxy_scheme():123 with pytest.raises(ValueError):124 httpx.Client(proxy="ftp://127.0.0.1")125 120 unmodified lines246 ({"all://": "http://127.0.0.1"}, True),247 ],248 )249 def test_for_deprecated_proxy_params(proxies, is_valid):311- with pytest.warns(DeprecationWarning):312- if not is_valid:313- with pytest.raises(ValueError):314- httpx.Client(proxies=proxies)315- else:316- httpx.Client(proxies=proxies)250+ mounts = {key: httpx.HTTPTransport(proxy=value) for key, value in proxies.items()}251 252+ if not is_valid:253+ with pytest.raises(ValueError):254+ httpx.Client(mounts=mounts)255+ else:256+ httpx.Client(mounts=mounts)257 319-def test_proxy_and_proxies_together():320- with pytest.warns(DeprecationWarning), pytest.raises(321- RuntimeError,322- ):323- httpx.Client(proxies={"all://": "http://127.0.0.1"}, proxy="http://127.0.0.1")258 325- with pytest.warns(DeprecationWarning), pytest.raises(326- RuntimeError,327- ):328- httpx.AsyncClient(329- proxies={"all://": "http://127.0.0.1"}, proxy="http://127.0.0.1"330- )331-332-259 def test_proxy_with_mounts():260 proxy_transport = httpx.HTTPTransport(proxy="http://127.0.0.1")261 client = httpx.Client(mounts={"http://": proxy_transport})262 2 unmodified linesmodified:tests/models/test_url.py-16 removed
863 unmodified lines864 865 assert url.host == "::ffff:192.168.0.1"866 assert url.netloc == b"[::ffff:192.168.0.1]:1234"867 assert str(url) == "http://[::ffff:192.168.0.1]:1234"868-869-870-# Test for deprecated API871-872-873-def test_url_raw_compatibility():874- """875- Test case for the (to-be-deprecated) `url.raw` accessor.876- """877- url = httpx.URL("https://www.example.com/path")878- scheme, host, port, raw_path = url.raw879-880- assert scheme == b"https"881- assert host == b"www.example.com"882- assert port is None883- assert raw_path == b"/path"modified:tests/conftest.py-20 removed
186 unmodified lines187 return trustme.CA()188 189 190 @pytest.fixture(scope="session")191-def ca_cert_pem_file(cert_authority):192- with cert_authority.cert_pem.tempfile() as tmp:193- yield tmp194-195-196-@pytest.fixture(scope="session")191 def localhost_cert(cert_authority):192 return cert_authority.issue_cert("localhost")193 194 89 unmodified lines284 def server() -> typing.Iterator[TestServer]:285 config = Config(app=app, lifespan="off", loop="asyncio")286 server = TestServer(config=config)287 yield from serve_in_thread(server)294-295-296-@pytest.fixture(scope="session")297-def https_server(cert_pem_file, cert_private_key_file):298- config = Config(299- app=app,300- lifespan="off",301- ssl_certfile=cert_pem_file,302- ssl_keyfile=cert_private_key_file,303- port=8001,304- loop="asyncio",305- )306- server = TestServer(config=config)307- yield from serve_in_thread(server)modified:tests/test_asgi.py-10 removed
220 unmodified lines221 async with httpx.AsyncClient(transport=transport) as client:222 response = await client.get("http://www.example.org/")223 224 assert response.status_code == 500225-226-227-@pytest.mark.anyio228-async def test_deprecated_shortcut():229- """230- The `app=...` shortcut is now deprecated.231- Use the explicit transport style instead.232- """233- with pytest.warns(DeprecationWarning):234- httpx.AsyncClient(app=hello_world)modified:tests/test_config.py+32 added-65 removed
1-import os1 import ssl2+import typing3 from pathlib import Path4 5 import certifi6 import pytest1 unmodified line8 import httpx9 10 11 def test_load_ssl_config():12- context = httpx.create_ssl_context()12+ context = httpx.SSLContext()13 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED14 assert context.check_hostname is True15 16 17-def test_load_ssl_config_verify_non_existing_path():17+def test_load_ssl_config_verify_non_existing_file():18 with pytest.raises(IOError):19- httpx.create_ssl_context(verify="/path/to/nowhere")19+ context = httpx.SSLContext()20+ context.load_verify_locations(cafile="/path/to/nowhere")21 22 22-def test_load_ssl_config_verify_existing_file():23- context = httpx.create_ssl_context(verify=certifi.where())24- assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED25- assert context.check_hostname is True23+def test_load_ssl_with_keylog(monkeypatch: typing.Any) -> None:24+ monkeypatch.setenv("SSLKEYLOGFILE", "test")25+ context = httpx.SSLContext()26+ assert context.keylog_filename == "test"27 28 28-@pytest.mark.parametrize("config", ("SSL_CERT_FILE", "SSL_CERT_DIR"))29-def test_load_ssl_config_verify_env_file(30- https_server, ca_cert_pem_file, config, cert_authority31-):32- os.environ[config] = (33- ca_cert_pem_file34- if config.endswith("_FILE")35- else str(Path(ca_cert_pem_file).parent)36- )37- context = httpx.create_ssl_context(trust_env=True)38- cert_authority.configure_trust(context)39-29+def test_load_ssl_config_verify_existing_file():30+ context = httpx.SSLContext()31+ context.load_verify_locations(capath=certifi.where())32 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED33 assert context.check_hostname is True42- assert len(context.get_ca_certs()) == 134 35 36 def test_load_ssl_config_verify_directory():46- path = Path(certifi.where()).parent47- context = httpx.create_ssl_context(verify=str(path))37+ context = httpx.SSLContext()38+ context.load_verify_locations(capath=Path(certifi.where()).parent)39 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED40 assert context.check_hostname is True41 42 43 def test_load_ssl_config_cert_and_key(cert_pem_file, cert_private_key_file):53- context = httpx.create_ssl_context(cert=(cert_pem_file, cert_private_key_file))44+ context = httpx.SSLContext()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 49 50 @pytest.mark.parametrize("password", [b"password", "password"])51 def test_load_ssl_config_cert_and_encrypted_key(52 cert_pem_file, cert_encrypted_private_key_file, password53 ):62- context = httpx.create_ssl_context(63- cert=(cert_pem_file, cert_encrypted_private_key_file, password)64- )54+ context = httpx.SSLContext()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 59 60 def test_load_ssl_config_cert_and_key_invalid_password(61 cert_pem_file, cert_encrypted_private_key_file62 ):63 with pytest.raises(ssl.SSLError):73- httpx.create_ssl_context(74- cert=(cert_pem_file, cert_encrypted_private_key_file, "password1")64+ context = httpx.SSLContext()65+ context.load_cert_chain(66+ cert_pem_file, cert_encrypted_private_key_file, "password1"67 )68 69 70 def test_load_ssl_config_cert_without_key_raises(cert_pem_file):71 with pytest.raises(ssl.SSLError):80- httpx.create_ssl_context(cert=cert_pem_file)72+ context = httpx.SSLContext()73+ context.load_cert_chain(cert_pem_file)74 75 76 def test_load_ssl_config_no_verify():84- context = httpx.create_ssl_context(verify=False)77+ context = httpx.SSLContext(verify=False)78 assert context.verify_mode == ssl.VerifyMode.CERT_NONE79 assert context.check_hostname is False80 81 89-def test_load_ssl_context():90- ssl_context = ssl.create_default_context()91- context = httpx.create_ssl_context(verify=ssl_context)82+def test_SSLContext_with_get_request(server, cert_pem_file):83+ context = httpx.SSLContext()84+ context.load_verify_locations(cert_pem_file)85+ response = httpx.get(server.url, ssl_context=context)86+ assert response.status_code == 20087 93- assert context is ssl_context88 89+def test_SSLContext_repr():90+ ssl_context = httpx.SSLContext()91 96-def test_create_ssl_context_with_get_request(server, cert_pem_file):97- context = httpx.create_ssl_context(verify=cert_pem_file)98- response = httpx.get(server.url, verify=context)99- assert response.status_code == 20092+ assert repr(ssl_context) == "<SSLContext(verify=True)>"93 94 95 def test_limits_repr():96 limits = httpx.Limits(max_connections=100)69 unmodified lines166 timeout = httpx.Timeout(None, read=5.0)167 assert repr(timeout) == "Timeout(connect=None, read=5.0, write=None, pool=None)"168 169 177-@pytest.mark.skipif(178- not hasattr(ssl.SSLContext, "keylog_filename"),179- reason="requires OpenSSL 1.1.1 or higher",180-)181-def test_ssl_config_support_for_keylog_file(tmpdir, monkeypatch): # pragma: no cover182- with monkeypatch.context() as m:183- m.delenv("SSLKEYLOGFILE", raising=False)184-185- context = httpx.create_ssl_context(trust_env=True)186-187- assert context.keylog_filename is None188-189- filename = str(tmpdir.join("test.log"))190-191- with monkeypatch.context() as m:192- m.setenv("SSLKEYLOGFILE", filename)193-194- context = httpx.create_ssl_context(trust_env=True)195-196- assert context.keylog_filename == filename197-198- context = httpx.create_ssl_context(trust_env=False)199-200- assert context.keylog_filename is None201-202-170 def test_proxy_from_url():171 proxy = httpx.Proxy("https://example.com")172 173 assert str(proxy.url) == "https://example.com"17 unmodified linesmodified:tests/test_utils.py-64 removed
1 unmodified line2 import logging3 import os4 import random5 6-import certifi6 import pytest7 8 import httpx9 from httpx._utils import (10 URLPattern,12- get_ca_bundle_from_env,11 get_environment_proxies,12 )13 16-from .common import TESTS_DIR14 18-15 @pytest.mark.parametrize(16 "encoding",17 (18 "utf-32",98 unmodified lines117 ),118 ]119 120 125-def test_logging_ssl(caplog):126- caplog.set_level(logging.DEBUG)127- with httpx.Client():128- pass129-130- cafile = certifi.where()131- assert caplog.record_tuples == [132- (133- "httpx",134- logging.DEBUG,135- "load_ssl_context verify=True cert=None trust_env=True http2=False",136- ),137- (138- "httpx",139- logging.DEBUG,140- f"load_verify_locations cafile='{cafile}'",141- ),142- ]143-144-145-def test_get_ssl_cert_file():146- # Two environments is not set.147- assert get_ca_bundle_from_env() is None148-149- os.environ["SSL_CERT_DIR"] = str(TESTS_DIR)150- # SSL_CERT_DIR is correctly set, SSL_CERT_FILE is not set.151- ca_bundle = get_ca_bundle_from_env()152- assert ca_bundle is not None and ca_bundle.endswith("tests")153-154- del os.environ["SSL_CERT_DIR"]155- os.environ["SSL_CERT_FILE"] = str(TESTS_DIR / "test_utils.py")156- # SSL_CERT_FILE is correctly set, SSL_CERT_DIR is not set.157- ca_bundle = get_ca_bundle_from_env()158- assert ca_bundle is not None and ca_bundle.endswith("tests/test_utils.py")159-160- os.environ["SSL_CERT_FILE"] = "wrongfile"161- # SSL_CERT_FILE is set with wrong file, SSL_CERT_DIR is not set.162- assert get_ca_bundle_from_env() is None163-164- del os.environ["SSL_CERT_FILE"]165- os.environ["SSL_CERT_DIR"] = "wrongpath"166- # SSL_CERT_DIR is set with wrong path, SSL_CERT_FILE is not set.167- assert get_ca_bundle_from_env() is None168-169- os.environ["SSL_CERT_DIR"] = str(TESTS_DIR)170- os.environ["SSL_CERT_FILE"] = str(TESTS_DIR / "test_utils.py")171- # Two environments is correctly set.172- ca_bundle = get_ca_bundle_from_env()173- assert ca_bundle is not None and ca_bundle.endswith("tests/test_utils.py")174-175- os.environ["SSL_CERT_FILE"] = "wrongfile"176- # Two environments is set but SSL_CERT_FILE is not a file.177- ca_bundle = get_ca_bundle_from_env()178- assert ca_bundle is not None and ca_bundle.endswith("tests")179-180- os.environ["SSL_CERT_DIR"] = "wrongpath"181- # Two environments is set but both are not correct.182- assert get_ca_bundle_from_env() is None183-184-121 @pytest.mark.parametrize(122 ["environment", "proxies"],123 [124 ({}, {}),128 unmodified linesmodified:tests/test_wsgi.py-9 removed
199 unmodified lines200 201 assert response.status_code == 200202 assert response.text == "success"203 assert server_protocol == "HTTP/1.1"204-205-206-def test_deprecated_shortcut():207- """208- The `app=...` shortcut is now deprecated.209- Use the explicit transport style instead.210- """211- with pytest.warns(DeprecationWarning):212- httpx.Client(app=application_factory([b"Hello, World!"]))modified:CHANGELOG.md+10 added
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.08+9+Version 0.28.0 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+17 ## 0.27.2 (27th August, 2024)18 19 ### Fixed20 1090 unmodified linesmodified:pyproject.toml+1 added-2 removed
30 unmodified lines31 "certifi",32 "httpcore==1.*",33 "anyio",34 "idna",35- "sniffio",35 ]36 dynamic = ["readme", "version"]37 38 [project.optional-dependencies]88 unmodified lines127 "network: marks tests which require network connection. Used in 3rd-party build environments that have network disabled."128 ]129 130 [tool.coverage.run]132-omit = ["venv/*", "httpx/_compat.py"]131+omit = ["venv/*"]132 include = ["httpx/*", "tests/*"]