Skip to content
Myr

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

29 files+527 added−941 removed

modified:.github/workflows/test-suite.yml+1 added-1 removed
modified:.github/CONTRIBUTING.md+3 added-2 removed
209 unmodified lines
210211```212import httpx213214proxies = {"all": "http://127.0.0.1:8080/"}214ssl_context = httpx.SSLContext()215ssl_context.load_verify_locations("/path/to/client.pem")216216with httpx.Client(proxies=proxies, verify="/path/to/client.pem") as client:217with 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 lines
modified:docs/advanced/ssl.md+147 added-48 removed
modified:docs/compatibility.md+1 added-3 removed
169 unmodified lines
170Also note that `requests.Session.request(...)` allows a `proxies=...` parameter, whereas `httpx.Client.request(...)` does not allow `mounts=...`.171172## SSL configuration173174When 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.174When using a `Client` instance, the ssl configurations should always be passed on client instantiation, rather than passed to the request method.175176If you need more than one different SSL configuration, you should use different client instances for each SSL configuration.177178Requests 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.179178## Request body on HTTP methods179180The 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 lines
modified:docs/environment_variables.md-60 removed
6 unmodified lines
7* Using the top-level API, such as `httpx.get("<url>", trust_env=False)`.89Here is a list of environment variables that HTTPX recognizes and what function they serve:1011## `SSLKEYLOGFILE`1213Valid values: a filename1415If 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.1617Support for `SSLKEYLOGFILE` requires Python 3.8 and OpenSSL 1.1.1 or newer.1819Example:2021```python22# test_script.py23import httpx2425with httpx.AsyncClient() as client:26 r = client.get("https://google.com")27```2829```console30SSLKEYLOGFILE=test.log python test_script.py31cat test.log32# TLS secrets log file, generated by OpenSSL / Python33SERVER_HANDSHAKE_TRAFFIC_SECRET XXXX34EXPORTER_SECRET XXXX35SERVER_TRAFFIC_SECRET_0 XXXX36CLIENT_HANDSHAKE_TRAFFIC_SECRET XXXX37CLIENT_TRAFFIC_SECRET_0 XXXX38SERVER_HANDSHAKE_TRAFFIC_SECRET XXXX39EXPORTER_SECRET XXXX40SERVER_TRAFFIC_SECRET_0 XXXX41CLIENT_HANDSHAKE_TRAFFIC_SECRET XXXX42CLIENT_TRAFFIC_SECRET_0 XXXX43```4445## `SSL_CERT_FILE`4647Valid values: a filename4849If this environment variable is set then HTTPX will load50CA certificate from the specified file instead of the default51location.5253Example:5455```console56SSL_CERT_FILE=/path/to/ca-certs/ca-bundle.crt python -c "import httpx; httpx.get('https://example.com')"57```5859## `SSL_CERT_DIR`6061Valid values: a directory following an [OpenSSL specific layout](https://www.openssl.org/docs/manmaster/man3/SSL_CTX_load_verify_locations.html).6263If 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.6465Example:6667```console68SSL_CERT_DIR=/path/to/ca-certs/ python -c "import httpx; httpx.get('https://example.com')"69```7011## Proxies1213The environment variables documented below are used as a convention by various HTTP tooling, including:14
39 unmodified lines
modified:docs/logging.md+19 added-19 removed
18 unmodified lines
1920Will send debug level output to the console, or wherever `stdout` is directed too...2122```23DEBUG [2023-03-16 14:36:20] httpx - load_ssl_context verify=True cert=None trust_env=True http2=False24DEBUG [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'25DEBUG [2023-03-16 14:36:20] httpcore - connection.connect_tcp.started host='www.example.com' port=443 local_address=None timeout=5.026DEBUG [2023-03-16 14:36:20] httpcore - connection.connect_tcp.complete return_value=<httpcore.backends.sync.SyncStream object at 0x1068fd270>27DEBUG [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.028DEBUG [2023-03-16 14:36:20] httpcore - connection.start_tls.complete return_value=<httpcore.backends.sync.SyncStream object at 0x1068fd240>29DEBUG [2023-03-16 14:36:20] httpcore - http11.send_request_headers.started request=<Request [b'GET']>30DEBUG [2023-03-16 14:36:20] httpcore - http11.send_request_headers.complete31DEBUG [2023-03-16 14:36:20] httpcore - http11.send_request_body.started request=<Request [b'GET']>32DEBUG [2023-03-16 14:36:20] httpcore - http11.send_request_body.complete33DEBUG [2023-03-16 14:36:20] httpcore - http11.receive_response_headers.started request=<Request [b'GET']>34DEBUG [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')])35INFO [2023-03-16 14:36:21] httpx - HTTP Request: GET https://www.example.com "HTTP/1.1 200 OK"36DEBUG [2023-03-16 14:36:21] httpcore - http11.receive_response_body.started request=<Request [b'GET']>37DEBUG [2023-03-16 14:36:21] httpcore - http11.receive_response_body.complete38DEBUG [2023-03-16 14:36:21] httpcore - http11.response_closed.started39DEBUG [2023-03-16 14:36:21] httpcore - http11.response_closed.complete40DEBUG [2023-03-16 14:36:21] httpcore - connection.close.started41DEBUG [2023-03-16 14:36:21] httpcore - connection.close.complete23DEBUG [2024-09-28 17:27:40] httpx - load_ssl_context verify=True cert=None24DEBUG [2024-09-28 17:27:40] httpx - load_verify_locations cafile='/Users/karenpetrosyan/oss/karhttpx/.venv/lib/python3.9/site-packages/certifi/cacert.pem'25DEBUG [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=None26DEBUG [2024-09-28 17:27:41] httpcore.connection - connect_tcp.complete return_value=<httpcore._backends.sync.SyncStream object at 0x101f1e8e0>27DEBUG [2024-09-28 17:27:41] httpcore.connection - start_tls.started ssl_context=SSLContext(verify=True) server_hostname='www.example.com' timeout=5.028DEBUG [2024-09-28 17:27:41] httpcore.connection - start_tls.complete return_value=<httpcore._backends.sync.SyncStream object at 0x1020f49a0>29DEBUG [2024-09-28 17:27:41] httpcore.http11 - send_request_headers.started request=<Request [b'GET']>30DEBUG [2024-09-28 17:27:41] httpcore.http11 - send_request_headers.complete31DEBUG [2024-09-28 17:27:41] httpcore.http11 - send_request_body.started request=<Request [b'GET']>32DEBUG [2024-09-28 17:27:41] httpcore.http11 - send_request_body.complete33DEBUG [2024-09-28 17:27:41] httpcore.http11 - receive_response_headers.started request=<Request [b'GET']>34DEBUG [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')])35INFO [2024-09-28 17:27:41] httpx - HTTP Request: GET https://www.example.com "HTTP/1.1 200 OK"36DEBUG [2024-09-28 17:27:41] httpcore.http11 - receive_response_body.started request=<Request [b'GET']>37DEBUG [2024-09-28 17:27:41] httpcore.http11 - receive_response_body.complete38DEBUG [2024-09-28 17:27:41] httpcore.http11 - response_closed.started39DEBUG [2024-09-28 17:27:41] httpcore.http11 - response_closed.complete40DEBUG [2024-09-28 17:27:41] httpcore.connection - close.started41DEBUG [2024-09-28 17:27:41] httpcore.connection - close.complete42```4344Logging output includes information from both the high-level `httpx` logger, and the network-level `httpcore` logger, which can be configured separately.45
38 unmodified lines
modified:httpx/_transports/asgi.py+19 added-6 removed
1from __future__ import annotations23import typing45import sniffio65from .._models import Request, Response6from .._types import AsyncByteStream7from .base import AsyncBaseTransport8
16 unmodified lines
2526__all__ = ["ASGITransport"]272829def is_running_trio() -> bool:30 try:31 # sniffio is a dependency of trio.3233 # See https://github.com/python-trio/trio/issues/280234 import sniffio3536 if sniffio.current_async_library() == "trio":37 return True38 except ImportError: # pragma: nocover39 pass4041 return False424344def create_event() -> Event:32 if sniffio.current_async_library() == "trio":45 if is_running_trio():46 import trio4748 return trio.Event()36 else:37 import asyncio4939 return asyncio.Event()50 import asyncio5152 return asyncio.Event()535455class ASGIResponseStream(AsyncByteStream):56 def __init__(self, body: list[bytes]) -> None:57 self._body = body58
129 unmodified lines
modified:httpx/_transports/default.py+21 added-10 removed
25 unmodified lines
2627from __future__ import annotations2829import contextlib30import ssl31import typing32from types import TracebackType3334import httpcore3535from .._config import DEFAULT_LIMITS, Limits, Proxy, create_ssl_context36from .._config import DEFAULT_LIMITS, Limits, Proxy, SSLContext, create_ssl_context37from .._exceptions import (38 ConnectError,39 ConnectTimeout,40 LocalProtocolError,
9 unmodified lines
50 WriteError,51 WriteTimeout,52)53from .._models import Request, Response53from .._types import AsyncByteStream, CertTypes, ProxyTypes, SyncByteStream, VerifyTypes54from .._types import AsyncByteStream, ProxyTypes, SyncByteStream55from .._urls import URL56from .base import AsyncBaseTransport, BaseTransport5758T = typing.TypeVar("T", bound="HTTPTransport")
65 unmodified lines
124125class 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()147148 if proxy is None:149 self._pool = httpcore.ConnectionPool(150 ssl_context=ssl_context,
119 unmodified lines
270271class 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()293294 if proxy is None:295 self._pool = httpcore.AsyncConnectionPool(296 ssl_context=ssl_context,
104 unmodified lines
modified:httpx/__init__.py+1 added
79 unmodified lines
80 "RequestError",81 "RequestNotRead",82 "Response",83 "ResponseNotRead",84 "SSLContext",85 "stream",86 "StreamClosed",87 "StreamConsumed",88 "StreamError",
18 unmodified lines
modified:httpx/__version__.py+1 added-1 removed
1__title__ = "httpx"2__description__ = "A next generation HTTP client, for Python 3."3__version__ = "0.27.2"3__version__ = "0.28.0"
modified:httpx/_api.py+66 added-66 removed
1from __future__ import annotations23import ssl4import typing5from contextlib import contextmanager67from ._client import Client8from ._config import DEFAULT_TIMEOUT_CONFIG9from ._models import Response10from ._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)21from ._urls import URL2223__all__ = [
21 unmodified lines
45 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 lines
78 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.8990 **Returns:** `Response`
9 unmodified lines
100 """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 lines
134 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 lines
155 """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 lines
184 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 lines
208 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 )219220221def options(
3 unmodified lines
225 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 lines
249 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 )260261262def head(
3 unmodified lines
266 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 lines
290 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 )301302303def post(
7 unmodified lines
311 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 lines
336 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 )347348349def put(
7 unmodified lines
357 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 lines
382 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 )393394395def patch(
7 unmodified lines
403 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 lines
428 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 )439440441def delete(
3 unmodified lines
445 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 lines
469 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 line
23import datetime4import enum5import logging6import ssl7import time8import typing9import warnings10from contextlib import asynccontextmanager, contextmanager11from types import TracebackType
16 unmodified lines
28 request_context,29)30from ._models import Cookies, Headers, Request, Response31from ._status_codes import codes30from ._transports.asgi import ASGITransport32from ._transports.base import AsyncBaseTransport, BaseTransport33from ._transports.default import AsyncHTTPTransport, HTTPTransport33from ._transports.wsgi import WSGITransport34from ._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)48from ._urls import URL, QueryParams49from ._utils import (53 Timer,50 URLPattern,51 get_environment_proxies,52 is_https_redirect,53 same_origin,
58 unmodified lines
112 ensures the `response.elapsed` is set once the response is closed.113 """114115 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 = start121122 def __iter__(self) -> typing.Iterator[bytes]:123 for chunk in self._stream:124 yield chunk125126 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()130131132class BoundAsyncStream(AsyncByteStream):
2 unmodified lines
135 ensures the `response.elapsed` is set once the response is closed.136 """137138 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 = start144145 async def __aiter__(self) -> typing.AsyncIterator[bytes]:146 async for chunk in self._stream:147 yield chunk148149 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()153154155EventHook = typing.Callable[..., typing.Any]
50 unmodified lines
206 return url207 return url.copy_with(raw_path=url.raw_path + b"/")208209 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}222223 @property224 def timeout(self) -> Timeout:
358 unmodified lines
583 * **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 proxy
6 unmodified lines
599 * **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-Type
6 unmodified lines
613 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 lines
654 "Using http2=True, but the 'h2' package is not installed. "655 "Make sure to install httpx using `pip install httpx[http2]`."656 ) from None657676 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)660685 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)691692 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)694661 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 lines
692 self._mounts = dict(sorted(self._mounts.items()))693694 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 transport708740 if app is not None:741 return WSGITransport(app=app)742709 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 )717718 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 )739740 def _transport_for_url(self, url: URL) -> BaseTransport:741 """
44 unmodified lines
786 "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)791792 request = self.build_request(793 method=method,794 url=url,
187 unmodified lines
982 """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()987988 if not isinstance(request.stream, SyncByteStream):989 raise RuntimeError(990 "Attempted to send an async request with a sync Client instance."
5 unmodified lines
996 assert isinstance(response.stream, SyncByteStream)997998 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 lines
1307 * **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 responses
1 unmodified line
1321 * **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-Type
6 unmodified lines
1335 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 lines
1376 "Using http2=True, but the 'h2' package is not installed. "1377 "Make sure to install httpx using `pip install httpx[http2]`."1378 ) from None13791423 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)13821432 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)14381439 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)14411383 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 )13931394 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 lines
1413 self._mounts = dict(sorted(self._mounts.items()))14141415 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 transport14281487 if app is not None:1488 return ASGITransport(app=app)14891429 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 )14371438 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 )14581459 def _transport_for_url(self, url: URL) -> AsyncBaseTransport:1460 """
45 unmodified lines
1506 "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)15111512 request = self.build_request(1513 method=method,1514 url=url,
188 unmodified lines
1703 """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()17081709 if not isinstance(request.stream, AsyncByteStream):1710 raise RuntimeError(1711 "Attempted to send an sync request with an AsyncClient instance."
4 unmodified lines
17161717 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 lines
deleted:httpx/_compat.py-63 removed
1"""2The _compat module is used for code which requires branching between different3Python environments. It is excluded from the code coverage checks.4"""56import re7import ssl8import sys9from types import ModuleType10from typing import Optional1112# 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.15try:16 import brotlicffi as brotli17except ImportError: # pragma: no cover18 try:19 import brotli20 except ImportError:21 brotli = None2223# Zstandard support is optional24zstd: Optional[ModuleType] = None25try:26 import zstandard as zstd27except (AttributeError, ImportError, ValueError): # Defensive:28 zstd = None29else: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 = None394041if sys.version_info >= (3, 10) or ssl.OPENSSL_VERSION_INFO >= (1, 1, 0, 7):4243 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_25152else:5354 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_1616263__all__ = ["brotli", "set_minimum_tls_version_1_2"]
modified:httpx/_config.py+84 added-156 removed
1from __future__ import annotations23import logging3import os4import ssl5import sys6import typing7from pathlib import Path7import warnings89import certifi1011from ._compat import set_minimum_tls_version_1_211from ._models import Headers13from ._types import CertTypes, HeaderTypes, TimeoutTypes, VerifyTypes12from ._types import HeaderTypes, TimeoutTypes13from ._urls import URL15from ._utils import get_ca_bundle_from_env1417__all__ = ["Limits", "Proxy", "Timeout", "create_ssl_context"]15__all__ = ["Limits", "Proxy", "SSLContext", "Timeout", "create_ssl_context"]1619DEFAULT_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)173839logger = logging.getLogger("httpx")404118class UnsetType:19 pass # pragma: no cover202122UNSET = UnsetType()232425def 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()6162 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)7160class SSLConfig:61 """62 SSL Configuration.63 """72 return ssl_context7365 DEFAULT_CA_BUNDLE_PATH = Path(certifi.where())7475class 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 = verify8581 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 return9290 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 = True9594 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_STRICT101104 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())104113 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 = keylogfile110128 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})>"114132 # 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)122139 # 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 pass123146 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)154155 self._load_client_certs(context)156157 return context158159 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)168169 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)172173 keylogfile = os.environ.get("SSLKEYLOGFILE")174 if keylogfile and self.trust_env:175 context.keylog_filename = keylogfile176177 return context178179 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 )194195124class Timeout:125 """126 Timeout configuration.127
173 unmodified lines
modified:httpx/_content.py+1 added-1 removed
199 unmodified lines
200 # 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)206207 if content is not None:208 return encode_content(content)
30 unmodified lines
modified:httpx/_decoders.py+25 added-7 removed
9 unmodified lines
10import io11import typing12import zlib1314from ._compat import brotli, zstd14from ._exceptions import DecodingError1516# Brotli support is optional17try:18 # The C bindings in `brotli` are recommended for CPython.19 import brotli20except 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 = None272829# Zstandard support is optional30try:31 import zstandard32except ImportError: # pragma: no cover33 zstandard = None # type: ignore343536class ContentDecoder:37 def decode(self, data: bytes) -> bytes:38 raise NotImplementedError() # pragma: no cover39
127 unmodified lines
167 """168169 # 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 None176159 self.decompressor = zstd.ZstdDecompressor().decompressobj()177 self.decompressor = zstandard.ZstdDecompressor().decompressobj()178179 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()191192 def flush(self) -> bytes:
191 unmodified lines
384385386if brotli is None:387 SUPPORTED_DECODERS.pop("br") # pragma: no cover370if zstd is None:388if zstandard is None:389 SUPPORTED_DECODERS.pop("zstd") # pragma: no cover
modified:httpx/_main.py+3 added-4 removed
14 unmodified lines
15import rich.syntax16import rich.table1718from ._client import Client19from ._config import SSLContext20from ._exceptions import RequestError21from ._models import Response22from ._status_codes import codes23
449 unmodified lines
473 """474 if not method:475 method = "POST" if content or data or files or json else "GET"476477 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 lines
modified:httpx/_types.py-22 removed
1"""2Type definitions for type checking purposes.3"""45import ssl5from http.cookiejar import CookieJar6from typing import (7 IO,8 TYPE_CHECKING,
6 unmodified lines
15 Iterator,16 List,17 Mapping,18 MutableMapping,20 NamedTuple,19 Optional,20 Sequence,21 Tuple,22 Union,
7 unmodified lines
303132PrimitiveData = Optional[Union[str, int, float, bool]]3336RawURL = NamedTuple(37 "RawURL",38 [39 ("raw_scheme", bytes),40 ("raw_host", bytes),41 ("port", Optional[int]),42 ("raw_path", bytes),43 ],44)4534URLTypes = Union["URL", str]3536QueryParamTypes = Union[37 "QueryParams",
13 unmodified lines
51]5253CookieTypes = Union["Cookies", CookieJar, Dict[str, str], List[Tuple[str, str]]]5467CertTypes = Union[68 # certfile69 str,70 # (certfile, keyfile)71 Tuple[str, Optional[str]],72 # (certfile, keyfile, password)73 Tuple[str, Optional[str], Optional[str]],74]75VerifyTypes = Union[str, bool, ssl.SSLContext]55TimeoutTypes = Union[56 Optional[float],57 Tuple[Optional[float], Optional[float], Optional[float], Optional[float]],58 "Timeout",59]60ProxyTypes = Union["URL", str, "Proxy"]82ProxiesTypes = Union[ProxyTypes, Dict[Union["URL", str], Union[None, ProxyTypes]]]6162AuthTypes = Union[63 Tuple[Union[str, bytes], Union[str, bytes]],64 Callable[["Request"], "Request"],
50 unmodified lines
modified:httpx/_urls.py+1 added-17 removed
3 unmodified lines
4from urllib.parse import parse_qs, unquote56import idna78from ._types import QueryParamTypes, RawURL8from ._types import QueryParamTypes9from ._urlparse import urlencode, urlparse10from ._utils import primitive_value_to_str1112__all__ = ["URL", "QueryParams"]
291 unmodified lines
304 """305 return unquote(self._uri_reference.fragment or "")306307 @property308 def raw(self) -> RawURL:309 """310 Provides the (scheme, host, port, target) for the outgoing request.311312 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 )322323 @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 lines
modified:httpx/_utils.py-43 removed
4 unmodified lines
5import ipaddress6import mimetypes7import os8import re9import time9import typing11from pathlib import Path10from urllib.request import getproxies1114import sniffio1512from ._types import PrimitiveData1314if typing.TYPE_CHECKING: # pragma: no cover15 from ._urls import URL
72 unmodified lines
88 value = _HTML5_FORM_ENCODING_RE.sub(replacer, value)89 return f'{name}="{value}"'.encode()909196def 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 None10610792def 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/Link
177 unmodified lines
273274 return length275276293class Timer:294 async def _get_time(self) -> float:295 library = sniffio.current_async_library()296 if library == "trio":297 import trio298299 return trio.current_time()300 else:301 import asyncio302303 return asyncio.get_event_loop().time()304305 def sync_start(self) -> None:306 self.started = time.perf_counter()307308 async def async_start(self) -> None:309 self.started = await self._get_time()310311 def sync_elapsed(self) -> float:312 now = time.perf_counter()313 return now - self.started314315 async def async_elapsed(self) -> float:316 now = await self._get_time()317 return now - self.started318319277class URLPattern:278 """279 A utility class currently used for making lookups against proxy keys...280
119 unmodified lines
modified:tests/client/test_proxies.py+12 added-86 removed
11 unmodified lines
12 u = httpx.URL(url)13 return httpcore.URL(scheme=u.raw_scheme, host=u.raw_host, port=u.port, target="/")141516@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)35def 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())4041 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)4748 assert len(expected_proxies) == len(client._mounts)495051def test_socks_proxy_deprecated():52 url = httpx.URL("http://www.example.com")5354 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)5960 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)656616def test_socks_proxy():17 url = httpx.URL("http://www.example.com")1819 client = httpx.Client(proxy="socks5://localhost/")
12 unmodified lines
3233@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 lines
51 ("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 lines
84 ),85 ],86)87def 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)9091 transport = client._transport_for_url(httpx.URL(url))9293 if expected is None:
7 unmodified lines
101@pytest.mark.anyio102@pytest.mark.network103async 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()110111112@pytest.mark.network113def 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()120121178def test_unsupported_proxy_scheme_deprecated():179 with pytest.warns(DeprecationWarning), pytest.raises(ValueError):180 httpx.Client(proxies="ftp://127.0.0.1")181182122def test_unsupported_proxy_scheme():123 with pytest.raises(ValueError):124 httpx.Client(proxy="ftp://127.0.0.1")125
120 unmodified lines
246 ({"all://": "http://127.0.0.1"}, True),247 ],248)249def 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()}251252 if not is_valid:253 with pytest.raises(ValueError):254 httpx.Client(mounts=mounts)255 else:256 httpx.Client(mounts=mounts)257319def 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")258325 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 )331332259def 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 lines
modified:tests/models/test_url.py-16 removed
863 unmodified lines
864865 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"868869870# Test for deprecated API871872873def 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.raw879880 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 lines
187 return trustme.CA()188189190@pytest.fixture(scope="session")191def ca_cert_pem_file(cert_authority):192 with cert_authority.cert_pem.tempfile() as tmp:193 yield tmp194195196@pytest.fixture(scope="session")191def localhost_cert(cert_authority):192 return cert_authority.issue_cert("localhost")193194
89 unmodified lines
284def 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)294295296@pytest.fixture(scope="session")297def 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 lines
221 async with httpx.AsyncClient(transport=transport) as client:222 response = await client.get("http://www.example.org/")223224 assert response.status_code == 500225226227@pytest.mark.anyio228async 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
1import os1import ssl2import typing3from pathlib import Path45import certifi6import pytest
1 unmodified line
8import httpx91011def 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 True151617def test_load_ssl_config_verify_non_existing_path():17def 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")212222def 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 True23def test_load_ssl_with_keylog(monkeypatch: typing.Any) -> None:24 monkeypatch.setenv("SSLKEYLOGFILE", "test")25 context = httpx.SSLContext()26 assert context.keylog_filename == "test"272828@pytest.mark.parametrize("config", ("SSL_CERT_FILE", "SSL_CERT_DIR"))29def 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)3929def 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()) == 1343536def 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 True414243def 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 True484950@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):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 True585960def 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 )686970def 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)747576def 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 False808189def test_load_ssl_context():90 ssl_context = ssl.create_default_context()91 context = httpx.create_ssl_context(verify=ssl_context)82def 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 == 2008793 assert context is ssl_context8889def test_SSLContext_repr():90 ssl_context = httpx.SSLContext()9196def 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)>"939495def test_limits_repr():96 limits = httpx.Limits(max_connections=100)
69 unmodified lines
166 timeout = httpx.Timeout(None, read=5.0)167 assert repr(timeout) == "Timeout(connect=None, read=5.0, write=None, pool=None)"168169177@pytest.mark.skipif(178 not hasattr(ssl.SSLContext, "keylog_filename"),179 reason="requires OpenSSL 1.1.1 or higher",180)181def test_ssl_config_support_for_keylog_file(tmpdir, monkeypatch): # pragma: no cover182 with monkeypatch.context() as m:183 m.delenv("SSLKEYLOGFILE", raising=False)184185 context = httpx.create_ssl_context(trust_env=True)186187 assert context.keylog_filename is None188189 filename = str(tmpdir.join("test.log"))190191 with monkeypatch.context() as m:192 m.setenv("SSLKEYLOGFILE", filename)193194 context = httpx.create_ssl_context(trust_env=True)195196 assert context.keylog_filename == filename197198 context = httpx.create_ssl_context(trust_env=False)199200 assert context.keylog_filename is None201202170def test_proxy_from_url():171 proxy = httpx.Proxy("https://example.com")172173 assert str(proxy.url) == "https://example.com"
17 unmodified lines
modified:tests/test_utils.py-64 removed
1 unmodified line
2import logging3import os4import random56import certifi6import pytest78import httpx9from httpx._utils import (10 URLPattern,12 get_ca_bundle_from_env,11 get_environment_proxies,12)1316from .common import TESTS_DIR141815@pytest.mark.parametrize(16 "encoding",17 (18 "utf-32",
98 unmodified lines
117 ),118 ]119120125def test_logging_ssl(caplog):126 caplog.set_level(logging.DEBUG)127 with httpx.Client():128 pass129130 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 ]143144145def test_get_ssl_cert_file():146 # Two environments is not set.147 assert get_ca_bundle_from_env() is None148149 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")153154 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")159160 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 None163164 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 None168169 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")174175 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")179180 os.environ["SSL_CERT_DIR"] = "wrongpath"181 # Two environments is set but both are not correct.182 assert get_ca_bundle_from_env() is None183184121@pytest.mark.parametrize(122 ["environment", "proxies"],123 [124 ({}, {}),
128 unmodified lines
modified:tests/test_wsgi.py-9 removed
199 unmodified lines
200201 assert response.status_code == 200202 assert response.text == "success"203 assert server_protocol == "HTTP/1.1"204205206def 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 lines
3All notable changes to this project will be documented in this file.45The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).67## Version 0.28.089Version 0.28.0 introduces an `httpx.SSLContext()` class and `ssl_context` parameter.1011* Added `httpx.SSLContext` class and `ssl_context` parameter. (#3022, #3335)12* The `verify` and `cert` arguments have been deprecated and will now raise warnings. (#3022, #3335)13* The deprecated `proxies` argument has now been removed.14* The deprecated `app` argument has now been removed.15* The `URL.raw` property has now been removed.1617## 0.27.2 (27th August, 2024)1819### Fixed20
1090 unmodified lines
modified:pyproject.toml+1 added-2 removed
30 unmodified lines
31 "certifi",32 "httpcore==1.*",33 "anyio",34 "idna",35 "sniffio",35]36dynamic = ["readme", "version"]3738[project.optional-dependencies]
88 unmodified lines
127 "network: marks tests which require network connection. Used in 3rd-party build environments that have network disabled."128]129130[tool.coverage.run]132omit = ["venv/*", "httpx/_compat.py"]131omit = ["venv/*"]132include = ["httpx/*", "tests/*"]