Skip to content

Commit d28bc12

Browse files
dbantyemann
andauthored
Redesign client for more flexibility via direct httpx access (#775)
* Prototype tighter httpx integration * Blacken * New client template * Update templates & tests * Update generated readmes * Rename `*_client` functions to `*_httpx_client` * Allow AuthenticatedClient anywhere a Client is allowed * Use macros to keep Client/AuthenticatedClient the same * Add changeset notes * Add integration test for minimal httpx version * Add mypy to integration tests * Install lower httpx in the right place for integration tests * Update every attrs to use new syntax, raise minimum httpx version * More release dry runs and prerelease action * Put back missing tabs * Put back missing tabs * Update end_to_end_tests/golden-record/my_test_api_client/client.py Co-authored-by: Ethan Mann <[email protected]> * Regen --------- Co-authored-by: Dylan Anthony <[email protected]> Co-authored-by: Ethan Mann <[email protected]>
1 parent 7b38b52 commit d28bc12

File tree

136 files changed

+2526
-1881
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

136 files changed

+2526
-1881
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
---
2+
default: minor
3+
---
4+
5+
#### Allow customizing the underlying `httpx` clients
6+
7+
There are many use-cases where customizing the underlying `httpx` client directly is necessary. Some examples are:
8+
9+
- [Event hooks](https://www.python-httpx.org/advanced/#event-hooks)
10+
- [Proxies](https://www.python-httpx.org/advanced/#http-proxying)
11+
- [Custom authentication](https://www.python-httpx.org/advanced/#customizing-authentication)
12+
- [Retries](https://www.python-httpx.org/advanced/#usage_1)
13+
14+
The new `Client` and `AuthenticatedClient` classes come with several methods to customize underlying clients. You can pass arbitrary arguments to `httpx.Client` or `httpx.AsyncClient` when they are constructed:
15+
16+
```python
17+
client = Client(base_url="https://api.example.com", httpx_args={"proxies": {"https://": "https://proxy.example.com"}})
18+
```
19+
20+
**The underlying clients are constructed lazily, only when needed. `httpx_args` are stored internally in a dictionary until the first request is made.**
21+
22+
You can force immediate construction of an underlying client in order to edit it directly:
23+
24+
```python
25+
import httpx
26+
from my_api import Client
27+
28+
client = Client(base_url="https://api.example.com")
29+
sync_client: httpx.Client = client.get_httpx_client()
30+
sync_client.timeout = 10
31+
async_client = client.get_async_httpx_client()
32+
async_client.timeout = 15
33+
```
34+
35+
You can also completely override the underlying clients:
36+
37+
```python
38+
import httpx
39+
from my_api import Client
40+
41+
client = Client(base_url="https://api.example.com")
42+
# The params you put in here ^ are discarded when you call set_httpx_client or set_async_httpx_client
43+
sync_client = httpx.Client(base_url="https://api.example.com", timeout=10)
44+
client.set_httpx_client(sync_client)
45+
async_client = httpx.AsyncClient(base_url="https://api.example.com", timeout=15)
46+
client.set_async_httpx_client(async_client)
47+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
default: major
3+
---
4+
5+
#### `AuthenticatedClient` no longer inherits from `Client`
6+
7+
The API of `AuthenticatedClient` is still a superset of `Client`, but the two classes no longer share a common base class.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
default: major
3+
---
4+
5+
#### Generated clients and models now use the newer attrs `@define` and `field` APIs
6+
7+
See [the attrs docs](https://www.attrs.org/en/stable/names.html#attrs-tng) for more information on how these may affect you.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
default: minor
3+
---
4+
5+
#### Clients now reuse connections between requests
6+
7+
This happens every time you use the same `Client` or `AuthenticatedClient` instance for multiple requests, however it is best to use a context manager (e.g., `with client as client:`) to ensure the client is closed properly.

Diff for: .changeset/connections_dont_close.md

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
---
2+
default: major
3+
---
4+
5+
#### Connections from clients no longer automatically close (PR [#775](https://github.com/openapi-generators/openapi-python-client/pull/775))
6+
7+
`Client` and `AuthenticatedClient` now reuse an internal [`httpx.Client`](https://www.python-httpx.org/advanced/#client-instances) (or `AsyncClient`)—keeping connections open between requests. This will improve performance overall, but may cause resource leaking if clients are not closed properly. The new clients are intended to be used via context managers—though for compatibility they don't _have_ to be used with context managers. If not using a context manager, connections will probably leak. Note that once a client is closed (by leaving the context manager), it can no longer be used—and attempting to do so will raise an exception.
8+
9+
APIs should now be called like:
10+
11+
```python
12+
with client as client:
13+
my_api.sync(client)
14+
another_api.sync(client)
15+
# client is closed here and can no longer be used
16+
```
17+
18+
Generated READMEs reflect the new syntax, but READMEs for existing generated clients should be updated manually. See [this diff](https://github.com/openapi-generators/openapi-python-client/pull/775/files#diff-62b50316369f84439d58f4981c37538f5b619d344393cb659080dadbda328547) for inspiration.

Diff for: .changeset/minimum_httpx_version_raised_to_020.md

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
default: major
3+
---
4+
5+
#### Minimum httpx version raised to 0.20
6+
7+
Some features of generated clients already failed at runtime when using httpx < 0.20, but now the minimum version is enforced at generation time.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
default: major
3+
---
4+
5+
#### Removed public attributes for `Client` and `AuthenticatedClient`
6+
7+
The following attributes have been removed from `Client` and `AuthenticatedClient`:
8+
9+
- `base_url`—this can now only be set via the initializer
10+
- `cookies`—set at initialization or use `.with_cookies()`
11+
- `headers`—set at initialization or use `.with_headers()`
12+
- `timeout`—set at initialization or use `.with_timeout()`
13+
- `verify_ssl`—this can now only be set via the initializer
14+
- `follow_redirects`—this can now only be set via the initializer
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
default: patch
3+
---
4+
5+
#### Stop showing Poetry instructions in generated READMEs when not appropriate
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
default: major
3+
---
4+
5+
#### The `timeout` param and `with_timeout` now take an `httpx.Timeout` instead of a float

Diff for: .github/workflows/checks.yml

+11
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,11 @@ jobs:
9090
integration:
9191
name: Integration Tests
9292
runs-on: ubuntu-latest
93+
strategy:
94+
matrix:
95+
httpx_version:
96+
- "0.20.0"
97+
- ""
9398
services:
9499
openapi-test-server:
95100
image: ghcr.io/openapi-generators/openapi-test-server:0.0.1
@@ -135,9 +140,15 @@ jobs:
135140
python -m venv .venv
136141
poetry run python -m pip install --upgrade pip
137142
poetry install
143+
- name: Set httpx version
144+
if: matrix.httpx_version != ''
145+
run: |
146+
cd integration-tests
147+
poetry run pip install httpx==${{ matrix.httpx_version }}
138148
- name: Run Tests
139149
run: |
140150
cd integration-tests
141151
poetry run pytest
152+
poetry run mypy . --strict
142153
143154

Diff for: end_to_end_tests/golden-record/README.md

+43-8
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,10 @@ from my_test_api_client.models import MyDataModel
2525
from my_test_api_client.api.my_tag import get_my_data_model
2626
from my_test_api_client.types import Response
2727

28-
my_data: MyDataModel = get_my_data_model.sync(client=client)
29-
# or if you need more info (e.g. status_code)
30-
response: Response[MyDataModel] = get_my_data_model.sync_detailed(client=client)
28+
with client as client:
29+
my_data: MyDataModel = get_my_data_model.sync(client=client)
30+
# or if you need more info (e.g. status_code)
31+
response: Response[MyDataModel] = get_my_data_model.sync_detailed(client=client)
3132
```
3233

3334
Or do the same thing with an async version:
@@ -37,8 +38,9 @@ from my_test_api_client.models import MyDataModel
3738
from my_test_api_client.api.my_tag import get_my_data_model
3839
from my_test_api_client.types import Response
3940

40-
my_data: MyDataModel = await get_my_data_model.asyncio(client=client)
41-
response: Response[MyDataModel] = await get_my_data_model.asyncio_detailed(client=client)
41+
async with client as client:
42+
my_data: MyDataModel = await get_my_data_model.asyncio(client=client)
43+
response: Response[MyDataModel] = await get_my_data_model.asyncio_detailed(client=client)
4244
```
4345

4446
By default, when you're calling an HTTPS API it will attempt to verify that SSL is working correctly. Using certificate verification is highly recommended most of the time, but sometimes you may need to authenticate to a server (especially an internal server) using a custom certificate bundle.
@@ -61,8 +63,6 @@ client = AuthenticatedClient(
6163
)
6264
```
6365

64-
There are more settings on the generated `Client` class which let you control more runtime behavior, check out the docstring on that class for more info.
65-
6666
Things to know:
6767
1. Every path/method combo becomes a Python module with four functions:
6868
1. `sync`: Blocking request that returns parsed data (if successful) or `None`
@@ -74,7 +74,42 @@ Things to know:
7474
1. If your endpoint had any tags on it, the first tag will be used as a module name for the function (my_tag above)
7575
1. Any endpoint which did not have a tag will be in `my_test_api_client.api.default`
7676

77-
## Building / publishing this Client
77+
## Advanced customizations
78+
79+
There are more settings on the generated `Client` class which let you control more runtime behavior, check out the docstring on that class for more info. You can also customize the underlying `httpx.Client` or `httpx.AsyncClient` (depending on your use-case):
80+
81+
```python
82+
from my_test_api_client import Client
83+
84+
def log_request(request):
85+
print(f"Request event hook: {request.method} {request.url} - Waiting for response")
86+
87+
def log_response(response):
88+
request = response.request
89+
print(f"Response event hook: {request.method} {request.url} - Status {response.status_code}")
90+
91+
client = Client(
92+
base_url="https://api.example.com",
93+
httpx_args={"event_hooks": {"request": [log_request], "response": [log_response]}},
94+
)
95+
96+
# Or get the underlying httpx client to modify directly with client.get_httpx_client() or client.get_async_httpx_client()
97+
```
98+
99+
You can even set the httpx client directly, but beware that this will override any existing settings (e.g., base_url):
100+
101+
```python
102+
import httpx
103+
from my_test_api_client import Client
104+
105+
client = Client(
106+
base_url="https://api.example.com",
107+
)
108+
# Note that base_url needs to be re-set, as would any shared cookies, headers, etc.
109+
client.set_httpx_client(httpx.Client(base_url="https://api.example.com", proxies="http://localhost:8030"))
110+
```
111+
112+
## Building / publishing this package
78113
This project uses [Poetry](https://python-poetry.org/) to manage dependencies and packaging. Here are the basics:
79114
1. Update the metadata in pyproject.toml (e.g. authors, version)
80115
1. If you're using a private repository, configure it with Poetry

Diff for: end_to_end_tests/golden-record/my_test_api_client/api/default/get_common_parameters.py

+9-21
Original file line numberDiff line numberDiff line change
@@ -4,19 +4,15 @@
44
import httpx
55

66
from ... import errors
7-
from ...client import Client
7+
from ...client import AuthenticatedClient, Client
88
from ...types import UNSET, Response, Unset
99

1010

1111
def _get_kwargs(
1212
*,
13-
client: Client,
1413
common: Union[Unset, None, str] = UNSET,
1514
) -> Dict[str, Any]:
16-
url = "{}/common_parameters".format(client.base_url)
17-
18-
headers: Dict[str, str] = client.get_headers()
19-
cookies: Dict[str, Any] = client.get_cookies()
15+
pass
2016

2117
params: Dict[str, Any] = {}
2218
params["common"] = common
@@ -25,16 +21,12 @@ def _get_kwargs(
2521

2622
return {
2723
"method": "get",
28-
"url": url,
29-
"headers": headers,
30-
"cookies": cookies,
31-
"timeout": client.get_timeout(),
32-
"follow_redirects": client.follow_redirects,
24+
"url": "/common_parameters",
3325
"params": params,
3426
}
3527

3628

37-
def _parse_response(*, client: Client, response: httpx.Response) -> Optional[Any]:
29+
def _parse_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Optional[Any]:
3830
if response.status_code == HTTPStatus.OK:
3931
return None
4032
if client.raise_on_unexpected_status:
@@ -43,7 +35,7 @@ def _parse_response(*, client: Client, response: httpx.Response) -> Optional[Any
4335
return None
4436

4537

46-
def _build_response(*, client: Client, response: httpx.Response) -> Response[Any]:
38+
def _build_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Response[Any]:
4739
return Response(
4840
status_code=HTTPStatus(response.status_code),
4941
content=response.content,
@@ -54,7 +46,7 @@ def _build_response(*, client: Client, response: httpx.Response) -> Response[Any
5446

5547
def sync_detailed(
5648
*,
57-
client: Client,
49+
client: Union[AuthenticatedClient, Client],
5850
common: Union[Unset, None, str] = UNSET,
5951
) -> Response[Any]:
6052
"""
@@ -70,12 +62,10 @@ def sync_detailed(
7062
"""
7163

7264
kwargs = _get_kwargs(
73-
client=client,
7465
common=common,
7566
)
7667

77-
response = httpx.request(
78-
verify=client.verify_ssl,
68+
response = client.get_httpx_client().request(
7969
**kwargs,
8070
)
8171

@@ -84,7 +74,7 @@ def sync_detailed(
8474

8575
async def asyncio_detailed(
8676
*,
87-
client: Client,
77+
client: Union[AuthenticatedClient, Client],
8878
common: Union[Unset, None, str] = UNSET,
8979
) -> Response[Any]:
9080
"""
@@ -100,11 +90,9 @@ async def asyncio_detailed(
10090
"""
10191

10292
kwargs = _get_kwargs(
103-
client=client,
10493
common=common,
10594
)
10695

107-
async with httpx.AsyncClient(verify=client.verify_ssl) as _client:
108-
response = await _client.request(**kwargs)
96+
response = await client.get_async_httpx_client().request(**kwargs)
10997

11098
return _build_response(client=client, response=response)

0 commit comments

Comments
 (0)