cloudru-qa-http-client 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cloudru_qa_http_client-1.0.0.dist-info/METADATA +615 -0
- cloudru_qa_http_client-1.0.0.dist-info/RECORD +18 -0
- cloudru_qa_http_client-1.0.0.dist-info/WHEEL +4 -0
- cloudru_qa_http_client-1.0.0.dist-info/licenses/LICENSE +202 -0
- http_client/.agents/skills/http-client-usage/SKILL.md +227 -0
- http_client/.agents/skills/http-client-usage/references/options.md +219 -0
- http_client/.agents/skills/http-client-usage/references/pitfalls.md +53 -0
- http_client/__init__.py +16 -0
- http_client/client.py +603 -0
- http_client/config.py +82 -0
- http_client/event_hooks.py +159 -0
- http_client/options.py +226 -0
- http_client/py.typed +1 -0
- http_client/types.py +141 -0
- http_client/utils/__init__.py +0 -0
- http_client/utils/logutils.py +275 -0
- http_client/utils/sanitizer.py +59 -0
- http_client/utils/traceparent.py +12 -0
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: http-client-usage
|
|
3
|
+
description: Building HTTP clients on the http_client library — an httpx wrapper providing constructor options, event hooks, send/stream decorators, request logging with secret masking, and streaming requests. Use when creating a client for an external API, adding an endpoint to an existing client, or configuring authentication, timeouts, retries, TLS, default headers, tracing, or streaming in a project that imports http_client. Key names are HttpClient, AsyncHttpClient, ClientOption, options.with_*, send_decorator, stream_request.
|
|
4
|
+
license: Apache-2.0
|
|
5
|
+
metadata:
|
|
6
|
+
library-version: "1.0.0"
|
|
7
|
+
source: packages/http-client
|
|
8
|
+
---
|
|
9
|
+
|
|
10
|
+
# Building clients on http_client
|
|
11
|
+
|
|
12
|
+
`http_client` is a thin wrapper around `httpx`. It adds exactly three things:
|
|
13
|
+
|
|
14
|
+
1. **Constructor options** (`ClientOption`) — configuration is passed as positional arguments to the constructor instead of a dozen keyword parameters.
|
|
15
|
+
2. **Transport decorators** — wrappers around `send` and `stream_request` for cross-cutting concerns: metrics, caching, plugging in an existing retry library.
|
|
16
|
+
3. **Request/response logging** with field masking by glom paths.
|
|
17
|
+
|
|
18
|
+
Everything else (`Request`, `Response`, `Auth`, `Timeout`, status codes) is plain `httpx`. Do not invent your own wrappers around what `httpx` already provides.
|
|
19
|
+
|
|
20
|
+
## Hard rules
|
|
21
|
+
|
|
22
|
+
1. Subclass `HttpClient` or `AsyncHttpClient`. `BaseHttpClient` is abstract and has no transport; never subclass it directly.
|
|
23
|
+
2. Configure only through constructor options. Do not assign `client.timeout`, `client.auth`, etc. after construction — `httpx.Client` is already built and the change will not apply.
|
|
24
|
+
3. Inside endpoint methods call `self.send(request)`, **not** `self.client.send(request)`. The direct call bypasses every decorator.
|
|
25
|
+
4. Do not add dependencies to the library itself — it must stay lightweight.
|
|
26
|
+
5. Never write a retry loop, backoff, or circuit breaker by hand. Take the project's existing retry library and mount it via `with_send_decorator`.
|
|
27
|
+
|
|
28
|
+
Before claiming an option cannot do something, check `references/pitfalls.md` — it documents the non-obvious behaviour that trips people up.
|
|
29
|
+
|
|
30
|
+
## Canonical client (sync)
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
import httpx
|
|
34
|
+
from http_client import HttpClient
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class OrdersClient(HttpClient):
|
|
38
|
+
"""Client for the orders service."""
|
|
39
|
+
|
|
40
|
+
def get_order(self, order_id: str) -> httpx.Response:
|
|
41
|
+
request = self.client.build_request("GET", f"/orders/{order_id}")
|
|
42
|
+
return self.send(request)
|
|
43
|
+
|
|
44
|
+
def create_order(self, payload: dict[str, object]) -> httpx.Response:
|
|
45
|
+
request = self.client.build_request("POST", "/orders", json=payload)
|
|
46
|
+
return self.send(request)
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Paths are relative to the `base_url` passed to the constructor — `httpx` joins them.
|
|
50
|
+
|
|
51
|
+
Assembly:
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
import logging
|
|
55
|
+
|
|
56
|
+
from http_client import options
|
|
57
|
+
from httpx import BasicAuth
|
|
58
|
+
|
|
59
|
+
client = OrdersClient(
|
|
60
|
+
"https://api.example.com",
|
|
61
|
+
options.with_auth(BasicAuth("admin", "PazzW0rD")),
|
|
62
|
+
options.with_timeout(30),
|
|
63
|
+
options.with_logger(logging.getLogger("orders")),
|
|
64
|
+
options.with_autogenerated_request_id(),
|
|
65
|
+
)
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## Canonical client (async)
|
|
69
|
+
|
|
70
|
+
Exactly two differences: the base class and `await`. The options are identical, including synchronous event hooks — those are wrapped into coroutines automatically.
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
class AsyncOrdersClient(AsyncHttpClient):
|
|
74
|
+
async def get_order(self, order_id: str) -> httpx.Response:
|
|
75
|
+
request = self.client.build_request("GET", f"/orders/{order_id}")
|
|
76
|
+
return await self.send(request)
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
One exception: `send`/`stream_request` decorators for an async client must themselves be async — there is no auto-wrapping for them.
|
|
80
|
+
|
|
81
|
+
## Choosing how to send
|
|
82
|
+
|
|
83
|
+
| Task | What to call |
|
|
84
|
+
|---|---|
|
|
85
|
+
| Endpoint method in your own client | `self.client.build_request(...)` → `self.send(request)` |
|
|
86
|
+
| One-off call without a custom client | `client.get(...)`, `client.post(...)`, `client.request(method, url, ...)` |
|
|
87
|
+
| Streaming download/upload, method and URL known | `client.stream(method, url, ...)` |
|
|
88
|
+
| Stream from a prepared `httpx.Request` | `client.stream_request(request)` |
|
|
89
|
+
|
|
90
|
+
`send` and `stream_request` are the only points decorators pass through. The `get`/`post`/... shortcuts call `send` internally, so decorators apply to them as well.
|
|
91
|
+
|
|
92
|
+
## Releasing connections
|
|
93
|
+
|
|
94
|
+
The connection pool is created in the constructor, so every client must be closed. Prefer the context manager:
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
with OrdersClient("https://api.example.com") as client:
|
|
98
|
+
client.get_order("42")
|
|
99
|
+
|
|
100
|
+
async with AsyncOrdersClient("https://api.example.com") as client:
|
|
101
|
+
await client.get_order("42")
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
For a long-lived client, close it explicitly: `client.close()` / `await client.aclose()`.
|
|
105
|
+
|
|
106
|
+
## Options
|
|
107
|
+
|
|
108
|
+
The full catalog with exact signatures and behaviour is in `references/options.md`. Summary:
|
|
109
|
+
|
|
110
|
+
| Option | Purpose |
|
|
111
|
+
|---|---|
|
|
112
|
+
| `with_auth(auth)` | any httpx authentication mechanism |
|
|
113
|
+
| `with_timeout(timeout)` | client timeout; defaults to 60 s on every phase |
|
|
114
|
+
| `with_logger(logger, sanitize_keys=..., ...)` | request and response logging |
|
|
115
|
+
| `with_default_headers(headers)` | headers applied to every request |
|
|
116
|
+
| `with_request_hook(hook)` / `with_response_hook(hook)` | arbitrary request/response processing |
|
|
117
|
+
| `with_autogenerated_request_id()` | `X-Request-ID` header |
|
|
118
|
+
| `with_autogenerated_traceparent()` | `Traceparent` header (W3C Trace Context) |
|
|
119
|
+
| `with_send_decorator(dec)` / `with_stream_decorator(dec)` | transport wrappers |
|
|
120
|
+
| `with_follow_redirects(max_redirects=20)` | follow redirects |
|
|
121
|
+
| `with_verify_context(verify=...)` / `use_truststore()` | TLS configuration |
|
|
122
|
+
|
|
123
|
+
### Writing your own option
|
|
124
|
+
|
|
125
|
+
`ClientOption` is `Callable[[BaseHttpClient], None]`. Options receive the actual client inside
|
|
126
|
+
`BaseHttpClient.__init__`, before the httpx transport exists. Use the public configuration properties
|
|
127
|
+
(`timeout`, `auth`, `verify`, `url_suffix`) and registration methods. Accessing `client.client` inside
|
|
128
|
+
an option raises `AttributeError`.
|
|
129
|
+
|
|
130
|
+
```python
|
|
131
|
+
import httpx
|
|
132
|
+
from http_client import ClientOption
|
|
133
|
+
from http_client.client import BaseHttpClient
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def with_api_key(key: str) -> ClientOption:
|
|
137
|
+
def add_key(request: httpx.Request) -> None:
|
|
138
|
+
request.headers["X-Api-Key"] = key
|
|
139
|
+
|
|
140
|
+
def option(client: BaseHttpClient) -> None:
|
|
141
|
+
client.add_request_hook(add_key, prepend=True)
|
|
142
|
+
|
|
143
|
+
return option
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
Compose options from built-ins or call `add_request_hook`, `add_response_hook`, `add_send_decorator`
|
|
147
|
+
and `add_stream_decorator`. `prepend=True` puts a request hook first. Configuration properties and
|
|
148
|
+
registration methods reject changes after construction with `RuntimeError`.
|
|
149
|
+
|
|
150
|
+
## Wrapping the transport
|
|
151
|
+
|
|
152
|
+
A decorator wraps `send`, so it sees the request on the way out and the response on the way back. The shape below is the whole pattern — this particular one just records what passed through, which is handy in tests:
|
|
153
|
+
|
|
154
|
+
```python
|
|
155
|
+
from collections.abc import Callable
|
|
156
|
+
from functools import wraps
|
|
157
|
+
|
|
158
|
+
import httpx
|
|
159
|
+
from http_client.types import SyncSendMethod
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def with_call_recorder(calls: list[str]) -> Callable[[SyncSendMethod], SyncSendMethod]:
|
|
163
|
+
def decorator(func: SyncSendMethod) -> SyncSendMethod:
|
|
164
|
+
@wraps(func)
|
|
165
|
+
def wrapper(request: httpx.Request, **kwargs: object) -> httpx.Response:
|
|
166
|
+
calls.append(f"-> {request.method} {request.url}")
|
|
167
|
+
response = func(request, **kwargs)
|
|
168
|
+
calls.append(f"<- {response.status_code}")
|
|
169
|
+
return response
|
|
170
|
+
|
|
171
|
+
return wrapper
|
|
172
|
+
|
|
173
|
+
return decorator
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
**Do not hand-roll retries, backoff, or circuit breakers here.** They are solved problems with dedicated libraries; check what the project already depends on and plug it in through this hook. Writing the retry loop yourself means reimplementing jitter, budgets, and idempotency rules — and getting them subtly wrong.
|
|
177
|
+
|
|
178
|
+
Annotation types live in `http_client.types`: `SyncSendMethod`, `AsyncSendMethod`, `SyncStreamRequestMethod`, `AsyncStreamRequestMethod` and the matching `*Decorator` aliases.
|
|
179
|
+
|
|
180
|
+
A `stream_request` decorator must itself be a context manager — put `@contextmanager` / `@asynccontextmanager` **below** `@wraps`:
|
|
181
|
+
|
|
182
|
+
```python
|
|
183
|
+
@wraps(func)
|
|
184
|
+
@contextmanager
|
|
185
|
+
def wrapper(request, **kwargs):
|
|
186
|
+
with func(request, **kwargs) as response:
|
|
187
|
+
yield response
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
## Streaming requests
|
|
191
|
+
|
|
192
|
+
```python
|
|
193
|
+
with client.stream("GET", "/large-file.zip") as response:
|
|
194
|
+
response.raise_for_status()
|
|
195
|
+
with open("file.zip", "wb") as f:
|
|
196
|
+
for chunk in response.iter_bytes(chunk_size=8192):
|
|
197
|
+
f.write(chunk)
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
```python
|
|
201
|
+
async with client.stream("GET", "/events") as response:
|
|
202
|
+
async for line in response.aiter_lines():
|
|
203
|
+
handle(line)
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
A streamed response body shows up in logs as `<streamed content>` — at the time the response hook fires the content has not been read yet. This is not an error.
|
|
207
|
+
|
|
208
|
+
## Logging
|
|
209
|
+
|
|
210
|
+
`with_logger` installs hooks that emit one record per request and one per response. The records are linked by the `id` field — an internal `trace_id` unrelated to any server-side tracing.
|
|
211
|
+
|
|
212
|
+
Common secrets — `authorization`, `cookie`, `x-api-key`, `password`, `token` and friends — are masked out of the box. `sanitize_keys` adds project-specific paths on top; it does not replace the defaults.
|
|
213
|
+
|
|
214
|
+
Masking is driven by glom paths applied to the body, headers, and query parameters. httpx lowercases header names, so write `"authorization"`, not `"Authorization"`.
|
|
215
|
+
|
|
216
|
+
```python
|
|
217
|
+
options.with_logger(
|
|
218
|
+
logger,
|
|
219
|
+
sanitize_keys=["authorization", "user.password", "items.*.token"],
|
|
220
|
+
)
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
Global defaults (level, JSON indent, truncation of long bodies) come from `http_client.configure_logging(...)`. `HTTP_CLIENT_*` environment variables **override** that function's arguments. Details and the full variable list are in `references/options.md`.
|
|
224
|
+
|
|
225
|
+
## Known pitfalls
|
|
226
|
+
|
|
227
|
+
Before debugging "strange" behaviour, read `references/pitfalls.md`. It covers `url_suffix` join rules, decorator ordering and freezing, Content-Type body filtering, and why options cannot touch the transport.
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
# Option catalog and configuration
|
|
2
|
+
|
|
3
|
+
All options live in `http_client.options`.
|
|
4
|
+
|
|
5
|
+
## Transport and connection
|
|
6
|
+
|
|
7
|
+
### `with_timeout(timeout: TimeoutTypes) -> ClientOption`
|
|
8
|
+
|
|
9
|
+
Client timeout. Accepts a number of seconds or an `httpx.Timeout`.
|
|
10
|
+
|
|
11
|
+
The default is `httpx.Timeout(60)`, i.e. 60 seconds for each phase (`connect`, `read`, `write`, `pool`).
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
from httpx import Timeout
|
|
15
|
+
|
|
16
|
+
options.with_timeout(Timeout(connect=5.0, read=30.0, write=5.0, pool=1.0))
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Precedence: an explicit `timeout=` on the call wins over the client timeout. Passing `timeout=None` on a call deliberately disables the timeout for that request.
|
|
20
|
+
|
|
21
|
+
### `with_follow_redirects(max_redirects: int = 20) -> ClientOption`
|
|
22
|
+
|
|
23
|
+
Enables redirect following and sets the limit. The default comes from `httpx._config.DEFAULT_MAX_REDIRECTS`.
|
|
24
|
+
|
|
25
|
+
Without this option the client does not follow redirects. Override per request with `client.get(url, follow_redirects=True)`.
|
|
26
|
+
|
|
27
|
+
### `with_verify_context(*, verify: ssl.SSLContext | str | bool) -> ClientOption`
|
|
28
|
+
|
|
29
|
+
TLS verification context. Accepts an `SSLContext`, a path to a CA bundle (converted to an `SSLContext` internally), or `False` to disable verification. Applies to both `HttpClient` and `AsyncHttpClient`.
|
|
30
|
+
|
|
31
|
+
⚠️ `False` disables certificate checking entirely — local debugging only, never production.
|
|
32
|
+
|
|
33
|
+
### `use_truststore() -> ClientOption`
|
|
34
|
+
|
|
35
|
+
Certificate verification through the system trust store. Requires the extra dependency:
|
|
36
|
+
|
|
37
|
+
```shell
|
|
38
|
+
pip install "cloudru-qa-http-client[truststore]"
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Without `truststore` installed it raises `ImportError` with a hint. Internally it calls `with_verify_context`.
|
|
42
|
+
|
|
43
|
+
## Authentication
|
|
44
|
+
|
|
45
|
+
### `with_auth(auth: AuthTypes) -> ClientOption`
|
|
46
|
+
|
|
47
|
+
Any httpx authentication mechanism: `BasicAuth`, `DigestAuth`, a callable, or your own `httpx.Auth` subclass.
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
from httpx import BasicAuth
|
|
51
|
+
|
|
52
|
+
options.with_auth(BasicAuth("user", "password"))
|
|
53
|
+
options.with_auth(lambda request: request.headers.update({"Authorization": f"Bearer {token}"}))
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Override for a single request: `client.get(url, auth=other_auth)`.
|
|
57
|
+
Disable authentication entirely for a request: `client.get(url, anonymous=True)` — `auth` is then not applied at all, not even one passed explicitly. Other per-call arguments such as `follow_redirects` still apply.
|
|
58
|
+
|
|
59
|
+
## Headers
|
|
60
|
+
|
|
61
|
+
### `with_default_headers(headers: dict[str, str]) -> ClientOption`
|
|
62
|
+
|
|
63
|
+
Adds a hook that fills in each header only when the request does not already carry it. A value passed per request wins over the default, matching `httpx` semantics.
|
|
64
|
+
|
|
65
|
+
### `with_autogenerated_request_id() -> ClientOption`
|
|
66
|
+
|
|
67
|
+
An `X-Request-ID` header carrying a random UUID4 per request. The hook is inserted at the **front** of the list, so the identifier is visible to later hooks, including the logging one.
|
|
68
|
+
|
|
69
|
+
### `with_autogenerated_traceparent() -> ClientOption`
|
|
70
|
+
|
|
71
|
+
A `Traceparent` header in W3C Trace Context format: `00-<32 hex>-<16 hex>-01`. Also inserted at the front of the list.
|
|
72
|
+
|
|
73
|
+
This is standalone generation, not an OpenTelemetry integration: no context is picked up from the current span.
|
|
74
|
+
|
|
75
|
+
## Event hooks
|
|
76
|
+
|
|
77
|
+
### `with_request_hook(hook: EventHook) -> ClientOption`
|
|
78
|
+
### `with_response_hook(hook: EventHook) -> ClientOption`
|
|
79
|
+
|
|
80
|
+
Append a hook to the corresponding list. The contract matches [httpx event hooks](https://www.python-httpx.org/advanced/event-hooks/): the hook receives a `Request` (or `Response`) and its return value is ignored. Mutate the object in place.
|
|
81
|
+
|
|
82
|
+
```python
|
|
83
|
+
def add_tenant(request: httpx.Request) -> None:
|
|
84
|
+
request.headers["X-Tenant"] = "acme"
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
For `AsyncHttpClient`, synchronous hooks are wrapped into coroutines during `__init__`, so the same set of options works for both clients. Native async hooks are accepted too; call order is preserved regardless of mixing.
|
|
88
|
+
|
|
89
|
+
## Transport decorators
|
|
90
|
+
|
|
91
|
+
### `with_send_decorator(decorator: SendDecorator) -> ClientOption`
|
|
92
|
+
### `with_stream_decorator(decorator: StreamRequestDecorator) -> ClientOption`
|
|
93
|
+
|
|
94
|
+
Wrap `_send` and `_stream_request` respectively. Composition happens once, in `__init__`:
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
for decorator in decorators:
|
|
98
|
+
func = decorator(func)
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
Consequences:
|
|
102
|
+
|
|
103
|
+
- The last decorator added becomes the outermost.
|
|
104
|
+
- Register decorators only in constructor options; late registration raises `RuntimeError`.
|
|
105
|
+
- For `AsyncHttpClient` the decorator must be async — there is no auto-wrapping, unlike event hooks.
|
|
106
|
+
|
|
107
|
+
Protocol types for annotations are in `http_client.types`.
|
|
108
|
+
|
|
109
|
+
## Logging
|
|
110
|
+
|
|
111
|
+
### `with_logger(logger, *, sanitize_keys=None, json_indent=None, use_line_breaks=None, log_level=None, use_default_sanitize_keys=True) -> ClientOption`
|
|
112
|
+
|
|
113
|
+
| Parameter | Type | Meaning |
|
|
114
|
+
|---|---|---|
|
|
115
|
+
| `logger` | `logging.Logger` | where to write |
|
|
116
|
+
| `sanitize_keys` | `Sequence[str] \| None` | glom paths to fields replaced with `****` |
|
|
117
|
+
| `use_default_sanitize_keys` | `bool` | also mask the built-in secret list (default `True`) |
|
|
118
|
+
| `json_indent` | `int \| None` | indent used when serializing JSON parts of the record |
|
|
119
|
+
| `use_line_breaks` | `bool` | newlines between record parts instead of spaces |
|
|
120
|
+
| `log_level` | `int \| None` | record level, defaults to `INFO` |
|
|
121
|
+
|
|
122
|
+
Record format:
|
|
123
|
+
|
|
124
|
+
```
|
|
125
|
+
Request: id=<uuid> Method: [GET] https://host/path QueryParams: {...} Headers: {...} Body: {...}
|
|
126
|
+
Response: id=<uuid> Status: 200 [OK] Headers: {...} Body: {...}
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
`id` is an internal identifier linking a request to its response. It is stored in `request.extensions["trace_id"]` and has nothing to do with server-side tracing.
|
|
130
|
+
|
|
131
|
+
Bodies are rendered by `Content-Type`:
|
|
132
|
+
|
|
133
|
+
| `Content-Type` | `Body:` shows |
|
|
134
|
+
|---|---|
|
|
135
|
+
| `application/json` | the parsed, masked, re-serialized body |
|
|
136
|
+
| `text/plain` | the body as is |
|
|
137
|
+
| `application/octet-stream` | the decoded body, or `<binary content (N bytes)>` if it is not text |
|
|
138
|
+
| anything else | `<not logged, content-type: ...>` |
|
|
139
|
+
| absent (no body) | nothing — the `Body:` part is omitted |
|
|
140
|
+
|
|
141
|
+
So an omitted `Body:` means there was no body, while `<not logged, ...>` means there was one and the type is not rendered.
|
|
142
|
+
|
|
143
|
+
A parsing failure in any part never breaks the request — the log gets `<Error parse: ExceptionType>` instead. Only the exception class is recorded: its message could carry fragments of the body or URL.
|
|
144
|
+
|
|
145
|
+
### Masking
|
|
146
|
+
|
|
147
|
+
A built-in list of common secrets is masked by default — `authorization`, `proxy-authorization`, `cookie`, `set-cookie`, `x-api-key`, `api-key`, `api_key`, `access_token`, `refresh_token`, `password`, `secret`, `token` (`event_hooks.DEFAULT_SANITIZE_KEYS`). Anything in `sanitize_keys` is added on top. Turn the defaults off only with `use_default_sanitize_keys=False`.
|
|
148
|
+
|
|
149
|
+
Masking covers the access-log records this library writes — not `httpx` exceptions, which may carry the full URL including query. Do not put secrets in URLs.
|
|
150
|
+
|
|
151
|
+
`sanitize_keys` is applied to headers, query parameters, and the parsed JSON body — independently, each path is looked up in all three. A path that does not match is silently skipped.
|
|
152
|
+
|
|
153
|
+
Syntax is [glom](https://glom.readthedocs.io/en/latest/):
|
|
154
|
+
|
|
155
|
+
| Path | What it masks |
|
|
156
|
+
|---|---|
|
|
157
|
+
| `authorization` | the `Authorization` header (httpx lowercases names) |
|
|
158
|
+
| `user.password` | a nested object field |
|
|
159
|
+
| `items.*.token` | a field inside every array element |
|
|
160
|
+
| `*.credentials.secret` | a field when the body itself is an array of objects |
|
|
161
|
+
|
|
162
|
+
### `configure_logging(...)` — global defaults
|
|
163
|
+
|
|
164
|
+
```python
|
|
165
|
+
from http_client import configure_logging
|
|
166
|
+
from http_client.config import LoggingConfig
|
|
167
|
+
|
|
168
|
+
configure_logging(
|
|
169
|
+
options=LoggingConfig(
|
|
170
|
+
log_level=logging.INFO,
|
|
171
|
+
json_indent=None,
|
|
172
|
+
use_line_breaks=False,
|
|
173
|
+
octet_stream_log_maxlength=1024,
|
|
174
|
+
plain_text_log_maxlength=None,
|
|
175
|
+
json_log_maxlength=None,
|
|
176
|
+
)
|
|
177
|
+
)
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
Pass a `LoggingConfig` through `options=...`. Its fields set the defaults.
|
|
181
|
+
The function writes to the module-level singleton `LOGGING_CONFIG`, from which the hooks read whenever the corresponding `with_logger` argument was not supplied.
|
|
182
|
+
|
|
183
|
+
**Environment variables override the function arguments**, not the other way round:
|
|
184
|
+
|
|
185
|
+
| Variable | Field |
|
|
186
|
+
|---|---|
|
|
187
|
+
| `HTTP_CLIENT_LOG_LEVEL` | `log_level` (integer) |
|
|
188
|
+
| `HTTP_CLIENT_USE_LINE_BREAKS` | `use_line_breaks` (`true`/`y`/`yes`/`on`) |
|
|
189
|
+
| `HTTP_CLIENT_JSON_INDENT` | `json_indent` |
|
|
190
|
+
| `HTTP_CLIENT_OCTET_STREAM_LOG_MAXLENGTH` | `octet_stream_log_maxlength` |
|
|
191
|
+
| `HTTP_CLIENT_PLAIN_TEXT_LOG_MAXLENGTH` | `plain_text_log_maxlength` |
|
|
192
|
+
| `HTTP_CLIENT_JSON_LOG_MAXLENGTH` | `json_log_maxlength` |
|
|
193
|
+
|
|
194
|
+
The length limits (`*_maxlength`) trim the middle of the string, keeping the head and tail and inserting `...`. They can only be set globally; `with_logger` does not accept them.
|
|
195
|
+
|
|
196
|
+
## Utilities
|
|
197
|
+
|
|
198
|
+
`http_client.utils.sanitizer.sanitize(value, sensitive_keys)` — masks a dict or list using the same glom paths. Returns a deep copy and leaves the original untouched.
|
|
199
|
+
|
|
200
|
+
`http_client.utils.traceparent.generate()` — a traceparent string.
|
|
201
|
+
|
|
202
|
+
`http_client.utils.logutils.create_request_log` / `create_response_log` — build the same log strings manually.
|
|
203
|
+
|
|
204
|
+
`http_client.utils.logutils` also exports the building blocks those two are made of, so a logger built
|
|
205
|
+
on a different backend renders bodies exactly the same way: `to_json`, `trim`, `decode`, `is_streamed`,
|
|
206
|
+
`is_buffered`, `parse_error`. These helpers are part of the public API.
|
|
207
|
+
|
|
208
|
+
## Inherited client attributes
|
|
209
|
+
|
|
210
|
+
| Attribute | Where it is set | Purpose |
|
|
211
|
+
|---|---|---|
|
|
212
|
+
| `DEFAULT_URL_SUFFIX` | overridden in the subclass | path prefix injected by the `endpoint()` method |
|
|
213
|
+
| `DEFAULT_TIMEOUT` | overridden in the subclass | default timeout, `httpx.Timeout(60)` |
|
|
214
|
+
| `base_url` | from the constructor | proxies `self.client.base_url` |
|
|
215
|
+
| `client` | created in `__init__` | the underlying `httpx.Client` / `httpx.AsyncClient` |
|
|
216
|
+
|
|
217
|
+
Lifecycle mirrors `httpx` exactly: the connection pool is built in the constructor, `__enter__` / `__aenter__` open it, and `__exit__` / `__aexit__` close it. `HttpClient.close()` and `AsyncHttpClient.aclose()` do the same for a client not used as a context manager — the naming follows `httpx`, so the async client has `aclose()` only. A closed client cannot be reopened; doing so raises `RuntimeError`.
|
|
218
|
+
|
|
219
|
+
`endpoint(path)` joins `url_suffix` with `path`. Leading slashes on `path` and a missing trailing slash on the suffix are both normalized, so `"/u-api/orders/v1"` and `"/u-api/orders/v1/"` behave identically. It accepts relative paths only: an absolute URL or a `..` segment raises `ValueError`.
|