httpx2 2.11.0__tar.gz → 2.13.0__tar.gz

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.
Files changed (37) hide show
  1. {httpx2-2.11.0 → httpx2-2.13.0}/CHANGELOG.md +27 -0
  2. {httpx2-2.11.0 → httpx2-2.13.0}/PKG-INFO +24 -28
  3. {httpx2-2.11.0 → httpx2-2.13.0}/README.md +12 -11
  4. {httpx2-2.11.0 → httpx2-2.13.0}/httpx2/__init__.py +54 -40
  5. {httpx2-2.11.0 → httpx2-2.13.0}/httpx2/_api.py +1 -1
  6. {httpx2-2.11.0 → httpx2-2.13.0}/httpx2/_client.py +15 -10
  7. {httpx2-2.11.0 → httpx2-2.13.0}/httpx2/_config.py +6 -35
  8. {httpx2-2.11.0 → httpx2-2.13.0}/httpx2/_content.py +10 -4
  9. {httpx2-2.11.0 → httpx2-2.13.0}/httpx2/_decoders.py +103 -62
  10. {httpx2-2.11.0 → httpx2-2.13.0}/httpx2/_main.py +3 -5
  11. {httpx2-2.11.0 → httpx2-2.13.0}/httpx2/_models.py +41 -33
  12. {httpx2-2.11.0 → httpx2-2.13.0}/httpx2/websockets/_exceptions.py +1 -1
  13. {httpx2-2.11.0 → httpx2-2.13.0}/pyproject.toml +3 -3
  14. {httpx2-2.11.0 → httpx2-2.13.0}/.gitignore +0 -0
  15. {httpx2-2.11.0 → httpx2-2.13.0}/LICENSE.md +0 -0
  16. {httpx2-2.11.0 → httpx2-2.13.0}/httpx2/__version__.py +0 -0
  17. {httpx2-2.11.0 → httpx2-2.13.0}/httpx2/_alias.py +0 -0
  18. {httpx2-2.11.0 → httpx2-2.13.0}/httpx2/_auth.py +0 -0
  19. {httpx2-2.11.0 → httpx2-2.13.0}/httpx2/_exceptions.py +0 -0
  20. {httpx2-2.11.0 → httpx2-2.13.0}/httpx2/_multipart.py +0 -0
  21. {httpx2-2.11.0 → httpx2-2.13.0}/httpx2/_sse.py +0 -0
  22. {httpx2-2.11.0 → httpx2-2.13.0}/httpx2/_status_codes.py +0 -0
  23. {httpx2-2.11.0 → httpx2-2.13.0}/httpx2/_transports/__init__.py +0 -0
  24. {httpx2-2.11.0 → httpx2-2.13.0}/httpx2/_transports/asgi.py +0 -0
  25. {httpx2-2.11.0 → httpx2-2.13.0}/httpx2/_transports/base.py +0 -0
  26. {httpx2-2.11.0 → httpx2-2.13.0}/httpx2/_transports/default.py +0 -0
  27. {httpx2-2.11.0 → httpx2-2.13.0}/httpx2/_transports/mock.py +0 -0
  28. {httpx2-2.11.0 → httpx2-2.13.0}/httpx2/_transports/wsgi.py +0 -0
  29. {httpx2-2.11.0 → httpx2-2.13.0}/httpx2/_types.py +0 -0
  30. {httpx2-2.11.0 → httpx2-2.13.0}/httpx2/_urlparse.py +0 -0
  31. {httpx2-2.11.0 → httpx2-2.13.0}/httpx2/_urls.py +0 -0
  32. {httpx2-2.11.0 → httpx2-2.13.0}/httpx2/_utils.py +0 -0
  33. {httpx2-2.11.0 → httpx2-2.13.0}/httpx2/py.typed +0 -0
  34. {httpx2-2.11.0 → httpx2-2.13.0}/httpx2/websockets/__init__.py +0 -0
  35. {httpx2-2.11.0 → httpx2-2.13.0}/httpx2/websockets/_api.py +0 -0
  36. {httpx2-2.11.0 → httpx2-2.13.0}/httpx2/websockets/_ping.py +0 -0
  37. {httpx2-2.11.0 → httpx2-2.13.0}/httpx2/websockets/_transport.py +0 -0
@@ -4,6 +4,33 @@ All notable changes to this project will be documented in this file.
4
4
 
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
6
6
 
7
+ ## 2.13.0 (September 14th, 2026)
8
+
9
+ ### Changed
10
+
11
+ * Require `brotlicffi` 1.2.0.2 or later for the `brotli` extra on non-CPython implementations.
12
+ ([#1179](https://github.com/pydantic/httpx2/pull/1179))
13
+
14
+ ### Fixed
15
+
16
+ * Make the `--no-verify` CLI flag disable TLS certificate verification and add an explicit `--verify` counterpart.
17
+ ([#1140](https://github.com/pydantic/httpx2/pull/1140),
18
+ [#1186](https://github.com/pydantic/httpx2/pull/1186))
19
+ * Avoid nested async generator finalization errors when streamed responses are abandoned early.
20
+ ([#1204](https://github.com/pydantic/httpx2/pull/1204))
21
+
22
+ ## 2.12.0 (August 18th, 2026)
23
+
24
+ ### Changed
25
+
26
+ * Use `backports.zstd` for Zstandard decoding on Python 3.13 and earlier.
27
+ ([#1146](https://github.com/pydantic/httpx2/pull/1146))
28
+
29
+ ### Fixed
30
+
31
+ * Bound peak memory while streaming compressed responses and close response streams when decoding fails.
32
+ ([#1126](https://github.com/pydantic/httpx2/pull/1126))
33
+
7
34
  ## 2.11.0 (August 18th, 2026)
8
35
 
9
36
  ### Added
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: httpx2
3
- Version: 2.11.0
3
+ Version: 2.13.0
4
4
  Summary: The next generation HTTP client.
5
5
  Project-URL: Changelog, https://github.com/pydantic/httpx2/blob/main/src/httpx2/CHANGELOG.md
6
6
  Project-URL: Homepage, https://github.com/pydantic/httpx2
@@ -27,14 +27,14 @@ Classifier: Programming Language :: Python :: 3.15
27
27
  Classifier: Topic :: Internet :: WWW/HTTP
28
28
  Requires-Python: >=3.10
29
29
  Requires-Dist: anyio>=4.10; sys_platform != 'emscripten'
30
- Requires-Dist: httpcore2==2.11.0; sys_platform != 'emscripten'
30
+ Requires-Dist: httpcore2==2.13.0; sys_platform != 'emscripten'
31
31
  Requires-Dist: httpx2-jsfetch; sys_platform == 'emscripten' and python_version >= '3.12'
32
32
  Requires-Dist: idna>=3.18
33
33
  Requires-Dist: truststore>=0.10; sys_platform != 'emscripten'
34
34
  Requires-Dist: typing-extensions>=4.5.0; python_version < '3.13'
35
35
  Provides-Extra: brotli
36
36
  Requires-Dist: brotli>=1.2.0; (platform_python_implementation == 'CPython') and extra == 'brotli'
37
- Requires-Dist: brotlicffi>=1.2.0.0; (platform_python_implementation != 'CPython') and extra == 'brotli'
37
+ Requires-Dist: brotlicffi>=1.2.0.2; (platform_python_implementation != 'CPython') and extra == 'brotli'
38
38
  Provides-Extra: cli
39
39
  Requires-Dist: click>=8.4.2; extra == 'cli'
40
40
  Requires-Dist: pygments==2.*; extra == 'cli'
@@ -46,7 +46,7 @@ Requires-Dist: socksio==1.*; extra == 'socks'
46
46
  Provides-Extra: ws
47
47
  Requires-Dist: wsproto>=1.2; extra == 'ws'
48
48
  Provides-Extra: zstd
49
- Requires-Dist: zstandard>=0.18.0; (python_version <= '3.13') and extra == 'zstd'
49
+ Requires-Dist: backports-zstd>=1.0.0; (python_version <= '3.13') and extra == 'zstd'
50
50
  Description-Content-Type: text/markdown
51
51
 
52
52
  <h1 align="center">HTTPX2</h1>
@@ -56,6 +56,7 @@ Description-Content-Type: text/markdown
56
56
  <p align="center">
57
57
  <a href="https://github.com/pydantic/httpx2/actions"><img src="https://github.com/pydantic/httpx2/workflows/Test%20Suite/badge.svg" alt="Test Suite"></a>
58
58
  <a href="https://pypi.org/project/httpx2/"><img src="https://badge.fury.io/py/httpx2.svg" alt="Package version"></a>
59
+ <a href="https://pydantic.dev/docs/logfire/join-slack/"><img src="https://img.shields.io/badge/Slack-Join%20Slack-4A154B?logo=slack" alt="Join Slack"></a>
59
60
  </p>
60
61
 
61
62
  HTTPX2 is a fully featured HTTP client library for Python. It includes **an integrated command line client**, has support for both **HTTP/1.1 and HTTP/2**, and provides both **sync and async APIs**.
@@ -104,11 +105,11 @@ httpx2 --help
104
105
 
105
106
  HTTPX2 builds on the well-established usability of `requests`, and gives you:
106
107
 
107
- * A broadly [requests-compatible API](https://httpx2.pydantic.dev/compatibility/).
108
+ * A broadly [requests-compatible API](https://pydantic.dev/docs/httpx2/guides/compatibility/).
108
109
  * An integrated command-line client.
109
- * HTTP/1.1 [and HTTP/2 support](https://httpx2.pydantic.dev/http2/).
110
- * Standard synchronous interface, but with [async support if you need it](https://httpx2.pydantic.dev/async/).
111
- * Ability to make requests directly to [WSGI applications](https://httpx2.pydantic.dev/advanced/transports/#wsgi-transport) or [ASGI applications](https://httpx2.pydantic.dev/advanced/transports/#asgi-transport).
110
+ * HTTP/1.1 [and HTTP/2 support](https://pydantic.dev/docs/httpx2/guides/http2/).
111
+ * Standard synchronous interface, but with [async support if you need it](https://pydantic.dev/docs/httpx2/guides/async/).
112
+ * Ability to make requests directly to [WSGI applications](https://pydantic.dev/docs/httpx2/advanced/transports/#wsgi-transport) or [ASGI applications](https://pydantic.dev/docs/httpx2/advanced/transports/#asgi-transport).
112
113
  * Strict timeouts everywhere.
113
114
  * Fully type annotated.
114
115
  * 100% test coverage.
@@ -147,15 +148,15 @@ pip install httpx2[http2]
147
148
 
148
149
  ## Documentation
149
150
 
150
- Project documentation is available at [https://httpx2.pydantic.dev/](https://httpx2.pydantic.dev/).
151
+ Project documentation is available at [https://pydantic.dev/docs/httpx2/](https://pydantic.dev/docs/httpx2/).
151
152
 
152
- For a run-through of all the basics, head over to the [QuickStart](https://httpx2.pydantic.dev/quickstart/).
153
+ For a run-through of all the basics, head over to the [QuickStart](https://pydantic.dev/docs/httpx2/get-started/quickstart/).
153
154
 
154
- For more advanced topics, see the [Advanced Usage](https://httpx2.pydantic.dev/advanced/) section, the [async support](https://httpx2.pydantic.dev/async/) section, or the [HTTP/2](https://httpx2.pydantic.dev/http2/) section.
155
+ For more advanced topics, see the [Advanced Usage](https://pydantic.dev/docs/httpx2/advanced/clients/) section, the [async support](https://pydantic.dev/docs/httpx2/guides/async/) section, or the [HTTP/2](https://pydantic.dev/docs/httpx2/guides/http2/) section.
155
156
 
156
- The [Developer Interface](https://httpx2.pydantic.dev/api/) provides a comprehensive API reference.
157
+ The [Developer Interface](https://pydantic.dev/docs/httpx2/api/api/) provides a comprehensive API reference.
157
158
 
158
- To find out about tools that integrate with HTTPX, see [Third Party Packages](https://httpx2.pydantic.dev/third_party_packages/).
159
+ To find out about tools that integrate with HTTPX, see [Third Party Packages](https://pydantic.dev/docs/httpx2/community/third_party_packages/).
159
160
 
160
161
  ## Observability with Pydantic Logfire
161
162
 
@@ -181,7 +182,7 @@ This works the same way for explicit `httpx2.Client()` and `httpx2.AsyncClient()
181
182
 
182
183
  ## Contribute
183
184
 
184
- If you want to contribute with HTTPX2 check out the [Contributing Guide](https://httpx2.pydantic.dev/contributing/) to learn how to start.
185
+ If you want to contribute with HTTPX2 check out the [Contributing Guide](https://pydantic.dev/docs/httpx2/community/contributing/) to learn how to start.
185
186
 
186
187
  ## Dependencies
187
188
 
@@ -200,7 +201,7 @@ As well as these optional installs:
200
201
  * `rich` - Rich terminal support. *(Optional, with `httpx2[cli]`)*
201
202
  * `click` - Command line client support. *(Optional, with `httpx2[cli]`)*
202
203
  * `brotli` or `brotlicffi` - Decoding for "brotli" compressed responses. *(Optional, with `httpx2[brotli]`)*
203
- * `zstandard` - Decoding for "zstd" compressed responses on Python 3.13 and below. *(Optional, with `httpx2[zstd]`. On Python 3.14+, `zstd` is supported via the stdlib [`compression.zstd`](https://docs.python.org/3/library/compression.zstd.html) module when it is available; the `httpx2[zstd]` extra installs nothing there, so decoding falls back to `zstandard` only on 3.13 and below.)*
204
+ * `backports.zstd` - Decoding for "zstd" compressed responses on Python 3.13 and below. *(Optional, with `httpx2[zstd]`. On Python 3.14+, `zstd` is supported via the stdlib [`compression.zstd`](https://docs.python.org/3/library/compression.zstd.html) module when it is available, and the `httpx2[zstd]` extra installs nothing.)*
204
205
 
205
206
  A huge amount of credit is due to `requests` for the API layout that
206
207
  much of this work follows, as well as to `urllib3` for plenty of design
@@ -212,25 +213,20 @@ inspiration around the lower-level networking details.
212
213
 
213
214
  ## Release Information
214
215
 
215
- ## 2.11.0 (August 18th, 2026)
216
-
217
- ### Added
218
-
219
- * Add the public `Origin` value object and `URL.origin` property for normalized,
220
- hashable origin comparisons. ([#1134](https://github.com/pydantic/httpx2/pull/1134))
216
+ ## 2.13.0 (September 14th, 2026)
221
217
 
222
218
  ### Changed
223
219
 
224
- * Require Brotli 1.2.0 or later for the `brotli` extra. ([#1141](https://github.com/pydantic/httpx2/pull/1141))
220
+ * Require `brotlicffi` 1.2.0.2 or later for the `brotli` extra on non-CPython implementations.
221
+ ([#1179](https://github.com/pydantic/httpx2/pull/1179))
225
222
 
226
223
  ### Fixed
227
224
 
228
- * Restore deprecated status code aliases. ([#1135](https://github.com/pydantic/httpx2/pull/1135))
229
- * Extract HTTP/2 release notes from changelog headings correctly. ([#1136](https://github.com/pydantic/httpx2/pull/1136))
230
- * Respect explicit `Transfer-Encoding` headers and expose buffered request body lengths to WSGI applications.
231
- ([#1137](https://github.com/pydantic/httpx2/pull/1137))
232
- * Validate multipart part header names and values before serialization.
233
- ([#1142](https://github.com/pydantic/httpx2/pull/1142))
225
+ * Make the `--no-verify` CLI flag disable TLS certificate verification and add an explicit `--verify` counterpart.
226
+ ([#1140](https://github.com/pydantic/httpx2/pull/1140),
227
+ [#1186](https://github.com/pydantic/httpx2/pull/1186))
228
+ * Avoid nested async generator finalization errors when streamed responses are abandoned early.
229
+ ([#1204](https://github.com/pydantic/httpx2/pull/1204))
234
230
 
235
231
  ---
236
232
 
@@ -5,6 +5,7 @@
5
5
  <p align="center">
6
6
  <a href="https://github.com/pydantic/httpx2/actions"><img src="https://github.com/pydantic/httpx2/workflows/Test%20Suite/badge.svg" alt="Test Suite"></a>
7
7
  <a href="https://pypi.org/project/httpx2/"><img src="https://badge.fury.io/py/httpx2.svg" alt="Package version"></a>
8
+ <a href="https://pydantic.dev/docs/logfire/join-slack/"><img src="https://img.shields.io/badge/Slack-Join%20Slack-4A154B?logo=slack" alt="Join Slack"></a>
8
9
  </p>
9
10
 
10
11
  HTTPX2 is a fully featured HTTP client library for Python. It includes **an integrated command line client**, has support for both **HTTP/1.1 and HTTP/2**, and provides both **sync and async APIs**.
@@ -53,11 +54,11 @@ httpx2 --help
53
54
 
54
55
  HTTPX2 builds on the well-established usability of `requests`, and gives you:
55
56
 
56
- * A broadly [requests-compatible API](https://httpx2.pydantic.dev/compatibility/).
57
+ * A broadly [requests-compatible API](https://pydantic.dev/docs/httpx2/guides/compatibility/).
57
58
  * An integrated command-line client.
58
- * HTTP/1.1 [and HTTP/2 support](https://httpx2.pydantic.dev/http2/).
59
- * Standard synchronous interface, but with [async support if you need it](https://httpx2.pydantic.dev/async/).
60
- * Ability to make requests directly to [WSGI applications](https://httpx2.pydantic.dev/advanced/transports/#wsgi-transport) or [ASGI applications](https://httpx2.pydantic.dev/advanced/transports/#asgi-transport).
59
+ * HTTP/1.1 [and HTTP/2 support](https://pydantic.dev/docs/httpx2/guides/http2/).
60
+ * Standard synchronous interface, but with [async support if you need it](https://pydantic.dev/docs/httpx2/guides/async/).
61
+ * Ability to make requests directly to [WSGI applications](https://pydantic.dev/docs/httpx2/advanced/transports/#wsgi-transport) or [ASGI applications](https://pydantic.dev/docs/httpx2/advanced/transports/#asgi-transport).
61
62
  * Strict timeouts everywhere.
62
63
  * Fully type annotated.
63
64
  * 100% test coverage.
@@ -96,15 +97,15 @@ pip install httpx2[http2]
96
97
 
97
98
  ## Documentation
98
99
 
99
- Project documentation is available at [https://httpx2.pydantic.dev/](https://httpx2.pydantic.dev/).
100
+ Project documentation is available at [https://pydantic.dev/docs/httpx2/](https://pydantic.dev/docs/httpx2/).
100
101
 
101
- For a run-through of all the basics, head over to the [QuickStart](https://httpx2.pydantic.dev/quickstart/).
102
+ For a run-through of all the basics, head over to the [QuickStart](https://pydantic.dev/docs/httpx2/get-started/quickstart/).
102
103
 
103
- For more advanced topics, see the [Advanced Usage](https://httpx2.pydantic.dev/advanced/) section, the [async support](https://httpx2.pydantic.dev/async/) section, or the [HTTP/2](https://httpx2.pydantic.dev/http2/) section.
104
+ For more advanced topics, see the [Advanced Usage](https://pydantic.dev/docs/httpx2/advanced/clients/) section, the [async support](https://pydantic.dev/docs/httpx2/guides/async/) section, or the [HTTP/2](https://pydantic.dev/docs/httpx2/guides/http2/) section.
104
105
 
105
- The [Developer Interface](https://httpx2.pydantic.dev/api/) provides a comprehensive API reference.
106
+ The [Developer Interface](https://pydantic.dev/docs/httpx2/api/api/) provides a comprehensive API reference.
106
107
 
107
- To find out about tools that integrate with HTTPX, see [Third Party Packages](https://httpx2.pydantic.dev/third_party_packages/).
108
+ To find out about tools that integrate with HTTPX, see [Third Party Packages](https://pydantic.dev/docs/httpx2/community/third_party_packages/).
108
109
 
109
110
  ## Observability with Pydantic Logfire
110
111
 
@@ -130,7 +131,7 @@ This works the same way for explicit `httpx2.Client()` and `httpx2.AsyncClient()
130
131
 
131
132
  ## Contribute
132
133
 
133
- If you want to contribute with HTTPX2 check out the [Contributing Guide](https://httpx2.pydantic.dev/contributing/) to learn how to start.
134
+ If you want to contribute with HTTPX2 check out the [Contributing Guide](https://pydantic.dev/docs/httpx2/community/contributing/) to learn how to start.
134
135
 
135
136
  ## Dependencies
136
137
 
@@ -149,7 +150,7 @@ As well as these optional installs:
149
150
  * `rich` - Rich terminal support. *(Optional, with `httpx2[cli]`)*
150
151
  * `click` - Command line client support. *(Optional, with `httpx2[cli]`)*
151
152
  * `brotli` or `brotlicffi` - Decoding for "brotli" compressed responses. *(Optional, with `httpx2[brotli]`)*
152
- * `zstandard` - Decoding for "zstd" compressed responses on Python 3.13 and below. *(Optional, with `httpx2[zstd]`. On Python 3.14+, `zstd` is supported via the stdlib [`compression.zstd`](https://docs.python.org/3/library/compression.zstd.html) module when it is available; the `httpx2[zstd]` extra installs nothing there, so decoding falls back to `zstandard` only on 3.13 and below.)*
153
+ * `backports.zstd` - Decoding for "zstd" compressed responses on Python 3.13 and below. *(Optional, with `httpx2[zstd]`. On Python 3.14+, `zstd` is supported via the stdlib [`compression.zstd`](https://docs.python.org/3/library/compression.zstd.html) module when it is available, and the `httpx2[zstd]` extra installs nothing.)*
153
154
 
154
155
  A huge amount of credit is due to `requests` for the API layout that
155
156
  much of this work follows, as well as to `urllib3` for plenty of design
@@ -14,82 +14,96 @@ from ._types import *
14
14
  from ._urls import *
15
15
 
16
16
  __all__ = [
17
+ # __version__.py
17
18
  "__description__",
18
19
  "__title__",
19
20
  "__version__",
21
+ # _alias.py
20
22
  "alias_httpx",
21
- "ASGITransport",
22
- "AsyncBaseTransport",
23
- "AsyncByteStream",
24
- "AsyncClient",
25
- "AsyncHTTPTransport",
23
+ # _api.py
24
+ "delete",
25
+ "get",
26
+ "head",
27
+ "options",
28
+ "patch",
29
+ "post",
30
+ "put",
31
+ "query",
32
+ "request",
33
+ "stream",
34
+ "websocket",
35
+ # _auth.py
26
36
  "Auth",
27
- "BaseTransport",
28
37
  "BasicAuth",
29
- "ByteStream",
38
+ "DigestAuth",
39
+ "FunctionAuth",
40
+ "NetRCAuth",
41
+ # _client.py
42
+ "AsyncClient",
30
43
  "Client",
44
+ "USE_CLIENT_DEFAULT",
45
+ # _config.py
46
+ "create_ssl_context",
47
+ "Limits",
48
+ "Proxy",
49
+ "Timeout",
50
+ # _content.py
51
+ "ByteStream",
52
+ # _exceptions.py
31
53
  "CloseError",
32
- "codes",
33
54
  "ConnectError",
34
55
  "ConnectTimeout",
35
56
  "CookieConflict",
36
- "Cookies",
37
- "create_ssl_context",
38
57
  "DecodingError",
39
- "delete",
40
- "DigestAuth",
41
- "EventSource",
42
- "FunctionAuth",
43
- "get",
44
- "head",
45
- "Headers",
46
58
  "HTTPError",
47
59
  "HTTPStatusError",
48
- "HTTPTransport",
49
60
  "InvalidURL",
50
- "Limits",
51
61
  "LocalProtocolError",
52
- "MockTransport",
53
- "NetRCAuth",
54
62
  "NetworkError",
55
- "options",
56
- "Origin",
57
- "patch",
58
63
  "PoolTimeout",
59
- "post",
60
64
  "ProtocolError",
61
- "Proxy",
62
65
  "ProxyError",
63
- "put",
64
- "query",
65
- "QueryParams",
66
66
  "ReadError",
67
67
  "ReadTimeout",
68
68
  "RemoteProtocolError",
69
- "request",
70
- "Request",
71
69
  "RequestError",
72
70
  "RequestNotRead",
73
- "Response",
74
71
  "ResponseNotRead",
75
- "ServerSentEvent",
76
- "SSEError",
77
- "stream",
78
72
  "StreamClosed",
79
73
  "StreamConsumed",
80
74
  "StreamError",
81
- "SyncByteStream",
82
- "Timeout",
83
75
  "TimeoutException",
84
76
  "TooManyRedirects",
85
77
  "TransportError",
86
78
  "UnsupportedProtocol",
87
- "URL",
88
- "USE_CLIENT_DEFAULT",
89
- "websocket",
90
79
  "WriteError",
91
80
  "WriteTimeout",
81
+ # _models.py
82
+ "Cookies",
83
+ "Headers",
84
+ "Request",
85
+ "Response",
86
+ # _sse.py
87
+ "EventSource",
88
+ "ServerSentEvent",
89
+ "SSEError",
90
+ # _status_codes.py
91
+ "codes",
92
+ # _transports
93
+ "ASGITransport",
94
+ "AsyncBaseTransport",
95
+ "AsyncHTTPTransport",
96
+ "BaseTransport",
97
+ "HTTPTransport",
98
+ "MockTransport",
92
99
  "WSGITransport",
100
+ # _types.py
101
+ "AsyncByteStream",
102
+ "SyncByteStream",
103
+ # _urls.py
104
+ "Origin",
105
+ "QueryParams",
106
+ "URL",
93
107
  ]
94
108
 
95
109
 
@@ -146,7 +146,7 @@ def stream(
146
146
 
147
147
  See also: [Streaming Responses][0]
148
148
 
149
- [0]: /quickstart#streaming-responses
149
+ [0]: quickstart.md#streaming-responses
150
150
  """
151
151
  with Client(
152
152
  cookies=cookies,
@@ -160,8 +160,13 @@ class BoundAsyncStream(AsyncByteStream):
160
160
  self.elapsed: datetime.timedelta | None = None
161
161
 
162
162
  async def __aiter__(self) -> typing.AsyncIterator[bytes]:
163
- async for chunk in self._stream:
164
- yield chunk
163
+ stream = self._stream.__aiter__()
164
+ try:
165
+ async for chunk in stream:
166
+ yield chunk
167
+ finally:
168
+ if isinstance(stream, AsyncGenerator):
169
+ await stream.aclose()
165
170
 
166
171
  async def aclose(self) -> None:
167
172
  self.elapsed = datetime.timedelta(seconds=time.perf_counter() - self._start)
@@ -257,7 +262,7 @@ class BaseClient:
257
262
 
258
263
  See also [Authentication][0].
259
264
 
260
- [0]: /quickstart/#authentication
265
+ [0]: quickstart.md#authentication
261
266
  """
262
267
  return self._auth
263
268
 
@@ -342,7 +347,7 @@ class BaseClient:
342
347
 
343
348
  See also: [Request instances][0]
344
349
 
345
- [0]: /advanced/clients/#request-instances
350
+ [0]: advanced/clients.md#request-instances
346
351
  """
347
352
  url = self._merge_url(url)
348
353
  headers = self._merge_headers(headers)
@@ -766,7 +771,7 @@ class Client(BaseClient):
766
771
  [Merging of configuration][0] for how the various parameters
767
772
  are merged with client-level configuration.
768
773
 
769
- [0]: /advanced/clients/#merging-of-configuration
774
+ [0]: advanced/clients.md#merging-of-configuration
770
775
  """
771
776
  if cookies is not None:
772
777
  message = (
@@ -817,7 +822,7 @@ class Client(BaseClient):
817
822
 
818
823
  See also: [Streaming Responses][0]
819
824
 
820
- [0]: /quickstart#streaming-responses
825
+ [0]: quickstart.md#streaming-responses
821
826
  """
822
827
  request = self.build_request(
823
828
  method=method,
@@ -960,7 +965,7 @@ class Client(BaseClient):
960
965
 
961
966
  See also: [Request instances][0]
962
967
 
963
- [0]: /advanced/clients/#request-instances
968
+ [0]: advanced/clients.md#request-instances
964
969
  """
965
970
  if self._state == ClientState.CLOSED:
966
971
  raise RuntimeError("Cannot send a request, as the client has been closed.")
@@ -1603,7 +1608,7 @@ class AsyncClient(BaseClient):
1603
1608
  and [Merging of configuration][0] for how the various parameters
1604
1609
  are merged with client-level configuration.
1605
1610
 
1606
- [0]: /advanced/clients/#merging-of-configuration
1611
+ [0]: advanced/clients.md#merging-of-configuration
1607
1612
  """
1608
1613
 
1609
1614
  if cookies is not None: # pragma: no cover
@@ -1655,7 +1660,7 @@ class AsyncClient(BaseClient):
1655
1660
 
1656
1661
  See also: [Streaming Responses][0]
1657
1662
 
1658
- [0]: /quickstart#streaming-responses
1663
+ [0]: quickstart.md#streaming-responses
1659
1664
  """
1660
1665
  request = self.build_request(
1661
1666
  method=method,
@@ -1798,7 +1803,7 @@ class AsyncClient(BaseClient):
1798
1803
 
1799
1804
  See also: [Request instances][0]
1800
1805
 
1801
- [0]: /advanced/clients/#request-instances
1806
+ [0]: advanced/clients.md#request-instances
1802
1807
  """
1803
1808
  if self._state == ClientState.CLOSED:
1804
1809
  raise RuntimeError("Cannot send a request, as the client has been closed.")
@@ -1,5 +1,6 @@
1
1
  from __future__ import annotations
2
2
 
3
+ import dataclasses
3
4
  import os
4
5
  import typing
5
6
 
@@ -75,6 +76,7 @@ def create_ssl_context(
75
76
  return ctx
76
77
 
77
78
 
79
+ @dataclasses.dataclass(init=False, repr=False)
78
80
  class Timeout:
79
81
  """
80
82
  Timeout configuration.
@@ -145,15 +147,6 @@ class Timeout:
145
147
  "pool": self.pool,
146
148
  }
147
149
 
148
- def __eq__(self, other: typing.Any) -> bool:
149
- return (
150
- isinstance(other, self.__class__)
151
- and self.connect == other.connect
152
- and self.read == other.read
153
- and self.write == other.write
154
- and self.pool == other.pool
155
- )
156
-
157
150
  def __repr__(self) -> str:
158
151
  class_name = self.__class__.__name__
159
152
  if len({self.connect, self.read, self.write, self.pool}) == 1:
@@ -161,6 +154,7 @@ class Timeout:
161
154
  return f"{class_name}(connect={self.connect}, read={self.read}, write={self.write}, pool={self.pool})"
162
155
 
163
156
 
157
+ @dataclasses.dataclass(kw_only=True)
164
158
  class Limits:
165
159
  """
166
160
  Configuration for limits to various client behaviors.
@@ -175,32 +169,9 @@ class Limits:
175
169
  * **keepalive_expiry** - Time limit on idle keep-alive connections in seconds.
176
170
  """
177
171
 
178
- def __init__(
179
- self,
180
- *,
181
- max_connections: int | None = None,
182
- max_keepalive_connections: int | None = None,
183
- keepalive_expiry: float | None = 5.0,
184
- ) -> None:
185
- self.max_connections = max_connections
186
- self.max_keepalive_connections = max_keepalive_connections
187
- self.keepalive_expiry = keepalive_expiry
188
-
189
- def __eq__(self, other: typing.Any) -> bool:
190
- return (
191
- isinstance(other, self.__class__)
192
- and self.max_connections == other.max_connections
193
- and self.max_keepalive_connections == other.max_keepalive_connections
194
- and self.keepalive_expiry == other.keepalive_expiry
195
- )
196
-
197
- def __repr__(self) -> str:
198
- class_name = self.__class__.__name__
199
- return (
200
- f"{class_name}(max_connections={self.max_connections}, "
201
- f"max_keepalive_connections={self.max_keepalive_connections}, "
202
- f"keepalive_expiry={self.keepalive_expiry})"
203
- )
172
+ max_connections: int | None = None
173
+ max_keepalive_connections: int | None = None
174
+ keepalive_expiry: float | None = 5.0
204
175
 
205
176
 
206
177
  class Proxy:
@@ -2,7 +2,7 @@ from __future__ import annotations
2
2
 
3
3
  import inspect
4
4
  import warnings
5
- from collections.abc import AsyncIterable, AsyncIterator, Iterable, Iterator, Mapping
5
+ from collections.abc import AsyncGenerator, AsyncIterable, AsyncIterator, Iterable, Iterator, Mapping
6
6
  from json import dumps as json_dumps
7
7
  from typing import (
8
8
  Any,
@@ -79,9 +79,15 @@ class AsyncIteratorByteStream(AsyncByteStream):
79
79
  yield chunk
80
80
  chunk = await self._stream.aread(self.CHUNK_SIZE)
81
81
  else:
82
- # Otherwise iterate.
83
- async for part in self._stream:
84
- yield part
82
+ # Otherwise iterate, making sure the wrapped stream is closed even if the
83
+ # consumer stops early (e.g. an exception is raised part-way through decoding).
84
+ stream = self._stream.__aiter__()
85
+ try:
86
+ async for part in stream:
87
+ yield part
88
+ finally:
89
+ if isinstance(stream, AsyncGenerator):
90
+ await stream.aclose()
85
91
 
86
92
 
87
93
  class UnattachedStream(AsyncByteStream, SyncByteStream):
@@ -7,8 +7,8 @@ See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding
7
7
  from __future__ import annotations
8
8
 
9
9
  import codecs
10
- import functools
11
10
  import io
11
+ import itertools
12
12
  import sys
13
13
  import typing
14
14
  import zlib
@@ -31,37 +31,60 @@ except ImportError: # pragma: no cover
31
31
  # Zstandard support is optional on Python <= 3.13.
32
32
  # On Python 3.14+, the stdlib includes an optional built-in zstd implementation.
33
33
  if typing.TYPE_CHECKING:
34
- # We keep checking Python version in the type checker path because try..except doesn't help type checkers.
35
34
  if sys.version_info >= (3, 14):
36
35
  from compression.zstd import ZstdDecompressor, ZstdError
37
36
  else:
38
- from zstandard import ZstdDecompressor as _ZstdDecompressor, ZstdError
37
+ from backports.zstd import ZstdDecompressor, ZstdError
39
38
 
40
- ZstdDecompressor = functools.partial(_ZstdDecompressor().decompressobj)
41
-
42
- _zstandard_installed: bool = False
39
+ _zstandard_installed: bool
43
40
  else: # pragma: no cover
44
- _zstandard_installed = False
45
41
  try:
46
- from compression.zstd import ZstdDecompressor, ZstdError
42
+ if sys.version_info >= (3, 14):
43
+ from compression.zstd import ZstdDecompressor, ZstdError
44
+ else:
45
+ from backports.zstd import ZstdDecompressor, ZstdError
47
46
 
48
47
  _zstandard_installed = True
49
- # Either Python <3.14 or the distro doesn't have `compression.zstd`.
50
48
  except ImportError:
51
- try:
52
- from zstandard import ZstdDecompressor as _ZstdDecompressor, ZstdError
49
+ _zstandard_installed = False
50
+
51
+
52
+ MAX_DECODE_CHUNK_SIZE = 2**20 # 1 MiB
53
+
54
+
55
+ class Decompressor(typing.Protocol):
56
+ @property
57
+ def unconsumed_tail(self) -> bytes: ...
58
+
59
+ def decompress(self, data: bytes, max_length: int) -> bytes: ...
60
+
61
+ def flush(self) -> bytes: ...
62
+
63
+
64
+ class ZlibDecompressor:
65
+ """
66
+ Drain a `zlib`/`gzip` decompressor in bounded pieces so a small compressed
67
+ input cannot inflate to an unbounded buffer in a single call.
68
+ """
69
+
70
+ def __init__(self, decompressor: Decompressor) -> None:
71
+ self.decompressor = decompressor
53
72
 
54
- ZstdDecompressor = functools.partial(_ZstdDecompressor().decompressobj)
55
- _zstandard_installed = True
56
- except ImportError:
57
- pass
73
+ def decompress(self, data: bytes) -> typing.Iterator[bytes]:
74
+ decompressed = self.decompressor.decompress(data, MAX_DECODE_CHUNK_SIZE)
75
+ while decompressed:
76
+ yield decompressed
77
+ decompressed = self.decompressor.decompress(self.decompressor.unconsumed_tail, MAX_DECODE_CHUNK_SIZE)
78
+
79
+ def flush(self) -> bytes:
80
+ return self.decompressor.flush()
58
81
 
59
82
 
60
83
  class ContentDecoder:
61
- def decode(self, data: bytes) -> bytes:
84
+ def decode(self, data: bytes) -> typing.Iterator[bytes]:
62
85
  raise NotImplementedError() # pragma: no cover
63
86
 
64
- def flush(self) -> bytes:
87
+ def flush(self) -> typing.Iterator[bytes]:
65
88
  raise NotImplementedError() # pragma: no cover
66
89
 
67
90
 
@@ -70,11 +93,11 @@ class IdentityDecoder(ContentDecoder):
70
93
  Handle unencoded data.
71
94
  """
72
95
 
73
- def decode(self, data: bytes) -> bytes:
74
- return data
96
+ def decode(self, data: bytes) -> typing.Iterator[bytes]:
97
+ yield data
75
98
 
76
- def flush(self) -> bytes:
77
- return b""
99
+ def flush(self) -> typing.Iterator[bytes]:
100
+ yield from ()
78
101
 
79
102
 
80
103
  class DeflateDecoder(ContentDecoder):
@@ -86,22 +109,23 @@ class DeflateDecoder(ContentDecoder):
86
109
 
87
110
  def __init__(self) -> None:
88
111
  self.first_attempt = True
89
- self.decompressor = zlib.decompressobj()
112
+ self.decompressor = ZlibDecompressor(zlib.decompressobj())
90
113
 
91
- def decode(self, data: bytes) -> bytes:
114
+ def decode(self, data: bytes) -> typing.Iterator[bytes]:
92
115
  was_first_attempt = self.first_attempt
93
116
  self.first_attempt = False
94
117
  try:
95
- return self.decompressor.decompress(data)
118
+ yield from self.decompressor.decompress(data)
96
119
  except zlib.error as exc:
97
120
  if was_first_attempt:
98
- self.decompressor = zlib.decompressobj(-zlib.MAX_WBITS)
99
- return self.decode(data)
100
- raise DecodingError(str(exc)) from exc
121
+ self.decompressor = ZlibDecompressor(zlib.decompressobj(-zlib.MAX_WBITS))
122
+ yield from self.decode(data)
123
+ else:
124
+ raise DecodingError(str(exc)) from exc
101
125
 
102
- def flush(self) -> bytes:
126
+ def flush(self) -> typing.Iterator[bytes]:
103
127
  try:
104
- return self.decompressor.flush()
128
+ yield self.decompressor.flush()
105
129
  except zlib.error as exc: # pragma: no cover
106
130
  raise DecodingError(str(exc)) from exc
107
131
 
@@ -114,17 +138,17 @@ class GZipDecoder(ContentDecoder):
114
138
  """
115
139
 
116
140
  def __init__(self) -> None:
117
- self.decompressor = zlib.decompressobj(zlib.MAX_WBITS | 16)
141
+ self.decompressor = ZlibDecompressor(zlib.decompressobj(zlib.MAX_WBITS | 16))
118
142
 
119
- def decode(self, data: bytes) -> bytes:
143
+ def decode(self, data: bytes) -> typing.Iterator[bytes]:
120
144
  try:
121
- return self.decompressor.decompress(data)
145
+ yield from self.decompressor.decompress(data)
122
146
  except zlib.error as exc:
123
147
  raise DecodingError(str(exc)) from exc
124
148
 
125
- def flush(self) -> bytes:
149
+ def flush(self) -> typing.Iterator[bytes]:
126
150
  try:
127
- return self.decompressor.flush()
151
+ yield self.decompressor.flush()
128
152
  except zlib.error as exc: # pragma: no cover
129
153
  raise DecodingError(str(exc)) from exc
130
154
 
@@ -149,26 +173,31 @@ class BrotliDecoder(ContentDecoder):
149
173
 
150
174
  self.decompressor = brotli.Decompressor()
151
175
  self.seen_data = False
152
- self._decompress: typing.Callable[[bytes], bytes]
176
+ self._decompress: typing.Callable[..., bytes]
153
177
  if hasattr(self.decompressor, "decompress"):
154
178
  # The 'brotlicffi' package.
155
179
  self._decompress = self.decompressor.decompress # pragma: no cover
156
180
  else:
157
181
  # The 'brotli' package.
158
- self._decompress = self.decompressor.process # pragma: no cover
182
+ self._decompress = self.decompressor.process
159
183
 
160
- def decode(self, data: bytes) -> bytes:
184
+ def decode(self, data: bytes) -> typing.Iterator[bytes]:
161
185
  if not data:
162
- return b""
186
+ return
163
187
  self.seen_data = True
164
188
  try:
165
- return self._decompress(data)
189
+ # The C backend may allocate nearly twice the requested threshold.
190
+ output_buffer_limit = MAX_DECODE_CHUNK_SIZE // 2
191
+ decompressed = self._decompress(data, output_buffer_limit=output_buffer_limit)
192
+ while decompressed:
193
+ yield decompressed
194
+ decompressed = self._decompress(b"", output_buffer_limit=output_buffer_limit)
166
195
  except brotli.error as exc:
167
196
  raise DecodingError(str(exc)) from exc
168
197
 
169
- def flush(self) -> bytes:
198
+ def flush(self) -> typing.Iterator[bytes]:
170
199
  if not self.seen_data:
171
- return b""
200
+ return
172
201
  try:
173
202
  if hasattr(self.decompressor, "finish"):
174
203
  # Only available in the 'brotlicffi' package.
@@ -177,16 +206,15 @@ class BrotliDecoder(ContentDecoder):
177
206
  # will never actually emit any data. However, it will potentially throw
178
207
  # errors if a truncated or damaged data stream has been used.
179
208
  self.decompressor.finish() # pragma: no cover
180
- return b""
181
209
  except brotli.error as exc: # pragma: no cover
182
210
  raise DecodingError(str(exc)) from exc
211
+ yield from ()
183
212
 
184
213
 
185
214
  class ZStandardDecoder(ContentDecoder):
186
215
  """Handle 'zstd' RFC 8878 decoding.
187
216
 
188
- If running on Python 3.14+ or a distro that doesn't have the `compression.zstd` stdlib module, requires either:
189
- `pip install zstandard` or `pip install httpx2[zstd]`.
217
+ On Python 3.13 and below, this requires `pip install httpx2[zstd]`.
190
218
  """
191
219
 
192
220
  # inspired by the ZstdDecoder implementation in urllib3
@@ -199,30 +227,34 @@ class ZStandardDecoder(ContentDecoder):
199
227
  self.decompressor = ZstdDecompressor()
200
228
  self.seen_data = False
201
229
 
202
- def decode(self, data: bytes) -> bytes:
230
+ def decode(self, data: bytes) -> typing.Iterator[bytes]:
203
231
  if not data:
204
- return b""
232
+ return
205
233
  self.seen_data = True
206
- output = io.BytesIO()
207
234
  try:
208
235
  if self.decompressor.eof:
209
236
  data = self.decompressor.unused_data + data
210
237
  self.decompressor = ZstdDecompressor()
211
- output.write(self.decompressor.decompress(data))
212
- while self.decompressor.eof and self.decompressor.unused_data:
213
- unused_data = self.decompressor.unused_data
238
+ while True:
239
+ decompressed = self.decompressor.decompress(data, MAX_DECODE_CHUNK_SIZE)
240
+ while decompressed:
241
+ yield decompressed
242
+ if self.decompressor.needs_input or self.decompressor.eof:
243
+ break
244
+ decompressed = self.decompressor.decompress(b"", MAX_DECODE_CHUNK_SIZE)
245
+ if not (self.decompressor.eof and self.decompressor.unused_data):
246
+ break
247
+ data = self.decompressor.unused_data
214
248
  self.decompressor = ZstdDecompressor()
215
- output.write(self.decompressor.decompress(unused_data))
216
249
  except ZstdError as exc:
217
250
  raise DecodingError(str(exc)) from exc
218
- return output.getvalue()
219
251
 
220
- def flush(self) -> bytes:
252
+ def flush(self) -> typing.Iterator[bytes]:
221
253
  if not self.seen_data:
222
- return b""
254
+ return
223
255
  if not self.decompressor.eof:
224
256
  raise DecodingError("Zstandard data is incomplete") # pragma: no cover
225
- return b""
257
+ yield from ()
226
258
 
227
259
 
228
260
  class MultiDecoder(ContentDecoder):
@@ -243,16 +275,25 @@ class MultiDecoder(ContentDecoder):
243
275
  # Note that we reverse the order for decoding.
244
276
  self.children: list[ContentDecoder] = [SUPPORTED_DECODERS[coding]() for coding in reversed(codings)]
245
277
 
246
- def decode(self, data: bytes) -> bytes:
278
+ def decode(self, data: bytes) -> typing.Iterator[bytes]:
279
+ streams: typing.Iterator[bytes] = iter((data,))
247
280
  for child in self.children:
248
- data = child.decode(data)
249
- return data
281
+ streams = self._pipe(child.decode, streams)
282
+ yield from streams
250
283
 
251
- def flush(self) -> bytes:
252
- data = b""
284
+ def flush(self) -> typing.Iterator[bytes]:
285
+ streams: typing.Iterator[bytes] = iter(())
253
286
  for child in self.children:
254
- data = child.decode(data) + child.flush()
255
- return data
287
+ streams = itertools.chain(self._pipe(child.decode, streams), child.flush())
288
+ yield from streams
289
+
290
+ @staticmethod
291
+ def _pipe(
292
+ decode: typing.Callable[[bytes], typing.Iterator[bytes]],
293
+ upstream: typing.Iterator[bytes],
294
+ ) -> typing.Iterator[bytes]:
295
+ for chunk in upstream:
296
+ yield from decode(chunk)
256
297
 
257
298
 
258
299
  class ByteChunker:
@@ -77,7 +77,7 @@ def print_help() -> None:
77
77
  )
78
78
 
79
79
  table.add_row("--follow-redirects", "Automatically follow redirects.")
80
- table.add_row("--no-verify", "Disable SSL verification.")
80
+ table.add_row("--verify / --no-verify", "Enable SSL verification.")
81
81
  table.add_row("--http2", "Send the request using HTTP/2, if the remote server supports it.")
82
82
 
83
83
  table.add_row(
@@ -393,11 +393,9 @@ def handle_help(
393
393
  help="Automatically follow redirects.",
394
394
  )
395
395
  @click.option(
396
- "--no-verify",
397
- "verify",
398
- is_flag=True,
396
+ "--verify/--no-verify",
399
397
  default=True,
400
- help="Disable SSL verification.",
398
+ help="Enable SSL verification.",
401
399
  )
402
400
  @click.option(
403
401
  "--http2",
@@ -1,13 +1,14 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import codecs
4
+ import contextlib
4
5
  import datetime
5
6
  import email.message
6
7
  import json as jsonlib
7
8
  import re
8
9
  import typing
9
10
  import urllib.request
10
- from collections.abc import Mapping
11
+ from collections.abc import AsyncGenerator, Mapping
11
12
  from http.cookiejar import Cookie, CookieJar
12
13
 
13
14
  from ._content import ByteStream, UnattachedStream, encode_request, encode_response
@@ -889,12 +890,12 @@ class Response:
889
890
  chunker = ByteChunker(chunk_size=chunk_size)
890
891
  with request_context(request=self._request):
891
892
  for raw_bytes in self.iter_raw():
892
- decoded = decoder.decode(raw_bytes)
893
+ for decoded in decoder.decode(raw_bytes):
894
+ for chunk in chunker.decode(decoded):
895
+ yield chunk
896
+ for decoded in decoder.flush():
893
897
  for chunk in chunker.decode(decoded):
894
- yield chunk
895
- decoded = decoder.flush()
896
- for chunk in chunker.decode(decoded):
897
- yield chunk # pragma: no cover
898
+ yield chunk # pragma: no cover
898
899
  for chunk in chunker.flush():
899
900
  yield chunk
900
901
 
@@ -941,16 +942,17 @@ class Response:
941
942
  self._num_bytes_downloaded = 0
942
943
  chunker = ByteChunker(chunk_size=chunk_size)
943
944
 
944
- with request_context(request=self._request):
945
- for raw_stream_bytes in self.stream:
946
- self._num_bytes_downloaded += len(raw_stream_bytes)
947
- for chunk in chunker.decode(raw_stream_bytes):
948
- yield chunk
949
-
950
- for chunk in chunker.flush():
951
- yield chunk
945
+ try:
946
+ with request_context(request=self._request):
947
+ for raw_stream_bytes in self.stream:
948
+ self._num_bytes_downloaded += len(raw_stream_bytes)
949
+ for chunk in chunker.decode(raw_stream_bytes):
950
+ yield chunk
952
951
 
953
- self.close()
952
+ for chunk in chunker.flush():
953
+ yield chunk
954
+ finally:
955
+ self.close()
954
956
 
955
957
  def close(self) -> None:
956
958
  """
@@ -970,10 +972,11 @@ class Response:
970
972
  Read and return the response content.
971
973
  """
972
974
  if not hasattr(self, "_content"):
973
- self._content = b"".join([part async for part in self.aiter_bytes()])
975
+ async with contextlib.aclosing(self.aiter_bytes()) as parts:
976
+ self._content = b"".join([part async for part in parts])
974
977
  return self._content
975
978
 
976
- async def aiter_bytes(self, chunk_size: int | None = None) -> typing.AsyncIterator[bytes]:
979
+ async def aiter_bytes(self, chunk_size: int | None = None) -> typing.AsyncGenerator[bytes, None]:
977
980
  """
978
981
  A byte-iterator over the decoded response content.
979
982
  This allows us to handle gzip, deflate, brotli, and zstd encoded responses.
@@ -986,13 +989,14 @@ class Response:
986
989
  decoder = self._get_content_decoder()
987
990
  chunker = ByteChunker(chunk_size=chunk_size)
988
991
  with request_context(request=self._request):
989
- async for raw_bytes in self.aiter_raw():
990
- decoded = decoder.decode(raw_bytes)
992
+ async with contextlib.aclosing(self.aiter_raw()) as raw_stream:
993
+ async for raw_bytes in raw_stream:
994
+ for decoded in decoder.decode(raw_bytes):
995
+ for chunk in chunker.decode(decoded):
996
+ yield chunk
997
+ for decoded in decoder.flush():
991
998
  for chunk in chunker.decode(decoded):
992
- yield chunk
993
- decoded = decoder.flush()
994
- for chunk in chunker.decode(decoded):
995
- yield chunk # pragma: no cover
999
+ yield chunk # pragma: no cover
996
1000
  for chunk in chunker.flush():
997
1001
  yield chunk
998
1002
 
@@ -1024,7 +1028,7 @@ class Response:
1024
1028
  for line in decoder.flush():
1025
1029
  yield line
1026
1030
 
1027
- async def aiter_raw(self, chunk_size: int | None = None) -> typing.AsyncIterator[bytes]:
1031
+ async def aiter_raw(self, chunk_size: int | None = None) -> typing.AsyncGenerator[bytes, None]:
1028
1032
  """
1029
1033
  A byte-iterator over the raw response content.
1030
1034
  """
@@ -1039,16 +1043,20 @@ class Response:
1039
1043
  self._num_bytes_downloaded = 0
1040
1044
  chunker = ByteChunker(chunk_size=chunk_size)
1041
1045
 
1042
- with request_context(request=self._request):
1043
- async for raw_stream_bytes in self.stream:
1044
- self._num_bytes_downloaded += len(raw_stream_bytes)
1045
- for chunk in chunker.decode(raw_stream_bytes):
1046
- yield chunk
1047
-
1048
- for chunk in chunker.flush():
1049
- yield chunk
1046
+ stream = self.stream.__aiter__()
1047
+ try:
1048
+ with request_context(request=self._request):
1049
+ async for raw_stream_bytes in stream:
1050
+ self._num_bytes_downloaded += len(raw_stream_bytes)
1051
+ for chunk in chunker.decode(raw_stream_bytes):
1052
+ yield chunk
1050
1053
 
1051
- await self.aclose()
1054
+ for chunk in chunker.flush():
1055
+ yield chunk
1056
+ finally:
1057
+ if isinstance(stream, AsyncGenerator):
1058
+ await stream.aclose()
1059
+ await self.aclose()
1052
1060
 
1053
1061
  async def aclose(self) -> None:
1054
1062
  """
@@ -41,7 +41,7 @@ class WebSocketDisconnect(HTTPXWSException):
41
41
 
42
42
  class WebSocketInvalidTypeReceived(HTTPXWSException):
43
43
  """
44
- Raised when a event is not of the expected type.
44
+ Raised when an event is not of the expected type.
45
45
  """
46
46
 
47
47
  def __init__(self, event: wsproto.events.Event) -> None:
@@ -1,5 +1,5 @@
1
1
  [build-system]
2
- requires = ["hatchling", "hatch-fancy-pypi-readme", "uv-dynamic-versioning>=0.14.0"]
2
+ requires = ["hatchling", "hatch-fancy-pypi-readme", "uv-dynamic-versioning>=0.14.1"]
3
3
  build-backend = "hatchling.build"
4
4
 
5
5
  [tool.hatch.version]
@@ -56,7 +56,7 @@ dependencies = [
56
56
  [project.optional-dependencies]
57
57
  brotli = [
58
58
  "brotli>=1.2.0; platform_python_implementation == 'CPython'",
59
- "brotlicffi>=1.2.0.0; platform_python_implementation != 'CPython'",
59
+ "brotlicffi>=1.2.0.2; platform_python_implementation != 'CPython'",
60
60
  ]
61
61
  cli = [
62
62
  "click>=8.4.2",
@@ -74,7 +74,7 @@ ws = [
74
74
  ]
75
75
  # TODO(Marcelo): Remove when Python 3.13 reaches EOL.
76
76
  zstd = [
77
- "zstandard>=0.18.0; python_version <= '3.13'",
77
+ "backports.zstd>=1.0.0; python_version <= '3.13'",
78
78
  ]
79
79
 
80
80
  [project.scripts]
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes