Compare commits

..

32 Commits

Author SHA1 Message Date
Ben Beasley
b5addb64f0
Adapt test_response_decode_text_using_autodetect for chardet 6.0 (#3773) 2026-02-23 10:40:42 +00:00
Josh Cannon
ae1b9f6623
Expose FunctionAuth in __all__ (#3699)
Co-authored-by: Kar Petrosyan <92274156+karpetrosyan@users.noreply.github.com>
Co-authored-by: Kar Petrosyan <kar.petrosyanpy@gmail.com>
2025-12-10 18:58:48 +04:00
Riccardo Magliocchetti
ca097c96f9
docs/ssl: fix typo (#3703) 2025-12-10 18:47:31 +04:00
ZProger
def4778d62
Fixed a syntax error in the file upload example (#3692) 2025-10-16 10:04:38 +01:00
dependabot[bot]
435e1dac89
Bump actions/setup-python from 5 to 6 (#3677)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-10-04 18:38:23 +01:00
Kim Christie
4b23574cf8
Update dependencies (#3665) 2025-09-16 14:23:31 +01:00
Tobias Fischer
652f051fea
Documentation for SSL_CERT_FILE and SSL_CERT_DIR (#3579)
Co-authored-by: Kim Christie <tom@tomchristie.com>
2025-09-11 11:59:20 +01:00
nikkie
3fee27838e
[docs] Remove load_ssl_context & load_verify_locations DEBUG log (#3589)
Co-authored-by: Kim Christie <tom@tomchristie.com>
2025-09-05 15:30:31 +01:00
Glen Keane
bc00d2bd9f
Update compatibility.md with documentation of exceptions differences (#3649)
Co-authored-by: Kim Christie <tom@tomchristie.com>
2025-09-05 15:19:37 +01:00
dependabot[bot]
767cf6baa6
Bump the python-packages group across 1 directory with 10 updates (#3658)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-09-04 15:29:43 +01:00
Christian Clauss
b55d463570
Upgrade Python type checker mypy (#3654) 2025-09-04 08:48:49 -05:00
Kamil Monicz
15e9759e65
Add httpx-secure to third party packages (#3629)
Co-authored-by: Kim Christie <tom@tomchristie.com>
2025-09-04 09:52:37 +01:00
Christian Clauss
364697efca
Upgrade Python formatter ruff (#3651) 2025-09-03 06:17:26 -05:00
Chai Landau
89102021fc
chore: update sponsorship graphic (#3620) 2025-08-07 08:52:25 -05:00
Alex Grönholm
4fb9528c2f
Drop Python 3.8 support (#3592) 2025-06-27 12:45:12 +02:00
Emmanuel Ferdman
336204f012
Display proxy protocol scheme on error (#3571) 2025-06-02 20:29:52 +01:00
Will Ockmore
6c7af96773
Add httpx-retries to third party packages docs (#3552) 2025-05-02 12:24:26 +01:00
mv-python
9e8ab40369
Docs: Add httpx.Proxy to api.md (#3512) 2025-03-05 12:52:58 +00:00
T-256
ce7a6e91fb
Add httpdbg to third party packages. (#3327)
Co-authored-by: Kar Petrosyan <92274156+karpetrosyan@users.noreply.github.com>
2025-02-27 21:43:26 +04:00
Kar Petrosyan
4189b7f051
fix typo (#3519) 2025-02-27 20:38:39 +04:00
Tom Christie
e70d0b08c9
Sharper CHANGELOG entry. (#3448) 2025-02-14 14:52:54 +00:00
dependabot[bot]
b395e6626b
Bump cryptography from 44.0.0 to 44.0.1 (#3499) 2025-02-12 11:25:05 +00:00
Bazyli Cyran
10b7295922
docs: Use with to open files in multipart examples (#3478) 2025-01-17 10:56:46 +00:00
Hugo van Kemenade
c7c13f18a5
Add support for Python 3.13 (#3460) 2024-12-23 15:50:57 -06:00
Tom Christie
26d48e0634
Version 0.28.1 (#3445) 2024-12-06 15:35:41 +00:00
Tom Christie
89599a9541
Fix verify=False, cert=... case. (#3442) 2024-12-04 11:29:09 +00:00
Elaina
8ecb86f0d7
Add test for request params behavior changes (#3364) (#3440)
Co-authored-by: Tom Christie <tom@tomchristie.com>
2024-12-03 16:12:27 +00:00
dependabot[bot]
0cb7e5a2e7
Bump the python-packages group with 11 updates (#3434)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Marcelo Trylesinski <marcelotryle@gmail.com>
2024-12-03 08:37:45 +01:00
Daniel Arvelini
15e21e9ea3
Updating deprecated docstring Client() class (#3426) 2024-11-29 11:15:56 +00:00
Tom Christie
80960fa319
Version 0.28.0. (#3419) 2024-11-28 14:50:04 +00:00
Tom Christie
a33c87852b
Fix extensions type annotation. (#3380) 2024-11-28 13:31:17 +00:00
Tom Christie
ce7e14da27
Error on verify as str. (#3418) 2024-11-28 11:46:59 +00:00
35 changed files with 378 additions and 192 deletions

View File

@ -15,9 +15,9 @@ jobs:
steps:
- uses: "actions/checkout@v4"
- uses: "actions/setup-python@v5"
- uses: "actions/setup-python@v6"
with:
python-version: 3.8
python-version: 3.9
- name: "Install dependencies"
run: "scripts/install"
- name: "Build package & docs"

View File

@ -14,11 +14,11 @@ jobs:
strategy:
matrix:
python-version: ["3.10", "3.11", "3.12", "3.13"]
python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"]
steps:
- uses: "actions/checkout@v4"
- uses: "actions/setup-python@v5"
- uses: "actions/setup-python@v6"
with:
python-version: "${{ matrix.python-version }}"
allow-prereleases: true

View File

@ -4,34 +4,47 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## 0.28.0 (...)
## [UNRELEASED]
TODO... writeup `truststore` switch & 3.10+ requirement.
### Removed
The 0.28 release includes a limited set of backwards incompatible changes.
* Drop support for Python 3.8
**Backwards incompatible changes**:
### Added
SSL configuration has been significantly simplified.
* Expose `FunctionAuth` from the public API. (#3699)
* The `verify` argument no longer accepts string arguments. Explicitly specified certificate stores can still be enabled through the SSL configuration API.
* The `cert` argument has now been removed. Client side certificates can still be enabled through the SSL configuration API.
* The `SSL_CERT_FILE` and `SSL_CERT_DIR` environment variables are no longer used. These environment variables can be enabled manually although should be obsoleted by our switch to `truststore`.
## 0.28.1 (6th December, 2024)
For users of the standard `verify=True` or `verify=False` cases this should require no changes.
* Fix SSL case where `verify=False` together with client side certificates.
## 0.28.0 (28th November, 2024)
For information on configuring more complex SSL cases, please see the [SSL documentation](docs/advanced/ssl.md).
Be aware that the default *JSON request bodies now use a more compact representation*. This is generally considered a prefered style, tho may require updates to test suites.
The 0.28 release includes a limited set of deprecations...
**Deprecations**:
We are working towards a simplified SSL configuration API.
*For users of the standard `verify=True` or `verify=False` cases, or `verify=<ssl_context>` case this should require no changes. The following cases have been deprecated...*
* The `verify` argument as a string argument is now deprecated and will raise warnings.
* The `cert` argument is now deprecated and will raise warnings.
Our revised [SSL documentation](docs/advanced/ssl.md) covers how to implement the same behaviour with a more constrained API.
**The following changes are also included**:
* The undocumented `URL.raw` property has now been deprecated, and will raise warnings.
* The deprecated `proxies` argument has now been removed.
* The deprecated `app` argument has now been removed.
* Ensure JSON request bodies are compact. (#3363)
* JSON request bodies use a compact representation. (#3363)
* Review URL percent escape sets, based on WHATWG spec. (#3371, #3373)
* Ensure `certifi` and `httpcore` are only imported if required. (#3377)
* Treat `socks5h` as a valid proxy scheme. (#3178)
* Cleanup `Request()` method signature in line with `client.request()` and `httpx.request()`. (#3378)
* Bugfix: When passing `params={}`, always strictly update rather than merge with an existing querystring. (#3364)
## 0.27.2 (27th August, 2024)

View File

@ -101,7 +101,7 @@ Or, to include the optional HTTP/2 support, use:
$ pip install httpx[http2]
```
HTTPX requires Python 3.10+.
HTTPX requires Python 3.9+.
## Documentation
@ -125,7 +125,7 @@ The HTTPX project relies on these excellent libraries:
* `httpcore` - The underlying transport implementation for `httpx`.
* `h11` - HTTP/1.1 support.
* `truststore` - System SSL certificates.
* `certifi` - SSL certificates.
* `idna` - Internationalized domain name support.
* `sniffio` - Async library autodetection.

View File

@ -270,8 +270,9 @@ multipart file encoding is available by passing a dictionary with the
name of the payloads as keys and either tuple of elements or a file-like object or a string as values.
```pycon
>>> files = {'upload-file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel')}
>>> r = httpx.post("https://httpbin.org/post", files=files)
>>> with open('report.xls', 'rb') as report_file:
... files = {'upload-file': ('report.xls', report_file, 'application/vnd.ms-excel')}
... r = httpx.post("https://httpbin.org/post", files=files)
>>> print(r.text)
{
...
@ -318,7 +319,10 @@ To do that, pass a list of `(field, <file>)` items instead of a dictionary, allo
For instance this request sends 2 files, `foo.png` and `bar.png` in one request on the `images` form field:
```pycon
>>> files = [('images', ('foo.png', open('foo.png', 'rb'), 'image/png')),
('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))]
>>> r = httpx.post("https://httpbin.org/post", files=files)
>>> with open('foo.png', 'rb') as foo_file, open('bar.png', 'rb') as bar_file:
... files = [
... ('images', ('foo.png', foo_file, 'image/png')),
... ('images', ('bar.png', bar_file, 'image/png')),
... ]
... r = httpx.post("https://httpbin.org/post", files=files)
```

View File

@ -1,28 +1,26 @@
When making a request over HTTPS we need to verify the identity of the requested host. We rely on the [`truststore`](https://truststore.readthedocs.io/en/latest/) package to load the system certificates, ensuring that `httpx` has the same behaviour on SSL sites as your browser.
When 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).
### SSL verification
### Enabling and disabling verification
By default httpx will verify HTTPS connections, and raise an error for invalid SSL cases...
```python
```pycon
>>> httpx.get("https://expired.badssl.com/")
httpx.ConnectError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:997)
```
If you're confident that you want to visit a site with an invalid certificate you can disable SSL verification completely...
You can disable SSL verification completely and allow insecure requests...
```python
```pycon
>>> httpx.get("https://expired.badssl.com/", verify=False)
<Response [200 OK]>
```
### Custom SSL configurations
### Configuring client instances
If you're using a `Client()` instance you can pass the `verify=<...>` configuration when instantiating the client.
If you're using a `Client()` instance you should pass any `verify=<...>` configuration when instantiating the client.
```python
>>> client = httpx.Client(verify=True)
```
By default the [certifi CA bundle](https://certifiio.readthedocs.io/en/latest/) is used for SSL verification.
For more complex configurations you can pass an [SSL Context](https://docs.python.org/3/library/ssl.html) instance...
@ -30,13 +28,35 @@ For more complex configurations you can pass an [SSL Context](https://docs.pytho
import certifi
import httpx
import ssl
import certifi
# Use certifi for certificate validation, rather than the system truststore.
# This SSL context is equivalent to the default `verify=True`.
ctx = ssl.create_default_context(cafile=certifi.where())
client = httpx.Client(verify=ctx)
```
Using [the `truststore` package](https://truststore.readthedocs.io/) to support system certificate stores...
```python
import ssl
import truststore
import httpx
# Use system certificate stores.
ctx = truststore.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
client = httpx.Client(verify=ctx)
```
Loding an alternative certificate verification store using [the standard SSL context API](https://docs.python.org/3/library/ssl.html)...
```python
import httpx
import ssl
# Use an explicitly configured certificate store.
ctx = ssl.create_default_context(cafile="path/to/certs.pem") # Either cafile or capath.
client = httpx.Client(verify=ctx)
```
### Client side certificates
Client side certificates allow a remote server to verify the client. They tend to be used within private organizations to authenticate requests to remote servers.
@ -51,23 +71,11 @@ client = httpx.Client(verify=ctx)
### 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).
These environment variables shouldn't be necessary since they're obsoleted by `truststore`. They can be enabled if required like so...
```python
# Use `SSL_CERT_FILE` or `SSL_CERT_DIR` if configured.
# Otherwise default to certifi.
ctx = ssl.create_default_context(
cafile=os.environ.get("SSL_CERT_FILE", certifi.where()),
capath=os.environ.get("SSL_CERT_DIR"),
)
client = httpx.Client(verify=ctx)
```
`httpx` does respect the `SSL_CERT_FILE` and `SSL_CERT_DIR` environment variables by default. For details, refer to [the section on the environment variables page](../environment_variables.md#ssl_cert_file).
### 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.
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...

View File

@ -159,3 +159,18 @@ what gets sent over the wire.*
* `def delete(name, [domain], [path])`
* `def clear([domain], [path])`
* *Standard mutable mapping interface*
## `Proxy`
*A configuration of the proxy server.*
```pycon
>>> proxy = Proxy("http://proxy.example.com:8030")
>>> client = Client(proxy=proxy)
```
* `def __init__(url, [ssl_context], [auth], [headers])`
* `.url` - **URL**
* `.auth` - **tuple[str, str]**
* `.headers` - **Headers**
* `.ssl_context` - **SSLContext**

View File

@ -23,7 +23,7 @@ To make asynchronous requests, you'll need an `AsyncClient`.
```
!!! tip
Use [IPython](https://ipython.readthedocs.io/en/stable/) or Python 3.8+ with `python -m asyncio` to try this code interactively, as they support executing `async`/`await` expressions in the console.
Use [IPython](https://ipython.readthedocs.io/en/stable/) or Python 3.9+ with `python -m asyncio` to try this code interactively, as they support executing `async`/`await` expressions in the console.
## API Differences

View File

@ -226,3 +226,7 @@ For both query params (`params=`) and form data (`data=`), `requests` supports s
In HTTPX, event hooks may access properties of requests and responses, but event hook callbacks cannot mutate the original request/response.
If you are looking for more control, consider checking out [Custom Transports](advanced/transports.md#custom-transports).
## Exceptions and Errors
`requests` exception hierarchy is slightly different to the `httpx` exception hierarchy. `requests` exposes a top level `RequestException`, where as `httpx` exposes a top level `HTTPError`. see the exceptions exposes in requests [here](https://requests.readthedocs.io/en/latest/_modules/requests/exceptions/). See the `httpx` error hierarchy [here](https://www.python-httpx.org/exceptions/).

View File

@ -51,3 +51,29 @@ python -c "import httpx; httpx.get('http://example.com')"
python -c "import httpx; httpx.get('http://127.0.0.1:5000/my-api')"
python -c "import httpx; httpx.get('https://www.python-httpx.org')"
```
## `SSL_CERT_FILE`
Valid values: a filename
If this environment variable is set then HTTPX will load
CA certificate from the specified file instead of the default
location.
Example:
```console
SSL_CERT_FILE=/path/to/ca-certs/ca-bundle.crt python -c "import httpx; httpx.get('https://example.com')"
```
## `SSL_CERT_DIR`
Valid values: a directory following an [OpenSSL specific layout](https://www.openssl.org/docs/manmaster/man3/SSL_CTX_load_verify_locations.html).
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.
Example:
```console
SSL_CERT_DIR=/path/to/ca-certs/ python -c "import httpx; httpx.get('https://example.com')"
```

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 MiB

After

Width:  |  Height:  |  Size: 113 KiB

View File

@ -145,6 +145,6 @@ To include the optional brotli and zstandard decoders support, use:
$ pip install httpx[brotli,zstd]
```
HTTPX requires Python 3.8+
HTTPX requires Python 3.9+
[sync-support]: https://github.com/encode/httpx/issues/572

View File

@ -20,8 +20,6 @@ httpx.get("https://www.example.com")
Will send debug level output to the console, or wherever `stdout` is directed too...
```
DEBUG [2024-09-28 17:27:40] httpx - load_ssl_context verify=True cert=None
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'
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=None
DEBUG [2024-09-28 17:27:41] httpcore.connection - connect_tcp.complete return_value=<httpcore._backends.sync.SyncStream object at 0x101f1e8e0>
DEBUG [2024-09-28 17:27:41] httpcore.connection - start_tls.started ssl_context=SSLContext(verify=True) server_hostname='www.example.com' timeout=5.0
@ -80,4 +78,4 @@ logging.config.dictConfig(LOGGING_CONFIG)
httpx.get('https://www.example.com')
```
The exact formatting of the debug logging may be subject to change across different versions of `httpx` and `httpcore`. If you need to rely on a particular format it is recommended that you pin installation of these packages to fixed versions.
The exact formatting of the debug logging may be subject to change across different versions of `httpx` and `httpcore`. If you need to rely on a particular format it is recommended that you pin installation of these packages to fixed versions.

View File

@ -174,8 +174,9 @@ Form encoded data can also include multiple values from a given key.
You can also upload files, using HTTP multipart encoding:
```pycon
>>> files = {'upload-file': open('report.xls', 'rb')}
>>> r = httpx.post("https://httpbin.org/post", files=files)
>>> with open('report.xls', 'rb') as report_file:
... files = {'upload-file': report_file}
... r = httpx.post("https://httpbin.org/post", files=files)
>>> print(r.text)
{
...
@ -190,8 +191,9 @@ You can also explicitly set the filename and content type, by using a tuple
of items for the file value:
```pycon
>>> files = {'upload-file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel')}
>>> r = httpx.post("https://httpbin.org/post", files=files)
>>> with open('report.xls', 'rb') as report_file:
... files = {'upload-file': ('report.xls', report_file, 'application/vnd.ms-excel')}
... r = httpx.post("https://httpbin.org/post", files=files)
>>> print(r.text)
{
...
@ -206,8 +208,9 @@ If you need to include non-file data fields in the multipart form, use the `data
```pycon
>>> data = {'message': 'Hello, world!'}
>>> files = {'file': open('report.xls', 'rb')}
>>> r = httpx.post("https://httpbin.org/post", data=data, files=files)
>>> with open('report.xls', 'rb') as report_file:
... files = {'file': report_file}
... r = httpx.post("https://httpbin.org/post", data=data, files=files)
>>> print(r.text)
{
...

View File

@ -2,67 +2,21 @@
As HTTPX usage grows, there is an expanding community of developers building tools and libraries that integrate with HTTPX, or depend on HTTPX. Here are some of them.
<!-- NOTE: Entries are alphabetised. -->
## Plugins
### httpx-ws
[GitHub](https://github.com/frankie567/httpx-ws) - [Documentation](https://frankie567.github.io/httpx-ws/)
WebSocket support for HTTPX.
### httpx-socks
[GitHub](https://github.com/romis2012/httpx-socks)
Proxy (HTTP, SOCKS) transports for httpx.
### Hishel
[GitHub](https://github.com/karpetrosyan/hishel) - [Documentation](https://hishel.com/)
An elegant HTTP Cache implementation for HTTPX and HTTP Core.
### Authlib
[GitHub](https://github.com/lepture/authlib) - [Documentation](https://docs.authlib.org/en/latest/)
The ultimate Python library in building OAuth and OpenID Connect clients and servers. Includes an [OAuth HTTPX client](https://docs.authlib.org/en/latest/client/httpx.html).
### Gidgethub
[GitHub](https://github.com/brettcannon/gidgethub) - [Documentation](https://gidgethub.readthedocs.io/en/latest/index.html)
An asynchronous GitHub API library. Includes [HTTPX support](https://gidgethub.readthedocs.io/en/latest/httpx.html).
### HTTPX-Auth
[GitHub](https://github.com/Colin-b/httpx_auth) - [Documentation](https://colin-b.github.io/httpx_auth/)
Provides authentication classes to be used with HTTPX [authentication parameter](advanced/authentication.md#customizing-authentication).
### pytest-HTTPX
[GitHub](https://github.com/Colin-b/pytest_httpx) - [Documentation](https://colin-b.github.io/pytest_httpx/)
Provides `httpx_mock` [pytest](https://docs.pytest.org/en/latest/) fixture to mock HTTPX within test cases.
### RESPX
[GitHub](https://github.com/lundberg/respx) - [Documentation](https://lundberg.github.io/respx/)
A utility for mocking out the Python HTTPX library.
### rpc.py
[Github](https://github.com/abersheeran/rpc.py) - [Documentation](https://github.com/abersheeran/rpc.py#rpcpy)
An fast and powerful RPC framework based on ASGI/WSGI. Use HTTPX as the client of the RPC service.
### VCR.py
[GitHub](https://github.com/kevin1024/vcrpy) - [Documentation](https://vcrpy.readthedocs.io/)
A utility for record and repeat an http request.
Provides authentication classes to be used with HTTPX's [authentication parameter](advanced/authentication.md#customizing-authentication).
### httpx-caching
@ -70,22 +24,82 @@ A utility for record and repeat an http request.
This package adds caching functionality to HTTPX
### httpx-secure
[GitHub](https://github.com/Zaczero/httpx-secure)
Drop-in SSRF protection for httpx with DNS caching and custom validation support.
### httpx-socks
[GitHub](https://github.com/romis2012/httpx-socks)
Proxy (HTTP, SOCKS) transports for httpx.
### httpx-sse
[GitHub](https://github.com/florimondmanca/httpx-sse)
Allows consuming Server-Sent Events (SSE) with HTTPX.
### robox
### httpx-retries
[Github](https://github.com/danclaudiupop/robox)
[GitHub](https://github.com/will-ockmore/httpx-retries) - [Documentation](https://will-ockmore.github.io/httpx-retries/)
A library for scraping the web built on top of HTTPX.
A retry layer for HTTPX.
### httpx-ws
[GitHub](https://github.com/frankie567/httpx-ws) - [Documentation](https://frankie567.github.io/httpx-ws/)
WebSocket support for HTTPX.
### pytest-HTTPX
[GitHub](https://github.com/Colin-b/pytest_httpx) - [Documentation](https://colin-b.github.io/pytest_httpx/)
Provides a [pytest](https://docs.pytest.org/en/latest/) fixture to mock HTTPX within test cases.
### RESPX
[GitHub](https://github.com/lundberg/respx) - [Documentation](https://lundberg.github.io/respx/)
A utility for mocking out HTTPX.
### rpc.py
[Github](https://github.com/abersheeran/rpc.py) - [Documentation](https://github.com/abersheeran/rpc.py#rpcpy)
A fast and powerful RPC framework based on ASGI/WSGI. Use HTTPX as the client of the RPC service.
## Libraries with HTTPX support
### Authlib
[GitHub](https://github.com/lepture/authlib) - [Documentation](https://docs.authlib.org/en/latest/)
A python library for building OAuth and OpenID Connect clients and servers. Includes an [OAuth HTTPX client](https://docs.authlib.org/en/latest/client/httpx.html).
### Gidgethub
[GitHub](https://github.com/brettcannon/gidgethub) - [Documentation](https://gidgethub.readthedocs.io/en/latest/index.html)
An asynchronous GitHub API library. Includes [HTTPX support](https://gidgethub.readthedocs.io/en/latest/httpx.html).
### httpdbg
[GitHub](https://github.com/cle-b/httpdbg) - [Documentation](https://httpdbg.readthedocs.io/)
A tool for python developers to easily debug the HTTP(S) client requests in a python program.
### VCR.py
[GitHub](https://github.com/kevin1024/vcrpy) - [Documentation](https://vcrpy.readthedocs.io/)
Record and repeat requests.
## Gists
<!-- NOTE: this list is in alphabetical order. -->
### urllib3-transport
[GitHub](https://gist.github.com/florimondmanca/d56764d78d748eb9f73165da388e546e)

View File

@ -50,6 +50,7 @@ __all__ = [
"DecodingError",
"delete",
"DigestAuth",
"FunctionAuth",
"get",
"head",
"Headers",

View File

@ -1,3 +1,3 @@
__title__ = "httpx"
__description__ = "A next generation HTTP client, for Python 3."
__version__ = "0.28.0"
__version__ = "0.28.1"

View File

@ -51,7 +51,7 @@ def request(
proxy: ProxyTypes | None = None,
timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
follow_redirects: bool = False,
verify: ssl.SSLContext | bool = True,
verify: ssl.SSLContext | str | bool = True,
trust_env: bool = True,
) -> Response:
"""
@ -136,7 +136,7 @@ def stream(
proxy: ProxyTypes | None = None,
timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
follow_redirects: bool = False,
verify: ssl.SSLContext | bool = True,
verify: ssl.SSLContext | str | bool = True,
trust_env: bool = True,
) -> typing.Iterator[Response]:
"""
@ -180,7 +180,7 @@ def get(
auth: AuthTypes | None = None,
proxy: ProxyTypes | None = None,
follow_redirects: bool = False,
verify: ssl.SSLContext | bool = True,
verify: ssl.SSLContext | str | bool = True,
timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
trust_env: bool = True,
) -> Response:
@ -216,7 +216,7 @@ def options(
auth: AuthTypes | None = None,
proxy: ProxyTypes | None = None,
follow_redirects: bool = False,
verify: ssl.SSLContext | bool = True,
verify: ssl.SSLContext | str | bool = True,
timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
trust_env: bool = True,
) -> Response:
@ -252,7 +252,7 @@ def head(
auth: AuthTypes | None = None,
proxy: ProxyTypes | None = None,
follow_redirects: bool = False,
verify: ssl.SSLContext | bool = True,
verify: ssl.SSLContext | str | bool = True,
timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
trust_env: bool = True,
) -> Response:
@ -292,7 +292,7 @@ def post(
auth: AuthTypes | None = None,
proxy: ProxyTypes | None = None,
follow_redirects: bool = False,
verify: ssl.SSLContext | bool = True,
verify: ssl.SSLContext | str | bool = True,
timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
trust_env: bool = True,
) -> Response:
@ -333,7 +333,7 @@ def put(
auth: AuthTypes | None = None,
proxy: ProxyTypes | None = None,
follow_redirects: bool = False,
verify: ssl.SSLContext | bool = True,
verify: ssl.SSLContext | str | bool = True,
timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
trust_env: bool = True,
) -> Response:
@ -374,7 +374,7 @@ def patch(
auth: AuthTypes | None = None,
proxy: ProxyTypes | None = None,
follow_redirects: bool = False,
verify: ssl.SSLContext | bool = True,
verify: ssl.SSLContext | str | bool = True,
timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
trust_env: bool = True,
) -> Response:
@ -412,7 +412,7 @@ def delete(
proxy: ProxyTypes | None = None,
follow_redirects: bool = False,
timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
verify: ssl.SSLContext | bool = True,
verify: ssl.SSLContext | str | bool = True,
trust_env: bool = True,
) -> Response:
"""

View File

@ -16,7 +16,7 @@ if typing.TYPE_CHECKING: # pragma: no cover
from hashlib import _Hash
__all__ = ["Auth", "BasicAuth", "DigestAuth", "NetRCAuth"]
__all__ = ["Auth", "BasicAuth", "DigestAuth", "FunctionAuth", "NetRCAuth"]
class Auth:

View File

@ -33,6 +33,7 @@ from ._transports.default import AsyncHTTPTransport, HTTPTransport
from ._types import (
AsyncByteStream,
AuthTypes,
CertTypes,
CookieTypes,
HeaderTypes,
ProxyTypes,
@ -619,8 +620,6 @@ class Client(BaseClient):
* **http2** - *(optional)* A boolean indicating if HTTP/2 support should be
enabled. Defaults to `False`.
* **proxy** - *(optional)* A proxy URL where all the traffic should be routed.
* **proxies** - *(optional)* A dictionary mapping proxy keys to proxy
URLs.
* **timeout** - *(optional)* The timeout configuration to use when sending
requests.
* **limits** - *(optional)* The limits configuration to use.
@ -644,7 +643,9 @@ class Client(BaseClient):
params: QueryParamTypes | None = None,
headers: HeaderTypes | None = None,
cookies: CookieTypes | None = None,
verify: ssl.SSLContext | bool = True,
verify: ssl.SSLContext | str | bool = True,
cert: CertTypes | None = None,
trust_env: bool = True,
http1: bool = True,
http2: bool = False,
proxy: ProxyTypes | None = None,
@ -656,7 +657,6 @@ class Client(BaseClient):
event_hooks: None | (typing.Mapping[str, list[EventHook]]) = None,
base_url: URL | str = "",
transport: BaseTransport | None = None,
trust_env: bool = True,
default_encoding: str | typing.Callable[[bytes], str] = "utf-8",
) -> None:
super().__init__(
@ -687,6 +687,8 @@ class Client(BaseClient):
self._transport = self._init_transport(
verify=verify,
cert=cert,
trust_env=trust_env,
http1=http1,
http2=http2,
limits=limits,
@ -698,6 +700,8 @@ class Client(BaseClient):
else self._init_proxy_transport(
proxy,
verify=verify,
cert=cert,
trust_env=trust_env,
http1=http1,
http2=http2,
limits=limits,
@ -713,7 +717,9 @@ class Client(BaseClient):
def _init_transport(
self,
verify: ssl.SSLContext | bool = True,
verify: ssl.SSLContext | str | bool = True,
cert: CertTypes | None = None,
trust_env: bool = True,
http1: bool = True,
http2: bool = False,
limits: Limits = DEFAULT_LIMITS,
@ -724,6 +730,8 @@ class Client(BaseClient):
return HTTPTransport(
verify=verify,
cert=cert,
trust_env=trust_env,
http1=http1,
http2=http2,
limits=limits,
@ -732,13 +740,17 @@ class Client(BaseClient):
def _init_proxy_transport(
self,
proxy: Proxy,
verify: ssl.SSLContext | bool = True,
verify: ssl.SSLContext | str | bool = True,
cert: CertTypes | None = None,
trust_env: bool = True,
http1: bool = True,
http2: bool = False,
limits: Limits = DEFAULT_LIMITS,
) -> BaseTransport:
return HTTPTransport(
verify=verify,
cert=cert,
trust_env=trust_env,
http1=http1,
http2=http2,
limits=limits,
@ -1345,7 +1357,8 @@ class AsyncClient(BaseClient):
params: QueryParamTypes | None = None,
headers: HeaderTypes | None = None,
cookies: CookieTypes | None = None,
verify: ssl.SSLContext | bool = True,
verify: ssl.SSLContext | str | bool = True,
cert: CertTypes | None = None,
http1: bool = True,
http2: bool = False,
proxy: ProxyTypes | None = None,
@ -1388,6 +1401,8 @@ class AsyncClient(BaseClient):
self._transport = self._init_transport(
verify=verify,
cert=cert,
trust_env=trust_env,
http1=http1,
http2=http2,
limits=limits,
@ -1400,6 +1415,8 @@ class AsyncClient(BaseClient):
else self._init_proxy_transport(
proxy,
verify=verify,
cert=cert,
trust_env=trust_env,
http1=http1,
http2=http2,
limits=limits,
@ -1414,7 +1431,9 @@ class AsyncClient(BaseClient):
def _init_transport(
self,
verify: ssl.SSLContext | bool = True,
verify: ssl.SSLContext | str | bool = True,
cert: CertTypes | None = None,
trust_env: bool = True,
http1: bool = True,
http2: bool = False,
limits: Limits = DEFAULT_LIMITS,
@ -1425,6 +1444,8 @@ class AsyncClient(BaseClient):
return AsyncHTTPTransport(
verify=verify,
cert=cert,
trust_env=trust_env,
http1=http1,
http2=http2,
limits=limits,
@ -1433,13 +1454,17 @@ class AsyncClient(BaseClient):
def _init_proxy_transport(
self,
proxy: Proxy,
verify: ssl.SSLContext | bool = True,
verify: ssl.SSLContext | str | bool = True,
cert: CertTypes | None = None,
trust_env: bool = True,
http1: bool = True,
http2: bool = False,
limits: Limits = DEFAULT_LIMITS,
) -> AsyncBaseTransport:
return AsyncHTTPTransport(
verify=verify,
cert=cert,
trust_env=trust_env,
http1=http1,
http2=http2,
limits=limits,
@ -1698,7 +1723,7 @@ class AsyncClient(BaseClient):
if not isinstance(request.stream, AsyncByteStream):
raise RuntimeError(
"Attempted to send an sync request with an AsyncClient instance."
"Attempted to send a sync request with an AsyncClient instance."
)
with request_context(request=request):

View File

@ -1,9 +1,10 @@
from __future__ import annotations
import os
import typing
from ._models import Headers
from ._types import HeaderTypes, TimeoutTypes
from ._types import CertTypes, HeaderTypes, TimeoutTypes
from ._urls import URL
if typing.TYPE_CHECKING:
@ -19,20 +20,53 @@ class UnsetType:
UNSET = UnsetType()
def create_ssl_context(verify: ssl.SSLContext | bool = True) -> ssl.SSLContext:
def create_ssl_context(
verify: ssl.SSLContext | str | bool = True,
cert: CertTypes | None = None,
trust_env: bool = True,
) -> ssl.SSLContext:
import ssl
import warnings
import truststore
import certifi
if verify is True:
return truststore.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
if trust_env and os.environ.get("SSL_CERT_FILE"): # pragma: nocover
ctx = ssl.create_default_context(cafile=os.environ["SSL_CERT_FILE"])
elif trust_env and os.environ.get("SSL_CERT_DIR"): # pragma: nocover
ctx = ssl.create_default_context(capath=os.environ["SSL_CERT_DIR"])
else:
# Default case...
ctx = ssl.create_default_context(cafile=certifi.where())
elif verify is False:
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
return ssl_context
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
elif isinstance(verify, str): # pragma: nocover
message = (
"`verify=<str>` is deprecated. "
"Use `verify=ssl.create_default_context(cafile=...)` "
"or `verify=ssl.create_default_context(capath=...)` instead."
)
warnings.warn(message, DeprecationWarning)
if os.path.isdir(verify):
return ssl.create_default_context(capath=verify)
return ssl.create_default_context(cafile=verify)
else:
ctx = verify
return verify
if cert: # pragma: nocover
message = (
"`cert=...` is deprecated. Use `verify=<ssl_context>` instead,"
"with `.load_cert_chain()` to configure the certificate chain."
)
warnings.warn(message, DeprecationWarning)
if isinstance(cert, str):
ctx.load_cert_chain(cert)
else:
ctx.load_cert_chain(*cert)
return ctx
class Timeout:

View File

@ -331,9 +331,7 @@ class StreamClosed(StreamError):
"""
def __init__(self) -> None:
message = (
"Attempted to read or stream content, but the stream has " "been closed."
)
message = "Attempted to read or stream content, but the stream has been closed."
super().__init__(message)

View File

@ -398,7 +398,7 @@ class Request:
self.method = method.upper()
self.url = URL(url) if params is None else URL(url, params=params)
self.headers = Headers(headers)
self.extensions = {} if extensions is None else extensions
self.extensions = {} if extensions is None else dict(extensions)
if cookies:
Cookies(cookies).set_cookie_header(self)
@ -537,7 +537,7 @@ class Response:
# the client will set `response.next_request`.
self.next_request: Request | None = None
self.extensions: ResponseExtensions = {} if extensions is None else extensions
self.extensions = {} if extensions is None else dict(extensions)
self.history = [] if history is None else list(history)
self.is_closed = False
@ -964,7 +964,7 @@ class Response:
Automatically called if the response body is read to completion.
"""
if not isinstance(self.stream, SyncByteStream):
raise RuntimeError("Attempted to call an sync close on an async stream.")
raise RuntimeError("Attempted to call a sync close on an async stream.")
if not self.is_closed:
self.is_closed = True
@ -1045,7 +1045,7 @@ class Response:
if self.is_closed:
raise StreamClosed()
if not isinstance(self.stream, AsyncByteStream):
raise RuntimeError("Attempted to call an async iterator on an sync stream.")
raise RuntimeError("Attempted to call an async iterator on a sync stream.")
self.is_stream_consumed = True
self._num_bytes_downloaded = 0
@ -1068,7 +1068,7 @@ class Response:
Automatically called if the response body is read to completion.
"""
if not isinstance(self.stream, AsyncByteStream):
raise RuntimeError("Attempted to call an async close on an sync stream.")
raise RuntimeError("Attempted to call an async close on a sync stream.")
if not self.is_closed:
self.is_closed = True

View File

@ -53,7 +53,7 @@ from .._exceptions import (
WriteTimeout,
)
from .._models import Request, Response
from .._types import AsyncByteStream, ProxyTypes, SyncByteStream
from .._types import AsyncByteStream, CertTypes, ProxyTypes, SyncByteStream
from .._urls import URL
from .base import AsyncBaseTransport, BaseTransport
@ -135,7 +135,9 @@ class ResponseStream(SyncByteStream):
class HTTPTransport(BaseTransport):
def __init__(
self,
verify: ssl.SSLContext | bool = True,
verify: ssl.SSLContext | str | bool = True,
cert: CertTypes | None = None,
trust_env: bool = True,
http1: bool = True,
http2: bool = False,
limits: Limits = DEFAULT_LIMITS,
@ -148,7 +150,7 @@ class HTTPTransport(BaseTransport):
import httpcore
proxy = Proxy(url=proxy) if isinstance(proxy, (str, URL)) else proxy
ssl_context = create_ssl_context(verify=verify)
ssl_context = create_ssl_context(verify=verify, cert=cert, trust_env=trust_env)
if proxy is None:
self._pool = httpcore.ConnectionPool(
@ -277,7 +279,9 @@ class AsyncResponseStream(AsyncByteStream):
class AsyncHTTPTransport(AsyncBaseTransport):
def __init__(
self,
verify: ssl.SSLContext | bool = True,
verify: ssl.SSLContext | str | bool = True,
cert: CertTypes | None = None,
trust_env: bool = True,
http1: bool = True,
http2: bool = False,
limits: Limits = DEFAULT_LIMITS,
@ -290,7 +294,7 @@ class AsyncHTTPTransport(AsyncBaseTransport):
import httpcore
proxy = Proxy(url=proxy) if isinstance(proxy, (str, URL)) else proxy
ssl_context = create_ssl_context(verify=verify)
ssl_context = create_ssl_context(verify=verify, cert=cert, trust_env=trust_env)
if proxy is None:
self._pool = httpcore.AsyncConnectionPool(
@ -351,7 +355,7 @@ class AsyncHTTPTransport(AsyncBaseTransport):
else: # pragma: no cover
raise ValueError(
"Proxy protocol must be either 'http', 'https', 'socks5', or 'socks5h',"
" but got {proxy.url.scheme!r}."
f" but got {proxy.url.scheme!r}."
)
async def __aenter__(self: A) -> A: # Use generics for subclass support.

View File

@ -15,7 +15,6 @@ from typing import (
Iterator,
List,
Mapping,
MutableMapping,
Optional,
Sequence,
Tuple,
@ -58,6 +57,7 @@ TimeoutTypes = Union[
"Timeout",
]
ProxyTypes = Union["URL", str, "Proxy"]
CertTypes = Union[str, Tuple[str, str], Tuple[str, str, str]]
AuthTypes = Union[
Tuple[Union[str, bytes], Union[str, bytes]],
@ -67,7 +67,7 @@ AuthTypes = Union[
RequestContent = Union[str, bytes, Iterable[bytes], AsyncIterable[bytes]]
ResponseContent = Union[str, bytes, Iterable[bytes], AsyncIterable[bytes]]
ResponseExtensions = MutableMapping[str, Any]
ResponseExtensions = Mapping[str, Any]
RequestData = Mapping[str, Any]
@ -84,7 +84,7 @@ FileTypes = Union[
]
RequestFiles = Union[Mapping[str, FileTypes], Sequence[Tuple[str, FileTypes]]]
RequestExtensions = MutableMapping[str, Any]
RequestExtensions = Mapping[str, Any]
__all__ = ["AsyncByteStream", "SyncByteStream"]

View File

@ -379,7 +379,7 @@ class URL:
if ":" in userinfo:
# Mask any password component.
userinfo = f'{userinfo.split(":")[0]}:[secure]'
userinfo = f"{userinfo.split(':')[0]}:[secure]"
authority = "".join(
[

View File

@ -6,7 +6,7 @@ build-backend = "hatchling.build"
name = "httpx"
description = "The next generation HTTP client."
license = "BSD-3-Clause"
requires-python = ">=3.8"
requires-python = ">=3.9"
authors = [
{ name = "Tom Christie", email = "tom@tomchristie.com" },
]
@ -20,15 +20,15 @@ classifiers = [
"Operating System :: OS Independent",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Topic :: Internet :: WWW/HTTP",
]
dependencies = [
"truststore==0.10.0",
"certifi",
"httpcore==1.*",
"anyio",
"idna",
@ -43,7 +43,7 @@ brotli = [
cli = [
"click==8.*",
"pygments==2.*",
"rich>=10,<14",
"rich>=10,<15",
]
http2 = [
"h2>=3,<5",

View File

@ -11,19 +11,19 @@ chardet==5.2.0
# Documentation
mkdocs==1.6.1
mkautodoc==0.2.0
mkdocs-material==9.5.39
mkdocs-material==9.6.18
# Packaging
build==1.2.2
twine==5.1.1
build==1.3.0
twine==6.1.0
# Tests & Linting
coverage[toml]==7.6.1
cryptography==43.0.1
mypy==1.11.2
pytest==8.3.3
ruff==0.6.8
trio==0.26.2
coverage[toml]==7.10.6
cryptography==45.0.7
mypy==1.17.1
pytest==8.4.1
ruff==0.12.11
trio==0.31.0
trio-typing==0.10.0
trustme==1.1.0
uvicorn==0.31.0
trustme==1.2.1
uvicorn==0.35.0

View File

@ -326,7 +326,7 @@ async def test_auth_property() -> None:
async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:
assert client.auth is None
client.auth = ("user", "password123") # type: ignore
client.auth = ("user", "password123")
assert isinstance(client.auth, httpx.BasicAuth)
url = "https://example.org/"

View File

@ -3,35 +3,35 @@ import httpx
def test_client_base_url():
client = httpx.Client()
client.base_url = "https://www.example.org/" # type: ignore
client.base_url = "https://www.example.org/"
assert isinstance(client.base_url, httpx.URL)
assert client.base_url == "https://www.example.org/"
def test_client_base_url_without_trailing_slash():
client = httpx.Client()
client.base_url = "https://www.example.org/path" # type: ignore
client.base_url = "https://www.example.org/path"
assert isinstance(client.base_url, httpx.URL)
assert client.base_url == "https://www.example.org/path/"
def test_client_base_url_with_trailing_slash():
client = httpx.Client()
client.base_url = "https://www.example.org/path/" # type: ignore
client.base_url = "https://www.example.org/path/"
assert isinstance(client.base_url, httpx.URL)
assert client.base_url == "https://www.example.org/path/"
def test_client_headers():
client = httpx.Client()
client.headers = {"a": "b"} # type: ignore
client.headers = {"a": "b"}
assert isinstance(client.headers, httpx.Headers)
assert client.headers["A"] == "b"
def test_client_cookies():
client = httpx.Client()
client.cookies = {"a": "b"} # type: ignore
client.cookies = {"a": "b"}
assert isinstance(client.cookies, httpx.Cookies)
mycookies = list(client.cookies.jar)
assert len(mycookies) == 1
@ -42,7 +42,7 @@ def test_client_timeout():
expected_timeout = 12.0
client = httpx.Client()
client.timeout = expected_timeout # type: ignore
client.timeout = expected_timeout
assert isinstance(client.timeout, httpx.Timeout)
assert client.timeout.connect == expected_timeout

View File

@ -17,7 +17,7 @@ def test_client_queryparams_string():
assert client.params["a"] == "b"
client = httpx.Client()
client.params = "a=b" # type: ignore
client.params = "a=b"
assert isinstance(client.params, httpx.QueryParams)
assert client.params["a"] == "b"

View File

@ -226,3 +226,16 @@ def test_request_generator_content_picklable():
request.read()
pickle_request = pickle.loads(pickle.dumps(request))
assert pickle_request.content == b"test 123"
def test_request_params():
request = httpx.Request("GET", "http://example.com", params={})
assert str(request.url) == "http://example.com"
request = httpx.Request(
"GET", "http://example.com?c=3", params={"a": "1", "b": "2"}
)
assert str(request.url) == "http://example.com?a=1&b=2"
request = httpx.Request("GET", "http://example.com?a=1", params={})
assert str(request.url) == "http://example.com"

View File

@ -1011,7 +1011,10 @@ def test_response_decode_text_using_autodetect():
assert response.status_code == 200
assert response.reason_phrase == "OK"
assert response.encoding == "ISO-8859-1"
# The encoded byte string is consistent with either ISO-8859-1 or
# WINDOWS-1252. Versions <6.0 of chardet claim the former, while chardet
# 6.0 detects the latter.
assert response.encoding in ("ISO-8859-1", "WINDOWS-1252")
assert response.text == text

View File

@ -1,5 +1,8 @@
import ssl
import typing
from pathlib import Path
import certifi
import pytest
import httpx
@ -17,6 +20,26 @@ def test_load_ssl_config_verify_non_existing_file():
context.load_verify_locations(cafile="/path/to/nowhere")
def test_load_ssl_with_keylog(monkeypatch: typing.Any) -> None:
monkeypatch.setenv("SSLKEYLOGFILE", "test")
context = httpx.create_ssl_context()
assert context.keylog_filename == "test"
def test_load_ssl_config_verify_existing_file():
context = httpx.create_ssl_context()
context.load_verify_locations(capath=certifi.where())
assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED
assert context.check_hostname is True
def test_load_ssl_config_verify_directory():
context = httpx.create_ssl_context()
context.load_verify_locations(capath=Path(certifi.where()).parent)
assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED
assert context.check_hostname is True
def test_load_ssl_config_cert_and_key(cert_pem_file, cert_private_key_file):
context = httpx.create_ssl_context()
context.load_cert_chain(cert_pem_file, cert_private_key_file)

View File

@ -489,18 +489,18 @@ def test_response_invalid_argument():
def test_ensure_ascii_false_with_french_characters():
data = {"greeting": "Bonjour, ça va ?"}
response = httpx.Response(200, json=data)
assert (
"ça va" in response.text
), "ensure_ascii=False should preserve French accented characters"
assert "ça va" in response.text, (
"ensure_ascii=False should preserve French accented characters"
)
assert response.headers["Content-Type"] == "application/json"
def test_separators_for_compact_json():
data = {"clé": "valeur", "liste": [1, 2, 3]}
response = httpx.Response(200, json=data)
assert (
response.text == '{"clé":"valeur","liste":[1,2,3]}'
), "separators=(',', ':') should produce a compact representation"
assert response.text == '{"clé":"valeur","liste":[1,2,3]}', (
"separators=(',', ':') should produce a compact representation"
)
assert response.headers["Content-Type"] == "application/json"