httpx2 2.13.0__tar.gz → 2.14.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.13.0 → httpx2-2.14.0}/CHANGELOG.md +34 -0
  2. {httpx2-2.13.0 → httpx2-2.14.0}/PKG-INFO +20 -10
  3. {httpx2-2.13.0 → httpx2-2.14.0}/httpx2/_auth.py +18 -11
  4. {httpx2-2.13.0 → httpx2-2.14.0}/httpx2/_content.py +2 -2
  5. {httpx2-2.13.0 → httpx2-2.14.0}/httpx2/_urls.py +1 -1
  6. {httpx2-2.13.0 → httpx2-2.14.0}/httpx2/_utils.py +53 -7
  7. {httpx2-2.13.0 → httpx2-2.14.0}/httpx2/websockets/_api.py +26 -7
  8. {httpx2-2.13.0 → httpx2-2.14.0}/httpx2/websockets/_transport.py +8 -1
  9. {httpx2-2.13.0 → httpx2-2.14.0}/.gitignore +0 -0
  10. {httpx2-2.13.0 → httpx2-2.14.0}/LICENSE.md +0 -0
  11. {httpx2-2.13.0 → httpx2-2.14.0}/README.md +0 -0
  12. {httpx2-2.13.0 → httpx2-2.14.0}/httpx2/__init__.py +0 -0
  13. {httpx2-2.13.0 → httpx2-2.14.0}/httpx2/__version__.py +0 -0
  14. {httpx2-2.13.0 → httpx2-2.14.0}/httpx2/_alias.py +0 -0
  15. {httpx2-2.13.0 → httpx2-2.14.0}/httpx2/_api.py +0 -0
  16. {httpx2-2.13.0 → httpx2-2.14.0}/httpx2/_client.py +0 -0
  17. {httpx2-2.13.0 → httpx2-2.14.0}/httpx2/_config.py +0 -0
  18. {httpx2-2.13.0 → httpx2-2.14.0}/httpx2/_decoders.py +0 -0
  19. {httpx2-2.13.0 → httpx2-2.14.0}/httpx2/_exceptions.py +0 -0
  20. {httpx2-2.13.0 → httpx2-2.14.0}/httpx2/_main.py +0 -0
  21. {httpx2-2.13.0 → httpx2-2.14.0}/httpx2/_models.py +0 -0
  22. {httpx2-2.13.0 → httpx2-2.14.0}/httpx2/_multipart.py +0 -0
  23. {httpx2-2.13.0 → httpx2-2.14.0}/httpx2/_sse.py +0 -0
  24. {httpx2-2.13.0 → httpx2-2.14.0}/httpx2/_status_codes.py +0 -0
  25. {httpx2-2.13.0 → httpx2-2.14.0}/httpx2/_transports/__init__.py +0 -0
  26. {httpx2-2.13.0 → httpx2-2.14.0}/httpx2/_transports/asgi.py +0 -0
  27. {httpx2-2.13.0 → httpx2-2.14.0}/httpx2/_transports/base.py +0 -0
  28. {httpx2-2.13.0 → httpx2-2.14.0}/httpx2/_transports/default.py +0 -0
  29. {httpx2-2.13.0 → httpx2-2.14.0}/httpx2/_transports/mock.py +0 -0
  30. {httpx2-2.13.0 → httpx2-2.14.0}/httpx2/_transports/wsgi.py +0 -0
  31. {httpx2-2.13.0 → httpx2-2.14.0}/httpx2/_types.py +0 -0
  32. {httpx2-2.13.0 → httpx2-2.14.0}/httpx2/_urlparse.py +0 -0
  33. {httpx2-2.13.0 → httpx2-2.14.0}/httpx2/py.typed +0 -0
  34. {httpx2-2.13.0 → httpx2-2.14.0}/httpx2/websockets/__init__.py +0 -0
  35. {httpx2-2.13.0 → httpx2-2.14.0}/httpx2/websockets/_exceptions.py +0 -0
  36. {httpx2-2.13.0 → httpx2-2.14.0}/httpx2/websockets/_ping.py +0 -0
  37. {httpx2-2.13.0 → httpx2-2.14.0}/pyproject.toml +0 -0
@@ -4,6 +4,40 @@ 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.14.0 (October 18th, 2026)
8
+
9
+ ### Added
10
+
11
+ * Match IP CIDR ranges, like `192.168.0.0/16` and `[fe80::]/10`, in `NO_PROXY` and `mounts`. Requests to any address in the range now bypass the proxy; previously only the network address itself did.
12
+ ([#1165](https://github.com/pydantic/httpx2/pull/1165))
13
+ * Accept bracketed IPv6 addresses, like `[::1]` and `[::1]:8080`, in `NO_PROXY`.
14
+ ([#1267](https://github.com/pydantic/httpx2/pull/1267))
15
+
16
+ ### Changed
17
+
18
+ * Raise `InvalidURL` for a `mounts` key with an IP host followed by anything other than a valid CIDR prefix, like `all://10.0.0.0/33`.
19
+ ([#1165](https://github.com/pydantic/httpx2/pull/1165))
20
+
21
+ ### Fixed
22
+
23
+ * Ignore `NO_PROXY` entries that cannot be parsed, instead of raising `InvalidURL` when the client is created.
24
+ ([#1267](https://github.com/pydantic/httpx2/pull/1267))
25
+ * Import `httpx2` on FIPS-enforced Python builds without `hashlib.md5`. `DigestAuth` raises `ProtocolError` when the server asks for an unavailable algorithm.
26
+ ([#1130](https://github.com/pydantic/httpx2/pull/1130))
27
+ * Handle reads after an ASGI WebSocket app shuts down, instead of leaking `anyio` exceptions.
28
+ ([#1233](https://github.com/pydantic/httpx2/pull/1233))
29
+ * Stop the sync WebSocket session from hanging on exit when its event queue is full.
30
+ ([#1123](https://github.com/pydantic/httpx2/pull/1123))
31
+
32
+ ## 2.13.1 (September 23rd, 2026)
33
+
34
+ ### Fixed
35
+
36
+ * Calculate `Content-Length` from the remaining bytes when a file is passed as `content=`, respecting its current position.
37
+ ([#1214](https://github.com/pydantic/httpx2/pull/1214))
38
+ * Stop the sync WebSocket keepalive thread cleanly when a ping races with connection shutdown.
39
+ ([#1228](https://github.com/pydantic/httpx2/pull/1228))
40
+
7
41
  ## 2.13.0 (September 14th, 2026)
8
42
 
9
43
  ### Changed
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: httpx2
3
- Version: 2.13.0
3
+ Version: 2.14.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,7 +27,7 @@ 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.13.0; sys_platform != 'emscripten'
30
+ Requires-Dist: httpcore2==2.14.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'
@@ -213,20 +213,30 @@ inspiration around the lower-level networking details.
213
213
 
214
214
  ## Release Information
215
215
 
216
- ## 2.13.0 (September 14th, 2026)
216
+ ## 2.14.0 (October 18th, 2026)
217
+
218
+ ### Added
219
+
220
+ * Match IP CIDR ranges, like `192.168.0.0/16` and `[fe80::]/10`, in `NO_PROXY` and `mounts`. Requests to any address in the range now bypass the proxy; previously only the network address itself did.
221
+ ([#1165](https://github.com/pydantic/httpx2/pull/1165))
222
+ * Accept bracketed IPv6 addresses, like `[::1]` and `[::1]:8080`, in `NO_PROXY`.
223
+ ([#1267](https://github.com/pydantic/httpx2/pull/1267))
217
224
 
218
225
  ### Changed
219
226
 
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))
227
+ * Raise `InvalidURL` for a `mounts` key with an IP host followed by anything other than a valid CIDR prefix, like `all://10.0.0.0/33`.
228
+ ([#1165](https://github.com/pydantic/httpx2/pull/1165))
222
229
 
223
230
  ### Fixed
224
231
 
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))
232
+ * Ignore `NO_PROXY` entries that cannot be parsed, instead of raising `InvalidURL` when the client is created.
233
+ ([#1267](https://github.com/pydantic/httpx2/pull/1267))
234
+ * Import `httpx2` on FIPS-enforced Python builds without `hashlib.md5`. `DigestAuth` raises `ProtocolError` when the server asks for an unavailable algorithm.
235
+ ([#1130](https://github.com/pydantic/httpx2/pull/1130))
236
+ * Handle reads after an ASGI WebSocket app shuts down, instead of leaking `anyio` exceptions.
237
+ ([#1233](https://github.com/pydantic/httpx2/pull/1233))
238
+ * Stop the sync WebSocket session from hanging on exit when its event queue is full.
239
+ ([#1123](https://github.com/pydantic/httpx2/pull/1123))
230
240
 
231
241
  ---
232
242
 
@@ -13,9 +13,9 @@ from ._models import Cookies, Request, Response
13
13
  from ._utils import to_bytes, to_str
14
14
 
15
15
  if typing.TYPE_CHECKING:
16
+ from collections.abc import Callable
16
17
  from hashlib import _Hash
17
18
 
18
-
19
19
  __all__ = ["Auth", "BasicAuth", "DigestAuth", "FunctionAuth", "NetRCAuth"]
20
20
 
21
21
 
@@ -167,15 +167,16 @@ class NetRCAuth(Auth):
167
167
 
168
168
 
169
169
  class DigestAuth(Auth):
170
- _ALGORITHM_TO_HASH_FUNCTION: dict[str, typing.Callable[[bytes], _Hash]] = {
171
- "MD5": hashlib.md5,
172
- "MD5-SESS": hashlib.md5,
173
- "SHA": hashlib.sha1,
174
- "SHA-SESS": hashlib.sha1,
175
- "SHA-256": hashlib.sha256,
176
- "SHA-256-SESS": hashlib.sha256,
177
- "SHA-512": hashlib.sha512,
178
- "SHA-512-SESS": hashlib.sha512,
170
+ # Hashes are resolved by name at use time, since FIPS builds may remove or block MD5.
171
+ _ALGORITHM_TO_HASH_NAME = {
172
+ "MD5": "md5",
173
+ "MD5-SESS": "md5",
174
+ "SHA": "sha1",
175
+ "SHA-SESS": "sha1",
176
+ "SHA-256": "sha256",
177
+ "SHA-256-SESS": "sha256",
178
+ "SHA-512": "sha512",
179
+ "SHA-512-SESS": "sha512",
179
180
  }
180
181
 
181
182
  def __init__(self, username: str | bytes, password: str | bytes) -> None:
@@ -239,7 +240,13 @@ class DigestAuth(Auth):
239
240
  raise ProtocolError(message, request=request) from exc
240
241
 
241
242
  def _build_auth_header(self, request: Request, challenge: _DigestAuthChallenge) -> str:
242
- hash_func = self._ALGORITHM_TO_HASH_FUNCTION[challenge.algorithm.upper()]
243
+ try:
244
+ hash_func: Callable[[bytes], _Hash] = getattr(
245
+ hashlib, self._ALGORITHM_TO_HASH_NAME[challenge.algorithm.upper()]
246
+ )
247
+ except (KeyError, AttributeError) as exc:
248
+ message = f"Unsupported digest auth algorithm {challenge.algorithm!r}"
249
+ raise ProtocolError(message, request=request) from exc
243
250
 
244
251
  def digest(data: bytes) -> bytes:
245
252
  return hash_func(data).hexdigest().encode()
@@ -19,7 +19,7 @@ from ._types import (
19
19
  ResponseContent,
20
20
  SyncByteStream,
21
21
  )
22
- from ._utils import peek_filelike_length, primitive_value_to_str
22
+ from ._utils import peek_filelike_remaining_length, primitive_value_to_str
23
23
 
24
24
  __all__ = ["ByteStream"]
25
25
 
@@ -119,7 +119,7 @@ def encode_content(
119
119
  # catches a case that's easy for users to make in error, and would
120
120
  # otherwise pass through here, like any other bytes-iterable,
121
121
  # because `dict` happens to be iterable. See issue #2491.
122
- content_length_or_none = peek_filelike_length(content)
122
+ content_length_or_none = peek_filelike_remaining_length(content)
123
123
 
124
124
  if content_length_or_none is None:
125
125
  headers = {"Transfer-Encoding": "chunked"}
@@ -34,7 +34,7 @@ class URL:
34
34
  assert url.port == 1234
35
35
  assert url.netloc == b"xn--mller-kva.de:1234"
36
36
  assert url.path == "/pa th"
37
- assert url.query == b"?search=ab"
37
+ assert url.query == b"search=ab"
38
38
  assert url.raw_path == b"/pa%20th?search=ab"
39
39
  assert url.fragment == "anchorlink"
40
40
 
@@ -6,6 +6,7 @@ import re
6
6
  import typing
7
7
  from urllib.request import getproxies
8
8
 
9
+ from ._exceptions import InvalidURL
9
10
  from ._types import PrimitiveData
10
11
 
11
12
  if typing.TYPE_CHECKING:
@@ -72,9 +73,17 @@ def get_environment_proxies() -> dict[str, str | None]:
72
73
  mounts[f"all://[{hostname}]"] = None
73
74
  elif hostname.lower() == "localhost":
74
75
  mounts[f"all://{hostname}"] = None
75
- else:
76
+ elif hostname.startswith("["):
77
+ mounts[f"all://{hostname}"] = None
78
+ elif "/" not in hostname:
76
79
  mounts[f"all://*{hostname}"] = None
77
80
 
81
+ for pattern in list(mounts):
82
+ try:
83
+ URLPattern(pattern)
84
+ except InvalidURL:
85
+ del mounts[pattern] # Like curl and Go, ignore entries that cannot be parsed.
86
+
78
87
  return mounts
79
88
 
80
89
 
@@ -115,6 +124,18 @@ def peek_filelike_length(stream: typing.Any) -> int | None:
115
124
  return length
116
125
 
117
126
 
127
+ def peek_filelike_remaining_length(stream: typing.Any) -> int | None:
128
+ """Return the remaining byte length without changing the stream position."""
129
+ try:
130
+ offset: int = stream.tell()
131
+ length: int = stream.seek(0, os.SEEK_END)
132
+ stream.seek(offset)
133
+ except (AttributeError, OSError):
134
+ return None
135
+
136
+ return max(0, length - offset)
137
+
138
+
118
139
  class URLPattern:
119
140
  """
120
141
  A utility class currently used for making lookups against proxy keys...
@@ -168,12 +189,26 @@ class URLPattern:
168
189
  )
169
190
 
170
191
  url = URL(pattern)
192
+ self.network = None
193
+ prefix = url.path.removeprefix("/")
194
+ if prefix and (is_ipv4_hostname(url.host) or is_ipv6_hostname(url.host)):
195
+ # A CIDR-style host, e.g. "all://192.168.0.0/16" or "all://[::1]/64".
196
+ host = f"[{url.host}]" if ":" in url.host else url.host
197
+ if "@" in pattern or "%" in pattern or not prefix.isdigit() or not pattern.endswith(f"{host}/{prefix}"):
198
+ raise InvalidURL(f"Invalid network in {pattern!r}")
199
+ try:
200
+ self.network = ipaddress.ip_network(f"{url.host}/{prefix}", strict=False)
201
+ except ValueError as exc:
202
+ raise InvalidURL(f"Invalid network in {pattern!r}") from exc
203
+
171
204
  self.pattern = pattern
172
205
  self.scheme = "" if url.scheme == "all" else url.scheme
173
206
  self.host = "" if url.host == "*" else url.host
174
207
  self.port = url.port
175
- if not url.host or url.host == "*":
208
+ if self.network is not None:
176
209
  self.host_regex: typing.Pattern[str] | None = None
210
+ elif not url.host or url.host == "*":
211
+ self.host_regex = None
177
212
  elif url.host.startswith("*."):
178
213
  # *.example.com should match "www.example.com", but not "example.com"
179
214
  domain = re.escape(url.host[2:])
@@ -190,25 +225,36 @@ class URLPattern:
190
225
  def matches(self, other: URL) -> bool:
191
226
  if self.scheme and self.scheme != other.scheme:
192
227
  return False
193
- if self.host and self.host_regex is not None and not self.host_regex.match(other.host):
228
+ if self.network is not None:
229
+ try:
230
+ other_address = ipaddress.ip_address(other.host)
231
+ except ValueError:
232
+ return False
233
+ if other_address not in self.network:
234
+ return False
235
+ elif self.host and self.host_regex is not None and not self.host_regex.match(other.host):
194
236
  return False
195
237
  if self.port is not None and self.port != other.port:
196
238
  return False
197
239
  return True
198
240
 
199
241
  @property
200
- def priority(self) -> tuple[int, int, int]:
242
+ def priority(self) -> tuple[int, int, int, int, int]:
201
243
  """
202
244
  The priority allows URLPattern instances to be sortable, so that
203
245
  we can match from most specific to least specific.
204
246
  """
205
247
  # URLs with a port should take priority over URLs without a port.
206
248
  port_priority = 0 if self.port is not None else 1
207
- # Longer hostnames should match first.
208
- host_priority = -len(self.host)
249
+ # Exact hosts match first, then networks, then patterns without a host.
250
+ host_kind_priority = 1 if self.network is not None else 0 if self.host else 2
251
+ # Smaller networks match first. Address count, not prefix length, so IPv4 and IPv6 compare fairly.
252
+ network_priority = self.network.num_addresses if self.network is not None else 0
253
+ # Longer hostnames should match first. Networks are already ordered by size.
254
+ host_priority = -len(self.host) if self.network is None else 0
209
255
  # Longer schemes should match first.
210
256
  scheme_priority = -len(self.scheme)
211
- return (port_priority, host_priority, scheme_priority)
257
+ return (port_priority, host_kind_priority, network_priority, host_priority, scheme_priority)
212
258
 
213
259
  def __hash__(self) -> int:
214
260
  return hash(self.pattern)
@@ -12,10 +12,15 @@ import typing
12
12
  from types import TracebackType
13
13
 
14
14
  if sys.version_info >= (3, 13):
15
+ from queue import ShutDown as QueueShutDown # pragma: no cover
15
16
  from typing import TypeVar # pragma: no cover
16
17
  else:
17
18
  from typing_extensions import TypeVar # pragma: no cover
18
19
 
20
+ class QueueShutDown(Exception): # pragma: no cover
21
+ """Stand-in for `queue.ShutDown`, which is never raised before Python 3.13."""
22
+
23
+
19
24
  import anyio
20
25
  import wsproto
21
26
  import wsproto.utilities
@@ -149,9 +154,17 @@ class WebSocketSession:
149
154
  tb: TracebackType | None,
150
155
  ) -> None:
151
156
  self.close()
152
- self._background_receive_task.join()
153
- if self._background_keepalive_ping_task is not None:
154
- self._background_keepalive_ping_task.join()
157
+ # A task blocked on a full events queue only exits once there's room, or the queue shuts down.
158
+ if sys.version_info >= (3, 13): # pragma: no cover - Python 3.13+ only
159
+ self._events.shutdown(immediate=True)
160
+ self._background_receive_task.join()
161
+ if self._background_keepalive_ping_task is not None:
162
+ self._background_keepalive_ping_task.join()
163
+ else: # pragma: no cover - Python < 3.13 only
164
+ for task in (self._background_receive_task, self._background_keepalive_ping_task):
165
+ while task is not None and task.is_alive():
166
+ with contextlib.suppress(queue.Empty):
167
+ self._events.get(timeout=0.01)
155
168
 
156
169
  def ping(self, payload: bytes = b"") -> threading.Event:
157
170
  """
@@ -315,6 +328,8 @@ class WebSocketSession:
315
328
  event = self._events.get(block=True, timeout=timeout)
316
329
  except queue.Empty as e:
317
330
  raise TimeoutError from e
331
+ except QueueShutDown as e: # pragma: no cover - Python 3.13+ only
332
+ raise WebSocketDisconnect() from e
318
333
  if isinstance(event, HTTPXWSException):
319
334
  raise event
320
335
  if isinstance(event, wsproto.events.CloseConnection):
@@ -547,8 +562,9 @@ class WebSocketSession:
547
562
  self._events.put(event)
548
563
  except (httpcore2.ReadError, httpcore2.WriteError, EndOfStream):
549
564
  self.close(CloseReason.INTERNAL_ERROR, "Stream error")
550
- self._events.put(WebSocketNetworkError())
551
- except ShouldClose:
565
+ with contextlib.suppress(QueueShutDown):
566
+ self._events.put(WebSocketNetworkError())
567
+ except (ShouldClose, QueueShutDown):
552
568
  pass
553
569
 
554
570
  def _background_keepalive_ping(self, interval_seconds: float, timeout_seconds: float | None = None) -> None:
@@ -557,13 +573,16 @@ class WebSocketSession:
557
573
  should_close = self._wait_until_closed(self._should_close.wait, interval_seconds)
558
574
  if should_close: # pragma: no cover
559
575
  raise ShouldClose()
560
- pong_callback = self.ping()
576
+ try:
577
+ pong_callback = self.ping()
578
+ except wsproto.utilities.LocalProtocolError:
579
+ return
561
580
  if timeout_seconds is not None:
562
581
  acknowledged = self._wait_until_closed(pong_callback.wait, timeout_seconds)
563
582
  if not acknowledged:
564
583
  self.close(CloseReason.INTERNAL_ERROR, "Keepalive ping timeout")
565
584
  self._events.put(WebSocketNetworkError())
566
- except ShouldClose:
585
+ except (ShouldClose, QueueShutDown):
567
586
  pass
568
587
 
569
588
  def _wait_until_closed(
@@ -106,7 +106,14 @@ class ASGIWebSocketAsyncNetworkStream:
106
106
  return await self._exit_stack.__aexit__(exc_type, exc_val, exc_tb)
107
107
 
108
108
  async def read(self, max_bytes: int, timeout: float | None = None) -> bytes:
109
- message: Message = await self.receive(timeout=timeout)
109
+ import httpcore2
110
+
111
+ try:
112
+ message: Message = await self.receive(timeout=timeout)
113
+ except anyio.EndOfStream:
114
+ return b""
115
+ except anyio.ClosedResourceError as exc:
116
+ raise httpcore2.ReadError() from exc
110
117
  type = message["type"]
111
118
 
112
119
  if type not in {"websocket.send", "websocket.close"}:
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
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes