httpx2 2.16.0__tar.gz → 2.16.1__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 (38) hide show
  1. {httpx2-2.16.0 → httpx2-2.16.1}/CHANGELOG.md +11 -0
  2. {httpx2-2.16.0 → httpx2-2.16.1}/PKG-INFO +13 -12
  3. {httpx2-2.16.0 → httpx2-2.16.1}/README.md +4 -2
  4. {httpx2-2.16.0 → httpx2-2.16.1}/httpx2/__init__.py +1 -1
  5. {httpx2-2.16.0 → httpx2-2.16.1}/httpx2/_api.py +8 -8
  6. {httpx2-2.16.0 → httpx2-2.16.1}/httpx2/_auth.py +14 -14
  7. {httpx2-2.16.0 → httpx2-2.16.1}/httpx2/_client.py +50 -55
  8. {httpx2-2.16.0 → httpx2-2.16.1}/httpx2/_config.py +6 -6
  9. {httpx2-2.16.0 → httpx2-2.16.1}/httpx2/_decoders.py +28 -27
  10. {httpx2-2.16.0 → httpx2-2.16.1}/httpx2/_exceptions.py +2 -2
  11. {httpx2-2.16.0 → httpx2-2.16.1}/httpx2/_main.py +12 -11
  12. {httpx2-2.16.0 → httpx2-2.16.1}/httpx2/_models.py +49 -36
  13. {httpx2-2.16.0 → httpx2-2.16.1}/httpx2/_multipart.py +12 -11
  14. {httpx2-2.16.0 → httpx2-2.16.1}/httpx2/_status_codes.py +2 -1
  15. {httpx2-2.16.0 → httpx2-2.16.1}/httpx2/_transports/asgi.py +10 -9
  16. {httpx2-2.16.0 → httpx2-2.16.1}/httpx2/_transports/base.py +3 -7
  17. {httpx2-2.16.0 → httpx2-2.16.1}/httpx2/_transports/default.py +13 -16
  18. {httpx2-2.16.0 → httpx2-2.16.1}/httpx2/_transports/mock.py +3 -3
  19. {httpx2-2.16.0 → httpx2-2.16.1}/httpx2/_transports/wsgi.py +9 -8
  20. {httpx2-2.16.0 → httpx2-2.16.1}/httpx2/_types.py +31 -29
  21. {httpx2-2.16.0 → httpx2-2.16.1}/httpx2/_urlparse.py +6 -6
  22. {httpx2-2.16.0 → httpx2-2.16.1}/httpx2/_urls.py +22 -21
  23. {httpx2-2.16.0 → httpx2-2.16.1}/httpx2/_utils.py +12 -8
  24. {httpx2-2.16.0 → httpx2-2.16.1}/httpx2/websockets/_api.py +20 -21
  25. {httpx2-2.16.0 → httpx2-2.16.1}/httpx2/websockets/_exceptions.py +2 -2
  26. {httpx2-2.16.0 → httpx2-2.16.1}/httpx2/websockets/_transport.py +9 -10
  27. {httpx2-2.16.0 → httpx2-2.16.1}/.gitignore +0 -0
  28. {httpx2-2.16.0 → httpx2-2.16.1}/LICENSE.md +0 -0
  29. {httpx2-2.16.0 → httpx2-2.16.1}/httpx2/__version__.py +0 -0
  30. {httpx2-2.16.0 → httpx2-2.16.1}/httpx2/_alias.py +0 -0
  31. {httpx2-2.16.0 → httpx2-2.16.1}/httpx2/_content.py +0 -0
  32. {httpx2-2.16.0 → httpx2-2.16.1}/httpx2/_cookies.py +0 -0
  33. {httpx2-2.16.0 → httpx2-2.16.1}/httpx2/_sse.py +0 -0
  34. {httpx2-2.16.0 → httpx2-2.16.1}/httpx2/_transports/__init__.py +1 -1
  35. {httpx2-2.16.0 → httpx2-2.16.1}/httpx2/py.typed +0 -0
  36. {httpx2-2.16.0 → httpx2-2.16.1}/httpx2/websockets/__init__.py +0 -0
  37. {httpx2-2.16.0 → httpx2-2.16.1}/httpx2/websockets/_ping.py +0 -0
  38. {httpx2-2.16.0 → httpx2-2.16.1}/pyproject.toml +0 -0
@@ -4,6 +4,17 @@ 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.16.1 (November 16th, 2026)
8
+
9
+ ### Fixed
10
+
11
+ * Return the response when a redirect has an invalid `Location` header and redirects are not followed, instead of raising `RemoteProtocolError`. `response.next_request` is `None` in that case.
12
+ ([#1064](https://github.com/pydantic/httpx2/pull/1064))
13
+ * Match subdomains for `NO_PROXY` entries written as `*.example.com`, the same as `.example.com`. The entry never matched before, so those requests still went through the proxy.
14
+ ([#1277](https://github.com/pydantic/httpx2/pull/1277))
15
+ * Parse Digest challenge parameter names case-insensitively, and allow whitespace around `=`. A challenge such as `Digest Realm="r", Nonce="n"` raised `ProtocolError` before.
16
+ ([#1315](https://github.com/pydantic/httpx2/pull/1315))
17
+
7
18
  ## 2.16.0 (October 21st, 2026)
8
19
 
9
20
  ### Changed
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: httpx2
3
- Version: 2.16.0
3
+ Version: 2.16.1
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
@@ -26,7 +26,7 @@ Classifier: Programming Language :: Python :: 3.15
26
26
  Classifier: Topic :: Internet :: WWW/HTTP
27
27
  Requires-Python: >=3.11
28
28
  Requires-Dist: anyio>=4.10; sys_platform != 'emscripten'
29
- Requires-Dist: httpcore2==2.16.0; sys_platform != 'emscripten'
29
+ Requires-Dist: httpcore2==2.16.1; sys_platform != 'emscripten'
30
30
  Requires-Dist: httpx2-jsfetch; sys_platform == 'emscripten' and python_version >= '3.12'
31
31
  Requires-Dist: idna>=3.18
32
32
  Requires-Dist: truststore>=0.10; sys_platform != 'emscripten'
@@ -58,7 +58,7 @@ Description-Content-Type: text/markdown
58
58
  <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
59
  </p>
60
60
 
61
- 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**.
61
+ 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**, supports **WebSockets**, and provides both **sync and async APIs**.
62
62
 
63
63
  > [!NOTE]
64
64
  > HTTPX2 is a continuation of the wonderful work started by [@lovelydinosaur](https://github.com/lovelydinosaur) and the broader HTTPX community. We're enormously grateful for everything that has gone into HTTPX over the years - it has been a foundational piece of the modern Python ecosystem, and this project would not exist without it.
@@ -108,6 +108,7 @@ HTTPX2 builds on the well-established usability of `requests`, and gives you:
108
108
  * An integrated command-line client.
109
109
  * HTTP/1.1 [and HTTP/2 support](https://pydantic.dev/docs/httpx2/guides/http2/).
110
110
  * Standard synchronous interface, but with [async support if you need it](https://pydantic.dev/docs/httpx2/guides/async/).
111
+ * [WebSocket support](https://pydantic.dev/docs/httpx2/guides/websockets/).
111
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.
@@ -151,7 +152,7 @@ Project documentation is available at [https://pydantic.dev/docs/httpx2/](https:
151
152
 
152
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://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
+ 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, the [HTTP/2](https://pydantic.dev/docs/httpx2/guides/http2/) section, or the [WebSockets](https://pydantic.dev/docs/httpx2/guides/websockets/) section.
155
156
 
156
157
  The [Developer Interface](https://pydantic.dev/docs/httpx2/api/api/) provides a comprehensive API reference.
157
158
 
@@ -197,6 +198,7 @@ As well as these optional installs:
197
198
 
198
199
  * `h2` - HTTP/2 support. *(Optional, with `httpx2[http2]`)*
199
200
  * `socksio` - SOCKS proxy support. *(Optional, with `httpx2[socks]`)*
201
+ * `wsproto` - WebSocket support. *(Optional, with `httpx2[ws]`)*
200
202
  * `rich` - Rich terminal support. *(Optional, with `httpx2[cli]`)*
201
203
  * `click` - Command line client support. *(Optional, with `httpx2[cli]`)*
202
204
  * `brotli` or `brotlicffi` - Decoding for "brotli" compressed responses. *(Optional, with `httpx2[brotli]`)*
@@ -212,17 +214,16 @@ inspiration around the lower-level networking details.
212
214
 
213
215
  ## Release Information
214
216
 
215
- ## 2.16.0 (October 21st, 2026)
216
-
217
- ### Changed
218
-
219
- * Look up only the cookie domains that match the request host, and skip the expired cookie sweep until a cookie is due. With 1,000 cookies across 500 domains, building the `Cookie` header is about 18 times faster. Cookies from different domains are now sent from the least to the most specific domain.
220
- ([#1285](https://github.com/pydantic/httpx2/pull/1285))
217
+ ## 2.16.1 (November 16th, 2026)
221
218
 
222
219
  ### Fixed
223
220
 
224
- * Reuse the client cookie jar instead of copying it on every request and redirect. A custom policy set with `client.cookies.jar.set_policy()` now applies to outgoing requests.
225
- ([#1284](https://github.com/pydantic/httpx2/pull/1284))
221
+ * Return the response when a redirect has an invalid `Location` header and redirects are not followed, instead of raising `RemoteProtocolError`. `response.next_request` is `None` in that case.
222
+ ([#1064](https://github.com/pydantic/httpx2/pull/1064))
223
+ * Match subdomains for `NO_PROXY` entries written as `*.example.com`, the same as `.example.com`. The entry never matched before, so those requests still went through the proxy.
224
+ ([#1277](https://github.com/pydantic/httpx2/pull/1277))
225
+ * Parse Digest challenge parameter names case-insensitively, and allow whitespace around `=`. A challenge such as `Digest Realm="r", Nonce="n"` raised `ProtocolError` before.
226
+ ([#1315](https://github.com/pydantic/httpx2/pull/1315))
226
227
 
227
228
  ---
228
229
 
@@ -8,7 +8,7 @@
8
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>
9
9
  </p>
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**.
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**, supports **WebSockets**, and provides both **sync and async APIs**.
12
12
 
13
13
  > [!NOTE]
14
14
  > HTTPX2 is a continuation of the wonderful work started by [@lovelydinosaur](https://github.com/lovelydinosaur) and the broader HTTPX community. We're enormously grateful for everything that has gone into HTTPX over the years - it has been a foundational piece of the modern Python ecosystem, and this project would not exist without it.
@@ -58,6 +58,7 @@ HTTPX2 builds on the well-established usability of `requests`, and gives you:
58
58
  * An integrated command-line client.
59
59
  * HTTP/1.1 [and HTTP/2 support](https://pydantic.dev/docs/httpx2/guides/http2/).
60
60
  * Standard synchronous interface, but with [async support if you need it](https://pydantic.dev/docs/httpx2/guides/async/).
61
+ * [WebSocket support](https://pydantic.dev/docs/httpx2/guides/websockets/).
61
62
  * 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).
62
63
  * Strict timeouts everywhere.
63
64
  * Fully type annotated.
@@ -101,7 +102,7 @@ Project documentation is available at [https://pydantic.dev/docs/httpx2/](https:
101
102
 
102
103
  For a run-through of all the basics, head over to the [QuickStart](https://pydantic.dev/docs/httpx2/get-started/quickstart/).
103
104
 
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.
105
+ 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, the [HTTP/2](https://pydantic.dev/docs/httpx2/guides/http2/) section, or the [WebSockets](https://pydantic.dev/docs/httpx2/guides/websockets/) section.
105
106
 
106
107
  The [Developer Interface](https://pydantic.dev/docs/httpx2/api/api/) provides a comprehensive API reference.
107
108
 
@@ -147,6 +148,7 @@ As well as these optional installs:
147
148
 
148
149
  * `h2` - HTTP/2 support. *(Optional, with `httpx2[http2]`)*
149
150
  * `socksio` - SOCKS proxy support. *(Optional, with `httpx2[socks]`)*
151
+ * `wsproto` - WebSocket support. *(Optional, with `httpx2[ws]`)*
150
152
  * `rich` - Rich terminal support. *(Optional, with `httpx2[cli]`)*
151
153
  * `click` - Command line client support. *(Optional, with `httpx2[cli]`)*
152
154
  * `brotli` or `brotlicffi` - Decoding for "brotli" compressed responses. *(Optional, with `httpx2[brotli]`)*
@@ -13,7 +13,7 @@ from ._transports import *
13
13
  from ._types import *
14
14
  from ._urls import *
15
15
 
16
- __all__ = [
16
+ __all__ = [ # noqa: RUF022
17
17
  # __version__.py
18
18
  "__description__",
19
19
  "__title__",
@@ -1,8 +1,8 @@
1
1
  from __future__ import annotations
2
2
 
3
- import typing
4
3
  from collections.abc import Generator
5
4
  from contextlib import contextmanager
5
+ from typing import TYPE_CHECKING, Any
6
6
 
7
7
  from ._client import Client
8
8
  from ._config import (
@@ -26,7 +26,7 @@ from ._types import (
26
26
  )
27
27
  from ._urls import URL
28
28
 
29
- if typing.TYPE_CHECKING:
29
+ if TYPE_CHECKING:
30
30
  import ssl # pragma: no cover
31
31
 
32
32
  from .websockets._api import WebSocketSession
@@ -55,7 +55,7 @@ def request(
55
55
  content: RequestContent | None = None,
56
56
  data: RequestData | None = None,
57
57
  files: RequestFiles | None = None,
58
- json: typing.Any | None = None,
58
+ json: Any | None = None,
59
59
  headers: HeaderTypes | None = None,
60
60
  cookies: CookieTypes | None = None,
61
61
  auth: AuthTypes | None = None,
@@ -128,7 +128,7 @@ def stream(
128
128
  content: RequestContent | None = None,
129
129
  data: RequestData | None = None,
130
130
  files: RequestFiles | None = None,
131
- json: typing.Any | None = None,
131
+ json: Any | None = None,
132
132
  headers: HeaderTypes | None = None,
133
133
  cookies: CookieTypes | None = None,
134
134
  auth: AuthTypes | None = None,
@@ -284,7 +284,7 @@ def post(
284
284
  content: RequestContent | None = None,
285
285
  data: RequestData | None = None,
286
286
  files: RequestFiles | None = None,
287
- json: typing.Any | None = None,
287
+ json: Any | None = None,
288
288
  params: QueryParamTypes | None = None,
289
289
  headers: HeaderTypes | None = None,
290
290
  cookies: CookieTypes | None = None,
@@ -325,7 +325,7 @@ def put(
325
325
  content: RequestContent | None = None,
326
326
  data: RequestData | None = None,
327
327
  files: RequestFiles | None = None,
328
- json: typing.Any | None = None,
328
+ json: Any | None = None,
329
329
  params: QueryParamTypes | None = None,
330
330
  headers: HeaderTypes | None = None,
331
331
  cookies: CookieTypes | None = None,
@@ -366,7 +366,7 @@ def patch(
366
366
  content: RequestContent | None = None,
367
367
  data: RequestData | None = None,
368
368
  files: RequestFiles | None = None,
369
- json: typing.Any | None = None,
369
+ json: Any | None = None,
370
370
  params: QueryParamTypes | None = None,
371
371
  headers: HeaderTypes | None = None,
372
372
  cookies: CookieTypes | None = None,
@@ -443,7 +443,7 @@ def query(
443
443
  content: RequestContent | None = None,
444
444
  data: RequestData | None = None,
445
445
  files: RequestFiles | None = None,
446
- json: typing.Any | None = None,
446
+ json: Any | None = None,
447
447
  params: QueryParamTypes | None = None,
448
448
  headers: HeaderTypes | None = None,
449
449
  cookies: CookieTypes | None = None,
@@ -4,16 +4,16 @@ import hashlib
4
4
  import os
5
5
  import re
6
6
  import time
7
- import typing
8
7
  from base64 import b64encode
8
+ from collections.abc import AsyncGenerator, Callable, Generator
9
+ from typing import TYPE_CHECKING, ClassVar, NamedTuple
9
10
  from urllib.request import parse_http_list
10
11
 
11
12
  from ._exceptions import ProtocolError
12
13
  from ._models import Cookies, Request, Response
13
14
  from ._utils import to_bytes, to_str
14
15
 
15
- if typing.TYPE_CHECKING:
16
- from collections.abc import Callable
16
+ if TYPE_CHECKING:
17
17
  from hashlib import _Hash
18
18
 
19
19
  __all__ = ["Auth", "BasicAuth", "DigestAuth", "FunctionAuth", "NetRCAuth"]
@@ -35,7 +35,7 @@ class Auth:
35
35
  requires_request_body = False
36
36
  requires_response_body = False
37
37
 
38
- def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:
38
+ def auth_flow(self, request: Request) -> Generator[Request, Response, None]:
39
39
  """
40
40
  Execute the authentication flow.
41
41
 
@@ -59,7 +59,7 @@ class Auth:
59
59
  """
60
60
  yield request
61
61
 
62
- def sync_auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:
62
+ def sync_auth_flow(self, request: Request) -> Generator[Request, Response, None]:
63
63
  """
64
64
  Execute the authentication flow synchronously.
65
65
 
@@ -82,7 +82,7 @@ class Auth:
82
82
  except StopIteration:
83
83
  break
84
84
 
85
- async def async_auth_flow(self, request: Request) -> typing.AsyncGenerator[Request, Response]:
85
+ async def async_auth_flow(self, request: Request) -> AsyncGenerator[Request, Response]:
86
86
  """
87
87
  Execute the authentication flow asynchronously.
88
88
 
@@ -112,10 +112,10 @@ class FunctionAuth(Auth):
112
112
  that takes the request, and returns a new, modified request.
113
113
  """
114
114
 
115
- def __init__(self, func: typing.Callable[[Request], Request]) -> None:
115
+ def __init__(self, func: Callable[[Request], Request]) -> None:
116
116
  self._func = func
117
117
 
118
- def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:
118
+ def auth_flow(self, request: Request) -> Generator[Request, Response, None]:
119
119
  yield self._func(request)
120
120
 
121
121
 
@@ -128,7 +128,7 @@ class BasicAuth(Auth):
128
128
  def __init__(self, username: str | bytes, password: str | bytes) -> None:
129
129
  self._auth_header = self._build_auth_header(username, password)
130
130
 
131
- def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:
131
+ def auth_flow(self, request: Request) -> Generator[Request, Response, None]:
132
132
  request.headers["Authorization"] = self._auth_header
133
133
  yield request
134
134
 
@@ -150,7 +150,7 @@ class NetRCAuth(Auth):
150
150
 
151
151
  self._netrc_info = netrc.netrc(file)
152
152
 
153
- def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:
153
+ def auth_flow(self, request: Request) -> Generator[Request, Response, None]:
154
154
  auth_info = self._netrc_info.authenticators(request.url.host)
155
155
  if auth_info is None or not auth_info[2]:
156
156
  # The netrc file did not have authentication credentials for this host.
@@ -168,7 +168,7 @@ class NetRCAuth(Auth):
168
168
 
169
169
  class DigestAuth(Auth):
170
170
  # Hashes are resolved by name at use time, since FIPS builds may remove or block MD5.
171
- _ALGORITHM_TO_HASH_NAME = {
171
+ _ALGORITHM_TO_HASH_NAME: ClassVar[dict[str, str]] = {
172
172
  "MD5": "md5",
173
173
  "MD5-SESS": "md5",
174
174
  "SHA": "sha1",
@@ -185,7 +185,7 @@ class DigestAuth(Auth):
185
185
  self._last_challenge: _DigestAuthChallenge | None = None
186
186
  self._nonce_count = 1
187
187
 
188
- def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:
188
+ def auth_flow(self, request: Request) -> Generator[Request, Response, None]:
189
189
  if self._last_challenge:
190
190
  request.headers["Authorization"] = self._build_auth_header(request, self._last_challenge)
191
191
 
@@ -226,7 +226,7 @@ class DigestAuth(Auth):
226
226
  header_dict: dict[str, str] = {}
227
227
  for field in parse_http_list(fields):
228
228
  key, value = field.strip().split("=", 1)
229
- header_dict[key] = value.strip('"')
229
+ header_dict[key.strip().lower()] = value.strip().strip('"')
230
230
 
231
231
  try:
232
232
  realm = header_dict["realm"].encode()
@@ -327,7 +327,7 @@ class DigestAuth(Auth):
327
327
  raise ProtocolError(message, request=request)
328
328
 
329
329
 
330
- class _DigestAuthChallenge(typing.NamedTuple):
330
+ class _DigestAuthChallenge(NamedTuple):
331
331
  realm: bytes
332
332
  nonce: bytes
333
333
  algorithm: str
@@ -4,11 +4,11 @@ import datetime
4
4
  import enum
5
5
  import logging
6
6
  import time
7
- import typing
8
7
  import warnings
9
- from collections.abc import AsyncGenerator, Generator
10
- from contextlib import asynccontextmanager, contextmanager
8
+ from collections.abc import AsyncGenerator, AsyncIterator, Callable, Generator, Iterator, Mapping
9
+ from contextlib import asynccontextmanager, contextmanager, suppress
11
10
  from types import TracebackType
11
+ from typing import TYPE_CHECKING, Any, Self
12
12
 
13
13
  from .__version__ import __version__
14
14
  from ._auth import Auth, BasicAuth, FunctionAuth
@@ -55,18 +55,13 @@ from ._types import (
55
55
  from ._urls import URL, QueryParams
56
56
  from ._utils import URLPattern, get_environment_proxies
57
57
 
58
- if typing.TYPE_CHECKING:
58
+ if TYPE_CHECKING:
59
59
  import ssl # pragma: no cover
60
60
 
61
61
  from .websockets._api import AsyncWebSocketSession, WebSocketSession
62
62
 
63
63
  __all__ = ["USE_CLIENT_DEFAULT", "AsyncClient", "Client"]
64
64
 
65
- # The type annotation for @classmethod and context managers here follows PEP 484
66
- # https://www.python.org/dev/peps/pep-0484/#annotating-instance-and-class-methods
67
- T = typing.TypeVar("T", bound="Client")
68
- U = typing.TypeVar("U", bound="AsyncClient")
69
-
70
65
 
71
66
  def _is_https_redirect(url: URL, location: URL) -> bool:
72
67
  """
@@ -139,7 +134,7 @@ class BoundSyncStream(SyncByteStream):
139
134
  self._start = start
140
135
  self.elapsed: datetime.timedelta | None = None
141
136
 
142
- def __iter__(self) -> typing.Iterator[bytes]:
137
+ def __iter__(self) -> Iterator[bytes]:
143
138
  yield from self._stream
144
139
 
145
140
  def close(self) -> None:
@@ -159,7 +154,7 @@ class BoundAsyncStream(AsyncByteStream):
159
154
  self._start = start
160
155
  self.elapsed: datetime.timedelta | None = None
161
156
 
162
- async def __aiter__(self) -> typing.AsyncIterator[bytes]:
157
+ async def __aiter__(self) -> AsyncIterator[bytes]:
163
158
  stream = self._stream.__aiter__()
164
159
  try:
165
160
  async for chunk in stream:
@@ -173,7 +168,7 @@ class BoundAsyncStream(AsyncByteStream):
173
168
  await self._stream.aclose()
174
169
 
175
170
 
176
- EventHook = typing.Callable[..., typing.Any]
171
+ EventHook = Callable[..., Any]
177
172
 
178
173
 
179
174
  class BaseClient:
@@ -187,10 +182,10 @@ class BaseClient:
187
182
  timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
188
183
  follow_redirects: bool = False,
189
184
  max_redirects: int = DEFAULT_MAX_REDIRECTS,
190
- event_hooks: None | (typing.Mapping[str, list[EventHook]]) = None,
185
+ event_hooks: Mapping[str, list[EventHook]] | None = None,
191
186
  base_url: URL | str = "",
192
187
  trust_env: bool = True,
193
- default_encoding: str | typing.Callable[[bytes], str | None] = "utf-8",
188
+ default_encoding: str | Callable[[bytes], str | None] = "utf-8",
194
189
  ) -> None:
195
190
  event_hooks = {} if event_hooks is None else event_hooks
196
191
 
@@ -331,7 +326,7 @@ class BaseClient:
331
326
  content: RequestContent | None = None,
332
327
  data: RequestData | None = None,
333
328
  files: RequestFiles | None = None,
334
- json: typing.Any | None = None,
329
+ json: Any | None = None,
335
330
  params: QueryParamTypes | None = None,
336
331
  headers: HeaderTypes | None = None,
337
332
  cookies: CookieTypes | None = None,
@@ -501,18 +496,18 @@ class BaseClient:
501
496
 
502
497
  try:
503
498
  url = URL(location)
504
- except InvalidURL as exc:
505
- raise RemoteProtocolError(f"Invalid URL in location header: {exc}.", request=request) from None
506
499
 
507
- # Handle malformed 'Location' headers that are "absolute" form, have no host.
508
- # See: https://github.com/encode/httpx/issues/771
509
- if url.scheme and not url.host:
510
- url = url.copy_with(host=request.url.host)
500
+ # Handle malformed 'Location' headers that are "absolute" form, have no host.
501
+ # See: https://github.com/encode/httpx/issues/771
502
+ if url.scheme and not url.host:
503
+ url = url.copy_with(host=request.url.host)
511
504
 
512
- # Facilitate relative 'Location' headers, as allowed by RFC 7231.
513
- # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')
514
- if url.is_relative_url:
515
- url = request.url.join(url)
505
+ # Facilitate relative 'Location' headers, as allowed by RFC 7231.
506
+ # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')
507
+ if url.is_relative_url:
508
+ url = request.url.join(url)
509
+ except InvalidURL as exc:
510
+ raise RemoteProtocolError(f"Invalid URL in location header: {exc}.", request=request) from None
516
511
 
517
512
  # Attach previous fragment if needed (RFC 7231 7.1.2)
518
513
  if request.url.fragment and not url.fragment:
@@ -622,15 +617,15 @@ class Client(BaseClient):
622
617
  http1: bool = True,
623
618
  http2: bool = False,
624
619
  proxy: ProxyTypes | None = None,
625
- mounts: None | (typing.Mapping[str, BaseTransport | None]) = None,
620
+ mounts: Mapping[str, BaseTransport | None] | None = None,
626
621
  timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
627
622
  follow_redirects: bool = False,
628
623
  limits: Limits = DEFAULT_LIMITS,
629
624
  max_redirects: int = DEFAULT_MAX_REDIRECTS,
630
- event_hooks: None | (typing.Mapping[str, list[EventHook]]) = None,
625
+ event_hooks: Mapping[str, list[EventHook]] | None = None,
631
626
  base_url: URL | str = "",
632
627
  transport: BaseTransport | None = None,
633
- default_encoding: str | typing.Callable[[bytes], str | None] = "utf-8",
628
+ default_encoding: str | Callable[[bytes], str | None] = "utf-8",
634
629
  ) -> None:
635
630
  super().__init__(
636
631
  auth=auth,
@@ -747,7 +742,7 @@ class Client(BaseClient):
747
742
  content: RequestContent | None = None,
748
743
  data: RequestData | None = None,
749
744
  files: RequestFiles | None = None,
750
- json: typing.Any | None = None,
745
+ json: Any | None = None,
751
746
  params: QueryParamTypes | None = None,
752
747
  headers: HeaderTypes | None = None,
753
748
  cookies: CookieTypes | None = None,
@@ -804,7 +799,7 @@ class Client(BaseClient):
804
799
  content: RequestContent | None = None,
805
800
  data: RequestData | None = None,
806
801
  files: RequestFiles | None = None,
807
- json: typing.Any | None = None,
802
+ json: Any | None = None,
808
803
  params: QueryParamTypes | None = None,
809
804
  headers: HeaderTypes | None = None,
810
805
  cookies: CookieTypes | None = None,
@@ -856,7 +851,7 @@ class Client(BaseClient):
856
851
  content: RequestContent | None = None,
857
852
  data: RequestData | None = None,
858
853
  files: RequestFiles | None = None,
859
- json: typing.Any | None = None,
854
+ json: Any | None = None,
860
855
  params: QueryParamTypes | None = None,
861
856
  headers: HeaderTypes | None = None,
862
857
  cookies: CookieTypes | None = None,
@@ -1048,13 +1043,13 @@ class Client(BaseClient):
1048
1043
  if not response.has_redirect_location:
1049
1044
  return response
1050
1045
 
1051
- request = self._build_redirect_request(request, response)
1052
- history = history + [response]
1053
-
1054
1046
  if follow_redirects:
1047
+ request = self._build_redirect_request(request, response)
1048
+ history = [*history, response]
1055
1049
  response.read()
1056
1050
  else:
1057
- response.next_request = request
1051
+ with suppress(RemoteProtocolError):
1052
+ response.next_request = self._build_redirect_request(request, response)
1058
1053
  return response
1059
1054
 
1060
1055
  except BaseException as exc:
@@ -1186,7 +1181,7 @@ class Client(BaseClient):
1186
1181
  content: RequestContent | None = None,
1187
1182
  data: RequestData | None = None,
1188
1183
  files: RequestFiles | None = None,
1189
- json: typing.Any | None = None,
1184
+ json: Any | None = None,
1190
1185
  params: QueryParamTypes | None = None,
1191
1186
  headers: HeaderTypes | None = None,
1192
1187
  cookies: CookieTypes | None = None,
@@ -1223,7 +1218,7 @@ class Client(BaseClient):
1223
1218
  content: RequestContent | None = None,
1224
1219
  data: RequestData | None = None,
1225
1220
  files: RequestFiles | None = None,
1226
- json: typing.Any | None = None,
1221
+ json: Any | None = None,
1227
1222
  params: QueryParamTypes | None = None,
1228
1223
  headers: HeaderTypes | None = None,
1229
1224
  cookies: CookieTypes | None = None,
@@ -1260,7 +1255,7 @@ class Client(BaseClient):
1260
1255
  content: RequestContent | None = None,
1261
1256
  data: RequestData | None = None,
1262
1257
  files: RequestFiles | None = None,
1263
- json: typing.Any | None = None,
1258
+ json: Any | None = None,
1264
1259
  params: QueryParamTypes | None = None,
1265
1260
  headers: HeaderTypes | None = None,
1266
1261
  cookies: CookieTypes | None = None,
@@ -1326,7 +1321,7 @@ class Client(BaseClient):
1326
1321
  content: RequestContent | None = None,
1327
1322
  data: RequestData | None = None,
1328
1323
  files: RequestFiles | None = None,
1329
- json: typing.Any | None = None,
1324
+ json: Any | None = None,
1330
1325
  params: QueryParamTypes | None = None,
1331
1326
  headers: HeaderTypes | None = None,
1332
1327
  cookies: CookieTypes | None = None,
@@ -1368,7 +1363,7 @@ class Client(BaseClient):
1368
1363
  if transport is not None:
1369
1364
  transport.close()
1370
1365
 
1371
- def __enter__(self: T) -> T:
1366
+ def __enter__(self) -> Self:
1372
1367
  if self._state != ClientState.UNOPENED:
1373
1368
  msg = {
1374
1369
  ClientState.OPENED: "Cannot open a client instance more than once.",
@@ -1458,16 +1453,16 @@ class AsyncClient(BaseClient):
1458
1453
  http1: bool = True,
1459
1454
  http2: bool = False,
1460
1455
  proxy: ProxyTypes | None = None,
1461
- mounts: None | (typing.Mapping[str, AsyncBaseTransport | None]) = None,
1456
+ mounts: Mapping[str, AsyncBaseTransport | None] | None = None,
1462
1457
  timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
1463
1458
  follow_redirects: bool = False,
1464
1459
  limits: Limits = DEFAULT_LIMITS,
1465
1460
  max_redirects: int = DEFAULT_MAX_REDIRECTS,
1466
- event_hooks: None | (typing.Mapping[str, list[EventHook]]) = None,
1461
+ event_hooks: Mapping[str, list[EventHook]] | None = None,
1467
1462
  base_url: URL | str = "",
1468
1463
  transport: AsyncBaseTransport | None = None,
1469
1464
  trust_env: bool = True,
1470
- default_encoding: str | typing.Callable[[bytes], str | None] = "utf-8",
1465
+ default_encoding: str | Callable[[bytes], str | None] = "utf-8",
1471
1466
  ) -> None:
1472
1467
  super().__init__(
1473
1468
  auth=auth,
@@ -1584,7 +1579,7 @@ class AsyncClient(BaseClient):
1584
1579
  content: RequestContent | None = None,
1585
1580
  data: RequestData | None = None,
1586
1581
  files: RequestFiles | None = None,
1587
- json: typing.Any | None = None,
1582
+ json: Any | None = None,
1588
1583
  params: QueryParamTypes | None = None,
1589
1584
  headers: HeaderTypes | None = None,
1590
1585
  cookies: CookieTypes | None = None,
@@ -1642,7 +1637,7 @@ class AsyncClient(BaseClient):
1642
1637
  content: RequestContent | None = None,
1643
1638
  data: RequestData | None = None,
1644
1639
  files: RequestFiles | None = None,
1645
- json: typing.Any | None = None,
1640
+ json: Any | None = None,
1646
1641
  params: QueryParamTypes | None = None,
1647
1642
  headers: HeaderTypes | None = None,
1648
1643
  cookies: CookieTypes | None = None,
@@ -1694,7 +1689,7 @@ class AsyncClient(BaseClient):
1694
1689
  content: RequestContent | None = None,
1695
1690
  data: RequestData | None = None,
1696
1691
  files: RequestFiles | None = None,
1697
- json: typing.Any | None = None,
1692
+ json: Any | None = None,
1698
1693
  params: QueryParamTypes | None = None,
1699
1694
  headers: HeaderTypes | None = None,
1700
1695
  cookies: CookieTypes | None = None,
@@ -1887,13 +1882,13 @@ class AsyncClient(BaseClient):
1887
1882
  if not response.has_redirect_location:
1888
1883
  return response
1889
1884
 
1890
- request = self._build_redirect_request(request, response)
1891
- history = history + [response]
1892
-
1893
1885
  if follow_redirects:
1886
+ request = self._build_redirect_request(request, response)
1887
+ history = [*history, response]
1894
1888
  await response.aread()
1895
1889
  else:
1896
- response.next_request = request
1890
+ with suppress(RemoteProtocolError):
1891
+ response.next_request = self._build_redirect_request(request, response)
1897
1892
  return response
1898
1893
 
1899
1894
  except BaseException as exc:
@@ -2024,7 +2019,7 @@ class AsyncClient(BaseClient):
2024
2019
  content: RequestContent | None = None,
2025
2020
  data: RequestData | None = None,
2026
2021
  files: RequestFiles | None = None,
2027
- json: typing.Any | None = None,
2022
+ json: Any | None = None,
2028
2023
  params: QueryParamTypes | None = None,
2029
2024
  headers: HeaderTypes | None = None,
2030
2025
  cookies: CookieTypes | None = None,
@@ -2061,7 +2056,7 @@ class AsyncClient(BaseClient):
2061
2056
  content: RequestContent | None = None,
2062
2057
  data: RequestData | None = None,
2063
2058
  files: RequestFiles | None = None,
2064
- json: typing.Any | None = None,
2059
+ json: Any | None = None,
2065
2060
  params: QueryParamTypes | None = None,
2066
2061
  headers: HeaderTypes | None = None,
2067
2062
  cookies: CookieTypes | None = None,
@@ -2098,7 +2093,7 @@ class AsyncClient(BaseClient):
2098
2093
  content: RequestContent | None = None,
2099
2094
  data: RequestData | None = None,
2100
2095
  files: RequestFiles | None = None,
2101
- json: typing.Any | None = None,
2096
+ json: Any | None = None,
2102
2097
  params: QueryParamTypes | None = None,
2103
2098
  headers: HeaderTypes | None = None,
2104
2099
  cookies: CookieTypes | None = None,
@@ -2164,7 +2159,7 @@ class AsyncClient(BaseClient):
2164
2159
  content: RequestContent | None = None,
2165
2160
  data: RequestData | None = None,
2166
2161
  files: RequestFiles | None = None,
2167
- json: typing.Any | None = None,
2162
+ json: Any | None = None,
2168
2163
  params: QueryParamTypes | None = None,
2169
2164
  headers: HeaderTypes | None = None,
2170
2165
  cookies: CookieTypes | None = None,
@@ -2206,7 +2201,7 @@ class AsyncClient(BaseClient):
2206
2201
  if proxy is not None:
2207
2202
  await proxy.aclose()
2208
2203
 
2209
- async def __aenter__(self: U) -> U:
2204
+ async def __aenter__(self) -> Self:
2210
2205
  if self._state != ClientState.UNOPENED:
2211
2206
  msg = {
2212
2207
  ClientState.OPENED: "Cannot open a client instance more than once.",