httpx2 2.9.0__tar.gz → 2.10.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.
- {httpx2-2.9.0 → httpx2-2.10.0}/CHANGELOG.md +28 -0
- {httpx2-2.9.0 → httpx2-2.10.0}/PKG-INFO +46 -6
- {httpx2-2.9.0 → httpx2-2.10.0}/README.md +22 -0
- httpx2-2.10.0/httpx2/_alias.py +71 -0
- {httpx2-2.9.0 → httpx2-2.10.0}/httpx2/_client.py +6 -3
- {httpx2-2.9.0 → httpx2-2.10.0}/httpx2/_config.py +2 -0
- {httpx2-2.9.0 → httpx2-2.10.0}/httpx2/_content.py +1 -1
- {httpx2-2.9.0 → httpx2-2.10.0}/httpx2/_models.py +12 -1
- httpx2-2.10.0/httpx2/_sse.py +226 -0
- {httpx2-2.9.0 → httpx2-2.10.0}/httpx2/_status_codes.py +31 -9
- httpx2-2.10.0/httpx2/_transports/__init__.py +27 -0
- httpx2-2.10.0/httpx2/websockets/__init__.py +57 -0
- {httpx2-2.9.0 → httpx2-2.10.0}/httpx2/websockets/_api.py +34 -4
- {httpx2-2.9.0 → httpx2-2.10.0}/httpx2/websockets/_ping.py +6 -4
- {httpx2-2.9.0 → httpx2-2.10.0}/httpx2/websockets/_transport.py +3 -6
- {httpx2-2.9.0 → httpx2-2.10.0}/pyproject.toml +7 -5
- httpx2-2.9.0/httpx2/_alias.py +0 -58
- httpx2-2.9.0/httpx2/_sse.py +0 -158
- httpx2-2.9.0/httpx2/_transports/__init__.py +0 -15
- httpx2-2.9.0/httpx2/websockets/__init__.py +0 -35
- {httpx2-2.9.0 → httpx2-2.10.0}/.gitignore +0 -0
- {httpx2-2.9.0 → httpx2-2.10.0}/LICENSE.md +0 -0
- {httpx2-2.9.0 → httpx2-2.10.0}/httpx2/__init__.py +0 -0
- {httpx2-2.9.0 → httpx2-2.10.0}/httpx2/__version__.py +0 -0
- {httpx2-2.9.0 → httpx2-2.10.0}/httpx2/_api.py +0 -0
- {httpx2-2.9.0 → httpx2-2.10.0}/httpx2/_auth.py +0 -0
- {httpx2-2.9.0 → httpx2-2.10.0}/httpx2/_decoders.py +0 -0
- {httpx2-2.9.0 → httpx2-2.10.0}/httpx2/_exceptions.py +0 -0
- {httpx2-2.9.0 → httpx2-2.10.0}/httpx2/_main.py +0 -0
- {httpx2-2.9.0 → httpx2-2.10.0}/httpx2/_multipart.py +0 -0
- {httpx2-2.9.0 → httpx2-2.10.0}/httpx2/_transports/asgi.py +0 -0
- {httpx2-2.9.0 → httpx2-2.10.0}/httpx2/_transports/base.py +0 -0
- {httpx2-2.9.0 → httpx2-2.10.0}/httpx2/_transports/default.py +0 -0
- {httpx2-2.9.0 → httpx2-2.10.0}/httpx2/_transports/mock.py +0 -0
- {httpx2-2.9.0 → httpx2-2.10.0}/httpx2/_transports/wsgi.py +0 -0
- {httpx2-2.9.0 → httpx2-2.10.0}/httpx2/_types.py +0 -0
- {httpx2-2.9.0 → httpx2-2.10.0}/httpx2/_urlparse.py +0 -0
- {httpx2-2.9.0 → httpx2-2.10.0}/httpx2/_urls.py +0 -0
- {httpx2-2.9.0 → httpx2-2.10.0}/httpx2/_utils.py +0 -0
- {httpx2-2.9.0 → httpx2-2.10.0}/httpx2/py.typed +0 -0
- {httpx2-2.9.0 → httpx2-2.10.0}/httpx2/websockets/_exceptions.py +0 -0
|
@@ -4,6 +4,34 @@ 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.10.0 (August 9th, 2026)
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
|
|
11
|
+
* Add support for running on WebAssembly / Emscripten via Pyodide, using a JavaScript
|
|
12
|
+
`fetch`-based transport defined in `httpx2-jsfetch`.
|
|
13
|
+
([#1119](https://github.com/pydantic/httpx2/pull/1119))
|
|
14
|
+
* Add `max_event_size` to cap SSE event buffering. ([#1071](https://github.com/pydantic/httpx2/pull/1071))
|
|
15
|
+
* Add RFC 9110 status code constants. ([#1069](https://github.com/pydantic/httpx2/pull/1069))
|
|
16
|
+
* Add support for Python 3.15. ([#1090](https://github.com/pydantic/httpx2/pull/1090))
|
|
17
|
+
|
|
18
|
+
### Changed
|
|
19
|
+
|
|
20
|
+
* Improve SSE chunk buffering performance. ([#1117](https://github.com/pydantic/httpx2/pull/1117))
|
|
21
|
+
* Skip cookie extraction for responses without `Set-Cookie` headers. ([#1107](https://github.com/pydantic/httpx2/pull/1107))
|
|
22
|
+
* Return `str | None` instead of `Any` from `Headers.get`. ([#1121](https://github.com/pydantic/httpx2/pull/1121))
|
|
23
|
+
|
|
24
|
+
### Fixed
|
|
25
|
+
|
|
26
|
+
* Enforce the WebSocket max message size across fragmented messages. ([#1085](https://github.com/pydantic/httpx2/pull/1085))
|
|
27
|
+
* Ignore unsolicited and duplicate WebSocket Pong frames. ([#1122](https://github.com/pydantic/httpx2/pull/1122))
|
|
28
|
+
|
|
29
|
+
## 2.9.1 (July 24th, 2026)
|
|
30
|
+
|
|
31
|
+
### Fixed
|
|
32
|
+
|
|
33
|
+
* Alias `httpcore` imports to `httpcore2` in `alias_httpx()`. ([#1082](https://github.com/pydantic/httpx2/pull/1082))
|
|
34
|
+
|
|
7
35
|
## 2.9.0 (July 23rd, 2026)
|
|
8
36
|
|
|
9
37
|
### Added
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: httpx2
|
|
3
|
-
Version: 2.
|
|
3
|
+
Version: 2.10.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
|
|
@@ -23,18 +23,20 @@ Classifier: Programming Language :: Python :: 3.11
|
|
|
23
23
|
Classifier: Programming Language :: Python :: 3.12
|
|
24
24
|
Classifier: Programming Language :: Python :: 3.13
|
|
25
25
|
Classifier: Programming Language :: Python :: 3.14
|
|
26
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
26
27
|
Classifier: Topic :: Internet :: WWW/HTTP
|
|
27
28
|
Requires-Python: >=3.10
|
|
28
|
-
Requires-Dist: anyio>=4.10
|
|
29
|
-
Requires-Dist: httpcore2==2.
|
|
29
|
+
Requires-Dist: anyio>=4.10; sys_platform != 'emscripten'
|
|
30
|
+
Requires-Dist: httpcore2==2.10.0; sys_platform != 'emscripten'
|
|
31
|
+
Requires-Dist: httpx2-jsfetch; sys_platform == 'emscripten' and python_version >= '3.12'
|
|
30
32
|
Requires-Dist: idna>=3.18
|
|
31
|
-
Requires-Dist: truststore>=0.10
|
|
33
|
+
Requires-Dist: truststore>=0.10; sys_platform != 'emscripten'
|
|
32
34
|
Requires-Dist: typing-extensions>=4.5.0; python_version < '3.13'
|
|
33
35
|
Provides-Extra: brotli
|
|
34
36
|
Requires-Dist: brotli; (platform_python_implementation == 'CPython') and extra == 'brotli'
|
|
35
37
|
Requires-Dist: brotlicffi; (platform_python_implementation != 'CPython') and extra == 'brotli'
|
|
36
38
|
Provides-Extra: cli
|
|
37
|
-
Requires-Dist: click>=8.4; extra == 'cli'
|
|
39
|
+
Requires-Dist: click>=8.4.2; extra == 'cli'
|
|
38
40
|
Requires-Dist: pygments==2.*; extra == 'cli'
|
|
39
41
|
Requires-Dist: rich<16,>=10; extra == 'cli'
|
|
40
42
|
Provides-Extra: http2
|
|
@@ -155,6 +157,28 @@ The [Developer Interface](https://httpx2.pydantic.dev/api/) provides a comprehen
|
|
|
155
157
|
|
|
156
158
|
To find out about tools that integrate with HTTPX, see [Third Party Packages](https://httpx2.pydantic.dev/third_party_packages/).
|
|
157
159
|
|
|
160
|
+
## Observability with Pydantic Logfire
|
|
161
|
+
|
|
162
|
+
Install Logfire with HTTPX instrumentation support:
|
|
163
|
+
|
|
164
|
+
```shell
|
|
165
|
+
pip install 'logfire[httpx]'
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
HTTPX2 works out of the box with [Pydantic Logfire](https://pydantic.dev/logfire), our observability platform built on OpenTelemetry. One line instruments every request, giving you traces, timings, and status codes with no other changes:
|
|
169
|
+
|
|
170
|
+
```python
|
|
171
|
+
import logfire
|
|
172
|
+
import httpx2
|
|
173
|
+
|
|
174
|
+
logfire.configure()
|
|
175
|
+
logfire.instrument_httpx()
|
|
176
|
+
|
|
177
|
+
httpx2.get("https://pydantic.dev/")
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
This works the same way for explicit `httpx2.Client()` and `httpx2.AsyncClient()` instances, and you can scope instrumentation to a single client by passing it in: `logfire.instrument_httpx(client)`. Pass `capture_all=True` to also record headers and bodies. See the [Logfire HTTPX docs](https://logfire.pydantic.dev/docs/integrations/http-clients/httpx/) for the full set of options.
|
|
181
|
+
|
|
158
182
|
## Contribute
|
|
159
183
|
|
|
160
184
|
If you want to contribute with HTTPX2 check out the [Contributing Guide](https://httpx2.pydantic.dev/contributing/) to learn how to start.
|
|
@@ -190,7 +214,23 @@ inspiration around the lower-level networking details.
|
|
|
190
214
|
|
|
191
215
|
### Added
|
|
192
216
|
|
|
193
|
-
* Add
|
|
217
|
+
* Add support for running on WebAssembly / Emscripten via Pyodide, using a JavaScript
|
|
218
|
+
`fetch`-based transport defined in `httpx2-jsfetch`.
|
|
219
|
+
([#1119](https://github.com/pydantic/httpx2/pull/1119))
|
|
220
|
+
* Add `max_event_size` to cap SSE event buffering. ([#1071](https://github.com/pydantic/httpx2/pull/1071))
|
|
221
|
+
* Add RFC 9110 status code constants. ([#1069](https://github.com/pydantic/httpx2/pull/1069))
|
|
222
|
+
* Add support for Python 3.15. ([#1090](https://github.com/pydantic/httpx2/pull/1090))
|
|
223
|
+
|
|
224
|
+
### Changed
|
|
225
|
+
|
|
226
|
+
* Improve SSE chunk buffering performance. ([#1117](https://github.com/pydantic/httpx2/pull/1117))
|
|
227
|
+
* Skip cookie extraction for responses without `Set-Cookie` headers. ([#1107](https://github.com/pydantic/httpx2/pull/1107))
|
|
228
|
+
* Return `str | None` instead of `Any` from `Headers.get`. ([#1121](https://github.com/pydantic/httpx2/pull/1121))
|
|
229
|
+
|
|
230
|
+
### Fixed
|
|
231
|
+
|
|
232
|
+
* Enforce the WebSocket max message size across fragmented messages. ([#1085](https://github.com/pydantic/httpx2/pull/1085))
|
|
233
|
+
* Ignore unsolicited and duplicate WebSocket Pong frames. ([#1122](https://github.com/pydantic/httpx2/pull/1122))
|
|
194
234
|
|
|
195
235
|
|
|
196
236
|
---
|
|
@@ -106,6 +106,28 @@ The [Developer Interface](https://httpx2.pydantic.dev/api/) provides a comprehen
|
|
|
106
106
|
|
|
107
107
|
To find out about tools that integrate with HTTPX, see [Third Party Packages](https://httpx2.pydantic.dev/third_party_packages/).
|
|
108
108
|
|
|
109
|
+
## Observability with Pydantic Logfire
|
|
110
|
+
|
|
111
|
+
Install Logfire with HTTPX instrumentation support:
|
|
112
|
+
|
|
113
|
+
```shell
|
|
114
|
+
pip install 'logfire[httpx]'
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
HTTPX2 works out of the box with [Pydantic Logfire](https://pydantic.dev/logfire), our observability platform built on OpenTelemetry. One line instruments every request, giving you traces, timings, and status codes with no other changes:
|
|
118
|
+
|
|
119
|
+
```python
|
|
120
|
+
import logfire
|
|
121
|
+
import httpx2
|
|
122
|
+
|
|
123
|
+
logfire.configure()
|
|
124
|
+
logfire.instrument_httpx()
|
|
125
|
+
|
|
126
|
+
httpx2.get("https://pydantic.dev/")
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
This works the same way for explicit `httpx2.Client()` and `httpx2.AsyncClient()` instances, and you can scope instrumentation to a single client by passing it in: `logfire.instrument_httpx(client)`. Pass `capture_all=True` to also record headers and bodies. See the [Logfire HTTPX docs](https://logfire.pydantic.dev/docs/integrations/http-clients/httpx/) for the full set of options.
|
|
130
|
+
|
|
109
131
|
## Contribute
|
|
110
132
|
|
|
111
133
|
If you want to contribute with HTTPX2 check out the [Contributing Guide](https://httpx2.pydantic.dev/contributing/) to learn how to start.
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import importlib
|
|
4
|
+
import importlib.abc
|
|
5
|
+
import importlib.machinery
|
|
6
|
+
import importlib.util
|
|
7
|
+
import sys
|
|
8
|
+
from collections.abc import Sequence
|
|
9
|
+
from types import ModuleType
|
|
10
|
+
|
|
11
|
+
__all__ = ["alias_httpx"]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class _AliasLoader(importlib.abc.Loader):
|
|
15
|
+
_original_spec: importlib.machinery.ModuleSpec | None
|
|
16
|
+
|
|
17
|
+
def __init__(self, real_name: str) -> None:
|
|
18
|
+
self._real_name = real_name
|
|
19
|
+
|
|
20
|
+
def create_module(self, spec: importlib.machinery.ModuleSpec) -> ModuleType:
|
|
21
|
+
module = importlib.import_module(self._real_name)
|
|
22
|
+
self._original_spec = module.__spec__
|
|
23
|
+
return module
|
|
24
|
+
|
|
25
|
+
def exec_module(self, module: ModuleType) -> None:
|
|
26
|
+
module.__spec__ = self._original_spec
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class _AliasFinder(importlib.abc.MetaPathFinder):
|
|
30
|
+
def __init__(self, alias: str, real: str) -> None:
|
|
31
|
+
self._alias = alias
|
|
32
|
+
self._real = real
|
|
33
|
+
|
|
34
|
+
def find_spec(
|
|
35
|
+
self,
|
|
36
|
+
fullname: str,
|
|
37
|
+
path: Sequence[str] | None = None,
|
|
38
|
+
target: ModuleType | None = None,
|
|
39
|
+
) -> importlib.machinery.ModuleSpec | None:
|
|
40
|
+
if fullname != self._alias and not fullname.startswith(self._alias + "."):
|
|
41
|
+
return None
|
|
42
|
+
real_name = self._real + fullname.removeprefix(self._alias)
|
|
43
|
+
if real_name not in sys.modules and importlib.util.find_spec(real_name) is None:
|
|
44
|
+
return None
|
|
45
|
+
return importlib.machinery.ModuleSpec(fullname, _AliasLoader(real_name))
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _alias(alias: str, module: ModuleType) -> None:
|
|
49
|
+
existing = sys.modules.get(alias)
|
|
50
|
+
if existing is not None and existing is not module:
|
|
51
|
+
raise RuntimeError(f"{alias} was already imported; call `alias_httpx()` before any `import {alias}`.")
|
|
52
|
+
|
|
53
|
+
if not any(isinstance(finder, _AliasFinder) and finder._alias == alias for finder in sys.meta_path):
|
|
54
|
+
sys.meta_path.insert(0, _AliasFinder(alias, module.__name__))
|
|
55
|
+
sys.modules[alias] = module
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def alias_httpx() -> None:
|
|
59
|
+
"""
|
|
60
|
+
Make `import httpx` resolve to `httpx2`, and `import httpcore` to `httpcore2`, process-wide.
|
|
61
|
+
|
|
62
|
+
Intended for applications migrating from `httpx`, so that dependencies still
|
|
63
|
+
importing `httpx` or `httpcore` share the `httpx2` classes. Libraries should never call this.
|
|
64
|
+
|
|
65
|
+
Must be called before anything imports `httpx` or `httpcore`. Calling it again is a no-op.
|
|
66
|
+
"""
|
|
67
|
+
import httpcore2
|
|
68
|
+
import httpx2
|
|
69
|
+
|
|
70
|
+
_alias("httpx", httpx2)
|
|
71
|
+
_alias("httpcore", httpcore2)
|
|
@@ -16,6 +16,7 @@ from ._config import (
|
|
|
16
16
|
DEFAULT_KEEPALIVE_PING_INTERVAL_SECONDS,
|
|
17
17
|
DEFAULT_KEEPALIVE_PING_TIMEOUT_SECONDS,
|
|
18
18
|
DEFAULT_LIMITS,
|
|
19
|
+
DEFAULT_MAX_EVENT_SIZE_BYTES,
|
|
19
20
|
DEFAULT_MAX_MESSAGE_SIZE_BYTES,
|
|
20
21
|
DEFAULT_MAX_REDIRECTS,
|
|
21
22
|
DEFAULT_QUEUE_SIZE,
|
|
@@ -34,8 +35,8 @@ from ._exceptions import (
|
|
|
34
35
|
from ._models import Cookies, Headers, Request, Response
|
|
35
36
|
from ._sse import EventSource
|
|
36
37
|
from ._status_codes import codes
|
|
38
|
+
from ._transports import AsyncHTTPTransport, HTTPTransport
|
|
37
39
|
from ._transports.base import AsyncBaseTransport, BaseTransport
|
|
38
|
-
from ._transports.default import AsyncHTTPTransport, HTTPTransport
|
|
39
40
|
from ._types import (
|
|
40
41
|
AsyncByteStream,
|
|
41
42
|
AuthTypes,
|
|
@@ -871,6 +872,7 @@ class Client(BaseClient):
|
|
|
871
872
|
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
|
|
872
873
|
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
|
873
874
|
extensions: RequestExtensions | None = None,
|
|
875
|
+
max_event_size: int | None = DEFAULT_MAX_EVENT_SIZE_BYTES,
|
|
874
876
|
) -> Generator[EventSource]:
|
|
875
877
|
"""
|
|
876
878
|
Connect to a server-sent events endpoint and yield an `EventSource`.
|
|
@@ -894,7 +896,7 @@ class Client(BaseClient):
|
|
|
894
896
|
timeout=timeout,
|
|
895
897
|
extensions=extensions,
|
|
896
898
|
) as response:
|
|
897
|
-
yield EventSource(response)
|
|
899
|
+
yield EventSource(response, max_event_size=max_event_size)
|
|
898
900
|
|
|
899
901
|
@contextmanager
|
|
900
902
|
def websocket(
|
|
@@ -1708,6 +1710,7 @@ class AsyncClient(BaseClient):
|
|
|
1708
1710
|
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
|
|
1709
1711
|
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
|
1710
1712
|
extensions: RequestExtensions | None = None,
|
|
1713
|
+
max_event_size: int | None = DEFAULT_MAX_EVENT_SIZE_BYTES,
|
|
1711
1714
|
) -> AsyncGenerator[EventSource]:
|
|
1712
1715
|
"""
|
|
1713
1716
|
Connect to a server-sent events endpoint and yield an `EventSource`.
|
|
@@ -1731,7 +1734,7 @@ class AsyncClient(BaseClient):
|
|
|
1731
1734
|
timeout=timeout,
|
|
1732
1735
|
extensions=extensions,
|
|
1733
1736
|
) as response:
|
|
1734
|
-
yield EventSource(response)
|
|
1737
|
+
yield EventSource(response, max_event_size=max_event_size)
|
|
1735
1738
|
|
|
1736
1739
|
@asynccontextmanager
|
|
1737
1740
|
async def websocket(
|
|
@@ -248,6 +248,8 @@ DEFAULT_TIMEOUT_CONFIG = Timeout(timeout=5.0)
|
|
|
248
248
|
DEFAULT_LIMITS = Limits(max_connections=100, max_keepalive_connections=20)
|
|
249
249
|
DEFAULT_MAX_REDIRECTS = 20
|
|
250
250
|
|
|
251
|
+
DEFAULT_MAX_EVENT_SIZE_BYTES = 1024 * 1024
|
|
252
|
+
|
|
251
253
|
DEFAULT_MAX_MESSAGE_SIZE_BYTES = 65_536
|
|
252
254
|
DEFAULT_QUEUE_SIZE = 512
|
|
253
255
|
DEFAULT_KEEPALIVE_PING_INTERVAL_SECONDS = 20.0
|
|
@@ -119,7 +119,7 @@ def encode_content(
|
|
|
119
119
|
headers = {"Transfer-Encoding": "chunked"}
|
|
120
120
|
else:
|
|
121
121
|
headers = {"Content-Length": str(content_length_or_none)}
|
|
122
|
-
return headers, IteratorByteStream(content)
|
|
122
|
+
return headers, IteratorByteStream(content)
|
|
123
123
|
|
|
124
124
|
elif isinstance(content, AsyncIterable):
|
|
125
125
|
headers = {"Transfer-Encoding": "chunked"}
|
|
@@ -51,6 +51,8 @@ __all__ = ["Cookies", "Headers", "Request", "Response"]
|
|
|
51
51
|
|
|
52
52
|
SENSITIVE_HEADERS = {"authorization", "proxy-authorization"}
|
|
53
53
|
|
|
54
|
+
_T = typing.TypeVar("_T")
|
|
55
|
+
|
|
54
56
|
|
|
55
57
|
def _is_known_encoding(encoding: str) -> bool:
|
|
56
58
|
"""
|
|
@@ -235,7 +237,13 @@ class Headers(typing.MutableMapping[str, str]):
|
|
|
235
237
|
"""
|
|
236
238
|
return [(key.decode(self.encoding), value.decode(self.encoding)) for _, key, value in self._list]
|
|
237
239
|
|
|
238
|
-
|
|
240
|
+
@typing.overload
|
|
241
|
+
def get(self, key: str, /) -> str | None: ...
|
|
242
|
+
|
|
243
|
+
@typing.overload
|
|
244
|
+
def get(self, key: str, default: _T) -> str | _T: ...
|
|
245
|
+
|
|
246
|
+
def get(self, key: str, default: _T | None = None) -> str | _T | None:
|
|
239
247
|
"""
|
|
240
248
|
Return a header value. If multiple occurrences of the header occur
|
|
241
249
|
then concatenate them together with commas.
|
|
@@ -1079,6 +1087,9 @@ class Cookies(typing.MutableMapping[str, str]):
|
|
|
1079
1087
|
"""
|
|
1080
1088
|
Loads any cookies based on the response `Set-Cookie` headers.
|
|
1081
1089
|
"""
|
|
1090
|
+
if "set-cookie" not in response.headers and "set-cookie2" not in response.headers:
|
|
1091
|
+
return
|
|
1092
|
+
|
|
1082
1093
|
urllib_response = self._CookieCompatResponse(response)
|
|
1083
1094
|
urllib_request = self._CookieCompatRequest(response.request)
|
|
1084
1095
|
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Server-sent events support, derived from httpx-sse (https://github.com/florimondmanca/httpx-sse).
|
|
3
|
+
|
|
4
|
+
```
|
|
5
|
+
MIT License
|
|
6
|
+
|
|
7
|
+
Copyright (c) 2022 Florimond Manca
|
|
8
|
+
|
|
9
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
10
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
11
|
+
in the Software without restriction, including without limitation the rights
|
|
12
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
13
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
14
|
+
furnished to do so, subject to the following conditions:
|
|
15
|
+
|
|
16
|
+
The above copyright notice and this permission notice shall be included in all
|
|
17
|
+
copies or substantial portions of the Software.
|
|
18
|
+
|
|
19
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
20
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
21
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
22
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
23
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
24
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
25
|
+
SOFTWARE.
|
|
26
|
+
```
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
import json as jsonlib
|
|
32
|
+
from collections.abc import AsyncIterator, Iterator
|
|
33
|
+
from dataclasses import dataclass
|
|
34
|
+
|
|
35
|
+
from ._config import DEFAULT_MAX_EVENT_SIZE_BYTES
|
|
36
|
+
from ._exceptions import TransportError, request_context
|
|
37
|
+
from ._models import Response
|
|
38
|
+
|
|
39
|
+
__all__ = ["EventSource", "SSEError", "ServerSentEvent"]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class SSEError(TransportError):
|
|
43
|
+
"""
|
|
44
|
+
An error that occurred while connecting to a server-sent events endpoint.
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass(frozen=True)
|
|
49
|
+
class ServerSentEvent:
|
|
50
|
+
event: str = "message"
|
|
51
|
+
data: str = ""
|
|
52
|
+
id: str = ""
|
|
53
|
+
retry: int | None = None
|
|
54
|
+
|
|
55
|
+
def json(self) -> object:
|
|
56
|
+
return jsonlib.loads(self.data)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class _SSEEventDecoder:
|
|
60
|
+
def __init__(self, max_event_size: int | None = None) -> None:
|
|
61
|
+
self._max_event_size = max_event_size
|
|
62
|
+
self._event = ""
|
|
63
|
+
self._data: list[str] = []
|
|
64
|
+
self._event_size = 0
|
|
65
|
+
self._last_event_id = ""
|
|
66
|
+
self._retry: int | None = None
|
|
67
|
+
self._pending = False
|
|
68
|
+
|
|
69
|
+
def decode(self, line: str) -> ServerSentEvent | None:
|
|
70
|
+
if not line:
|
|
71
|
+
self._event_size = 0
|
|
72
|
+
if not self._pending:
|
|
73
|
+
return None
|
|
74
|
+
|
|
75
|
+
sse = ServerSentEvent(
|
|
76
|
+
event=self._event or "message",
|
|
77
|
+
data="\n".join(self._data),
|
|
78
|
+
id=self._last_event_id,
|
|
79
|
+
retry=self._retry,
|
|
80
|
+
)
|
|
81
|
+
self._event = ""
|
|
82
|
+
self._data = []
|
|
83
|
+
self._retry = None
|
|
84
|
+
self._pending = False
|
|
85
|
+
return sse
|
|
86
|
+
|
|
87
|
+
if line.startswith(":"):
|
|
88
|
+
return None
|
|
89
|
+
|
|
90
|
+
self._event_size += len(line.encode("utf-8"))
|
|
91
|
+
self._check_size()
|
|
92
|
+
|
|
93
|
+
fieldname, _, value = line.partition(":")
|
|
94
|
+
value = value[1:] if value.startswith(" ") else value
|
|
95
|
+
|
|
96
|
+
if fieldname == "event":
|
|
97
|
+
self._event = value
|
|
98
|
+
self._pending = True
|
|
99
|
+
elif fieldname == "data":
|
|
100
|
+
self._data.append(value)
|
|
101
|
+
self._pending = True
|
|
102
|
+
elif fieldname == "id":
|
|
103
|
+
if "\0" not in value:
|
|
104
|
+
self._last_event_id = value
|
|
105
|
+
self._pending = True
|
|
106
|
+
elif fieldname == "retry":
|
|
107
|
+
try:
|
|
108
|
+
self._retry = int(value)
|
|
109
|
+
self._pending = True
|
|
110
|
+
except ValueError:
|
|
111
|
+
pass
|
|
112
|
+
|
|
113
|
+
return None
|
|
114
|
+
|
|
115
|
+
def check_pending(self, pending_size: int) -> None:
|
|
116
|
+
"""
|
|
117
|
+
Bound the total bytes buffered for the in-progress event, including
|
|
118
|
+
a trailing line that has not been terminated by a newline yet.
|
|
119
|
+
"""
|
|
120
|
+
self._check_size(pending_size)
|
|
121
|
+
|
|
122
|
+
def _check_size(self, pending_size: int = 0) -> None:
|
|
123
|
+
if self._max_event_size is not None and self._event_size + pending_size > self._max_event_size:
|
|
124
|
+
raise SSEError(f"Server-sent event exceeded the {self._max_event_size} byte limit.")
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class _SSELineDecoder:
|
|
128
|
+
def __init__(self) -> None:
|
|
129
|
+
self._parts: list[str] = []
|
|
130
|
+
self._pending_size = 0
|
|
131
|
+
self._trailing_cr = False
|
|
132
|
+
|
|
133
|
+
@property
|
|
134
|
+
def pending_size(self) -> int:
|
|
135
|
+
return self._pending_size
|
|
136
|
+
|
|
137
|
+
def decode(self, text: str) -> list[str]:
|
|
138
|
+
if self._trailing_cr:
|
|
139
|
+
text = "\r" + text
|
|
140
|
+
self._trailing_cr = False
|
|
141
|
+
if text.endswith("\r"):
|
|
142
|
+
self._trailing_cr = True
|
|
143
|
+
text = text[:-1]
|
|
144
|
+
|
|
145
|
+
text = text.replace("\r\n", "\n").replace("\r", "\n")
|
|
146
|
+
if "\n" not in text:
|
|
147
|
+
self._append(text)
|
|
148
|
+
return []
|
|
149
|
+
|
|
150
|
+
lines = text.split("\n")
|
|
151
|
+
self._append(lines[0])
|
|
152
|
+
lines[0] = self._consume_pending()
|
|
153
|
+
self._append(lines.pop())
|
|
154
|
+
return lines
|
|
155
|
+
|
|
156
|
+
def flush(self) -> list[str]:
|
|
157
|
+
if self._trailing_cr:
|
|
158
|
+
self._append("\n")
|
|
159
|
+
self._trailing_cr = False
|
|
160
|
+
buffer = self._consume_pending()
|
|
161
|
+
if not buffer:
|
|
162
|
+
return []
|
|
163
|
+
return buffer.split("\n")
|
|
164
|
+
|
|
165
|
+
def _append(self, text: str) -> None:
|
|
166
|
+
if text:
|
|
167
|
+
self._parts.append(text)
|
|
168
|
+
self._pending_size += len(text.encode("utf-8"))
|
|
169
|
+
|
|
170
|
+
def _consume_pending(self) -> str:
|
|
171
|
+
pending = "".join(self._parts)
|
|
172
|
+
self._parts = []
|
|
173
|
+
self._pending_size = 0
|
|
174
|
+
return pending
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
class _SSEParser:
|
|
178
|
+
def __init__(self, max_event_size: int | None = None) -> None:
|
|
179
|
+
self._event_decoder = _SSEEventDecoder(max_event_size)
|
|
180
|
+
self._line_decoder = _SSELineDecoder()
|
|
181
|
+
|
|
182
|
+
def decode(self, text: str) -> Iterator[ServerSentEvent]:
|
|
183
|
+
yield from self._decode_lines(self._line_decoder.decode(text))
|
|
184
|
+
self._event_decoder.check_pending(self._line_decoder.pending_size)
|
|
185
|
+
|
|
186
|
+
def flush(self) -> Iterator[ServerSentEvent]:
|
|
187
|
+
yield from self._decode_lines(self._line_decoder.flush())
|
|
188
|
+
|
|
189
|
+
def _decode_lines(self, lines: list[str]) -> Iterator[ServerSentEvent]:
|
|
190
|
+
for line in lines:
|
|
191
|
+
sse = self._event_decoder.decode(line)
|
|
192
|
+
if sse is not None:
|
|
193
|
+
yield sse
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
class EventSource:
|
|
197
|
+
def __init__(self, response: Response, max_event_size: int | None = DEFAULT_MAX_EVENT_SIZE_BYTES) -> None:
|
|
198
|
+
self._response = response
|
|
199
|
+
self._max_event_size = max_event_size
|
|
200
|
+
|
|
201
|
+
@property
|
|
202
|
+
def response(self) -> Response:
|
|
203
|
+
return self._response
|
|
204
|
+
|
|
205
|
+
def _check_content_type(self) -> None:
|
|
206
|
+
content_type, _, _ = self._response.headers.get("content-type", "").partition(";")
|
|
207
|
+
if content_type.strip().lower() != "text/event-stream":
|
|
208
|
+
raise SSEError(f"Expected response with content type 'text/event-stream', got {content_type.strip()!r}.")
|
|
209
|
+
|
|
210
|
+
def __iter__(self) -> Iterator[ServerSentEvent]:
|
|
211
|
+
with request_context(request=self._response.request):
|
|
212
|
+
self._check_content_type()
|
|
213
|
+
parser = _SSEParser(self._max_event_size)
|
|
214
|
+
for chunk in self._response.iter_text():
|
|
215
|
+
yield from parser.decode(chunk)
|
|
216
|
+
yield from parser.flush()
|
|
217
|
+
|
|
218
|
+
async def __aiter__(self) -> AsyncIterator[ServerSentEvent]:
|
|
219
|
+
with request_context(request=self._response.request):
|
|
220
|
+
self._check_content_type()
|
|
221
|
+
parser = _SSEParser(self._max_event_size)
|
|
222
|
+
async for chunk in self._response.aiter_text():
|
|
223
|
+
for sse in parser.decode(chunk):
|
|
224
|
+
yield sse
|
|
225
|
+
for sse in parser.flush():
|
|
226
|
+
yield sse
|
|
@@ -1,21 +1,43 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
import warnings
|
|
4
|
+
from enum import EnumMeta, IntEnum
|
|
4
5
|
|
|
5
6
|
__all__ = ["codes"]
|
|
6
7
|
|
|
7
|
-
|
|
8
|
-
|
|
8
|
+
# Constant names that were renamed by RFC 9110, kept as deprecated aliases
|
|
9
|
+
# mapping each old name to its canonical replacement.
|
|
10
|
+
_DEPRECATED_CODES = {
|
|
11
|
+
"REQUEST_ENTITY_TOO_LARGE": "CONTENT_TOO_LARGE",
|
|
12
|
+
"REQUEST_URI_TOO_LONG": "URI_TOO_LONG",
|
|
13
|
+
"REQUESTED_RANGE_NOT_SATISFIABLE": "RANGE_NOT_SATISFIABLE",
|
|
14
|
+
"UNPROCESSABLE_ENTITY": "UNPROCESSABLE_CONTENT",
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class _CodesMeta(EnumMeta):
|
|
19
|
+
def __getattr__(cls, name: str) -> codes:
|
|
20
|
+
if name in _DEPRECATED_CODES:
|
|
21
|
+
new_name = _DEPRECATED_CODES[name]
|
|
22
|
+
warnings.warn(
|
|
23
|
+
f"'{name}' is deprecated. Use '{new_name}' instead.",
|
|
24
|
+
category=DeprecationWarning,
|
|
25
|
+
stacklevel=2,
|
|
26
|
+
)
|
|
27
|
+
return cls[new_name]
|
|
28
|
+
raise AttributeError(name)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class codes(IntEnum, metaclass=_CodesMeta):
|
|
9
32
|
"""HTTP status codes and reason phrases
|
|
10
33
|
|
|
11
34
|
Status codes from the following RFCs are all observed:
|
|
12
35
|
|
|
13
|
-
* RFC
|
|
36
|
+
* RFC 9110: HTTP Semantics, obsoletes 7231 & 7238
|
|
14
37
|
* RFC 6585: Additional HTTP Status Codes
|
|
15
38
|
* RFC 3229: Delta encoding in HTTP
|
|
16
39
|
* RFC 4918: HTTP Extensions for WebDAV, obsoletes 2518
|
|
17
40
|
* RFC 5842: Binding Extensions to WebDAV
|
|
18
|
-
* RFC 7238: Permanent Redirect
|
|
19
41
|
* RFC 2295: Transparent Content Negotiation in HTTP
|
|
20
42
|
* RFC 2774: An HTTP Extension Framework
|
|
21
43
|
* RFC 7540: Hypertext Transfer Protocol Version 2 (HTTP/2)
|
|
@@ -126,14 +148,14 @@ class codes(IntEnum):
|
|
|
126
148
|
GONE = 410, "Gone"
|
|
127
149
|
LENGTH_REQUIRED = 411, "Length Required"
|
|
128
150
|
PRECONDITION_FAILED = 412, "Precondition Failed"
|
|
129
|
-
|
|
130
|
-
|
|
151
|
+
CONTENT_TOO_LARGE = 413, "Content Too Large"
|
|
152
|
+
URI_TOO_LONG = 414, "URI Too Long"
|
|
131
153
|
UNSUPPORTED_MEDIA_TYPE = 415, "Unsupported Media Type"
|
|
132
|
-
|
|
154
|
+
RANGE_NOT_SATISFIABLE = 416, "Range Not Satisfiable"
|
|
133
155
|
EXPECTATION_FAILED = 417, "Expectation Failed"
|
|
134
156
|
IM_A_TEAPOT = 418, "I'm a teapot"
|
|
135
157
|
MISDIRECTED_REQUEST = 421, "Misdirected Request"
|
|
136
|
-
|
|
158
|
+
UNPROCESSABLE_CONTENT = 422, "Unprocessable Content"
|
|
137
159
|
LOCKED = 423, "Locked"
|
|
138
160
|
FAILED_DEPENDENCY = 424, "Failed Dependency"
|
|
139
161
|
TOO_EARLY = 425, "Too Early"
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
|
|
3
|
+
from .asgi import ASGITransport
|
|
4
|
+
from .base import AsyncBaseTransport, BaseTransport
|
|
5
|
+
from .mock import MockTransport
|
|
6
|
+
from .wsgi import WSGITransport
|
|
7
|
+
|
|
8
|
+
if sys.platform == "emscripten": # pragma: nocover
|
|
9
|
+
if sys.version_info < (3, 12):
|
|
10
|
+
raise RuntimeError("httpx2 requires Python 3.12+ on Emscripten.")
|
|
11
|
+
|
|
12
|
+
from httpx2_jsfetch import (
|
|
13
|
+
AsyncJavascriptFetchTransport as AsyncHTTPTransport,
|
|
14
|
+
JavascriptFetchTransport as HTTPTransport,
|
|
15
|
+
)
|
|
16
|
+
else:
|
|
17
|
+
from .default import AsyncHTTPTransport, HTTPTransport
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"ASGITransport",
|
|
21
|
+
"AsyncBaseTransport",
|
|
22
|
+
"BaseTransport",
|
|
23
|
+
"AsyncHTTPTransport",
|
|
24
|
+
"HTTPTransport",
|
|
25
|
+
"MockTransport",
|
|
26
|
+
"WSGITransport",
|
|
27
|
+
]
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""
|
|
2
|
+
WebSocket support, derived from httpx-ws (https://github.com/frankie567/httpx-ws).
|
|
3
|
+
|
|
4
|
+
```
|
|
5
|
+
MIT License
|
|
6
|
+
|
|
7
|
+
Copyright (c) 2021 François Voron
|
|
8
|
+
|
|
9
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
10
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
11
|
+
in the Software without restriction, including without limitation the rights
|
|
12
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
13
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
14
|
+
furnished to do so, subject to the following conditions:
|
|
15
|
+
|
|
16
|
+
The above copyright notice and this permission notice shall be included in all
|
|
17
|
+
copies or substantial portions of the Software.
|
|
18
|
+
|
|
19
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
20
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
21
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
22
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
23
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
24
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
25
|
+
SOFTWARE.
|
|
26
|
+
```
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from ._api import (
|
|
30
|
+
AsyncWebSocketClient,
|
|
31
|
+
AsyncWebSocketSession,
|
|
32
|
+
JSONMode,
|
|
33
|
+
WebSocketClient,
|
|
34
|
+
WebSocketSession,
|
|
35
|
+
)
|
|
36
|
+
from ._exceptions import (
|
|
37
|
+
HTTPXWSException,
|
|
38
|
+
WebSocketDisconnect,
|
|
39
|
+
WebSocketInvalidTypeReceived,
|
|
40
|
+
WebSocketNetworkError,
|
|
41
|
+
WebSocketUpgradeError,
|
|
42
|
+
)
|
|
43
|
+
from ._transport import ASGIWebSocketTransport
|
|
44
|
+
|
|
45
|
+
__all__ = [
|
|
46
|
+
"ASGIWebSocketTransport",
|
|
47
|
+
"AsyncWebSocketClient",
|
|
48
|
+
"AsyncWebSocketSession",
|
|
49
|
+
"HTTPXWSException",
|
|
50
|
+
"JSONMode",
|
|
51
|
+
"WebSocketClient",
|
|
52
|
+
"WebSocketDisconnect",
|
|
53
|
+
"WebSocketInvalidTypeReceived",
|
|
54
|
+
"WebSocketNetworkError",
|
|
55
|
+
"WebSocketSession",
|
|
56
|
+
"WebSocketUpgradeError",
|
|
57
|
+
]
|
|
@@ -504,6 +504,7 @@ class WebSocketSession:
|
|
|
504
504
|
import httpcore2
|
|
505
505
|
|
|
506
506
|
partial_message_buffer: str | bytes | None = None
|
|
507
|
+
partial_message_size = 0
|
|
507
508
|
try:
|
|
508
509
|
while not self._should_close.is_set():
|
|
509
510
|
data = self._wait_until_closed(self._read_stream, max_bytes)
|
|
@@ -520,6 +521,11 @@ class WebSocketSession:
|
|
|
520
521
|
if isinstance(event, wsproto.events.CloseConnection):
|
|
521
522
|
self._should_close.set()
|
|
522
523
|
if isinstance(event, wsproto.events.Message):
|
|
524
|
+
partial_message_size += len(event.data.encode() if isinstance(event.data, str) else event.data)
|
|
525
|
+
if partial_message_size > max_bytes:
|
|
526
|
+
self.close(CloseReason.MESSAGE_TOO_BIG, "Message too big")
|
|
527
|
+
self._events.put(WebSocketDisconnect(CloseReason.MESSAGE_TOO_BIG, "Message too big"))
|
|
528
|
+
break
|
|
523
529
|
# Unfinished message: bufferize
|
|
524
530
|
if not event.message_finished:
|
|
525
531
|
if partial_message_buffer is None:
|
|
@@ -528,12 +534,14 @@ class WebSocketSession:
|
|
|
528
534
|
partial_message_buffer += event.data
|
|
529
535
|
# Finished message but no buffer: just emit the event
|
|
530
536
|
elif partial_message_buffer is None:
|
|
537
|
+
partial_message_size = 0
|
|
531
538
|
self._events.put(event)
|
|
532
539
|
# Finished message with buffer: emit the full event
|
|
533
540
|
else:
|
|
534
541
|
event_type = type(event)
|
|
535
542
|
full_message_event = event_type(partial_message_buffer + event.data)
|
|
536
543
|
partial_message_buffer = None
|
|
544
|
+
partial_message_size = 0
|
|
537
545
|
self._events.put(full_message_event)
|
|
538
546
|
continue
|
|
539
547
|
self._events.put(event)
|
|
@@ -1065,6 +1073,7 @@ class AsyncWebSocketSession(anyio.AsyncContextManagerMixin):
|
|
|
1065
1073
|
import httpcore2
|
|
1066
1074
|
|
|
1067
1075
|
partial_message_buffer: str | bytes | None = None
|
|
1076
|
+
partial_message_size = 0
|
|
1068
1077
|
try:
|
|
1069
1078
|
while not self._should_close.is_set():
|
|
1070
1079
|
data = await self._read_stream(max_bytes)
|
|
@@ -1081,6 +1090,13 @@ class AsyncWebSocketSession(anyio.AsyncContextManagerMixin):
|
|
|
1081
1090
|
if isinstance(event, wsproto.events.CloseConnection):
|
|
1082
1091
|
self._should_close.set()
|
|
1083
1092
|
if isinstance(event, wsproto.events.Message):
|
|
1093
|
+
partial_message_size += len(event.data.encode() if isinstance(event.data, str) else event.data)
|
|
1094
|
+
if partial_message_size > max_bytes:
|
|
1095
|
+
await self.close(CloseReason.MESSAGE_TOO_BIG, "Message too big")
|
|
1096
|
+
await self._send_event.send(
|
|
1097
|
+
WebSocketDisconnect(CloseReason.MESSAGE_TOO_BIG, "Message too big")
|
|
1098
|
+
)
|
|
1099
|
+
break
|
|
1084
1100
|
# Unfinished message: bufferize
|
|
1085
1101
|
if not event.message_finished:
|
|
1086
1102
|
if partial_message_buffer is None:
|
|
@@ -1089,12 +1105,14 @@ class AsyncWebSocketSession(anyio.AsyncContextManagerMixin):
|
|
|
1089
1105
|
partial_message_buffer += event.data
|
|
1090
1106
|
# Finished message but no buffer: just emit the event
|
|
1091
1107
|
elif partial_message_buffer is None:
|
|
1108
|
+
partial_message_size = 0
|
|
1092
1109
|
await self._send_event.send(event)
|
|
1093
1110
|
# Finished message with buffer: emit the full event
|
|
1094
1111
|
else:
|
|
1095
1112
|
event_type = type(event)
|
|
1096
1113
|
full_message_event = event_type(partial_message_buffer + event.data)
|
|
1097
1114
|
partial_message_buffer = None
|
|
1115
|
+
partial_message_size = 0
|
|
1098
1116
|
await self._send_event.send(full_message_event)
|
|
1099
1117
|
continue
|
|
1100
1118
|
await self._send_event.send(event)
|
|
@@ -1151,7 +1169,10 @@ class WebSocketClient(typing.Generic[SyncSession]):
|
|
|
1151
1169
|
client:
|
|
1152
1170
|
HTTPX client to use.
|
|
1153
1171
|
max_message_size_bytes:
|
|
1154
|
-
|
|
1172
|
+
Maximum incoming message size in bytes.
|
|
1173
|
+
Larger messages, including fragmented messages whose
|
|
1174
|
+
cumulative size exceeds the limit, close the connection
|
|
1175
|
+
with `MESSAGE_TOO_BIG`.
|
|
1155
1176
|
Defaults to 65 KiB.
|
|
1156
1177
|
queue_size:
|
|
1157
1178
|
Size of the queue where the received messages will be held
|
|
@@ -1300,7 +1321,10 @@ def connect_ws(
|
|
|
1300
1321
|
HTTPX client to use.
|
|
1301
1322
|
If not provided, a default one will be initialized.
|
|
1302
1323
|
max_message_size_bytes:
|
|
1303
|
-
|
|
1324
|
+
Maximum incoming message size in bytes.
|
|
1325
|
+
Larger messages, including fragmented messages whose
|
|
1326
|
+
cumulative size exceeds the limit, close the connection
|
|
1327
|
+
with `MESSAGE_TOO_BIG`.
|
|
1304
1328
|
Defaults to 65 KiB.
|
|
1305
1329
|
queue_size:
|
|
1306
1330
|
Size of the queue where the received messages will be held
|
|
@@ -1394,7 +1418,10 @@ class AsyncWebSocketClient(typing.Generic[AsyncSession]):
|
|
|
1394
1418
|
client:
|
|
1395
1419
|
HTTPX client to use.
|
|
1396
1420
|
max_message_size_bytes:
|
|
1397
|
-
|
|
1421
|
+
Maximum incoming message size in bytes.
|
|
1422
|
+
Larger messages, including fragmented messages whose
|
|
1423
|
+
cumulative size exceeds the limit, close the connection
|
|
1424
|
+
with `MESSAGE_TOO_BIG`.
|
|
1398
1425
|
Defaults to 65 KiB.
|
|
1399
1426
|
queue_size:
|
|
1400
1427
|
Size of the queue where the received messages will be held
|
|
@@ -1543,7 +1570,10 @@ async def aconnect_ws(
|
|
|
1543
1570
|
HTTPX client to use.
|
|
1544
1571
|
If not provided, a default one will be initialized.
|
|
1545
1572
|
max_message_size_bytes:
|
|
1546
|
-
|
|
1573
|
+
Maximum incoming message size in bytes.
|
|
1574
|
+
Larger messages, including fragmented messages whose
|
|
1575
|
+
cumulative size exceeds the limit, close the connection
|
|
1576
|
+
with `MESSAGE_TOO_BIG`.
|
|
1547
1577
|
Defaults to 65 KiB.
|
|
1548
1578
|
queue_size:
|
|
1549
1579
|
Size of the queue where the received messages will be held
|
|
@@ -22,8 +22,9 @@ class PingManager(PingManagerBase):
|
|
|
22
22
|
return ping_id, event
|
|
23
23
|
|
|
24
24
|
def ack(self, ping_id: bytes | bytearray) -> None:
|
|
25
|
-
event = self._pings.pop(bytes(ping_id))
|
|
26
|
-
event
|
|
25
|
+
event = self._pings.pop(bytes(ping_id), None)
|
|
26
|
+
if event is not None:
|
|
27
|
+
event.set()
|
|
27
28
|
|
|
28
29
|
|
|
29
30
|
class AsyncPingManager(PingManagerBase):
|
|
@@ -37,5 +38,6 @@ class AsyncPingManager(PingManagerBase):
|
|
|
37
38
|
return ping_id, event
|
|
38
39
|
|
|
39
40
|
def ack(self, ping_id: bytes | bytearray) -> None:
|
|
40
|
-
event = self._pings.pop(bytes(ping_id))
|
|
41
|
-
event
|
|
41
|
+
event = self._pings.pop(bytes(ping_id), None)
|
|
42
|
+
if event is not None:
|
|
43
|
+
event.set()
|
|
@@ -7,6 +7,7 @@ from types import TracebackType
|
|
|
7
7
|
|
|
8
8
|
import anyio
|
|
9
9
|
import wsproto
|
|
10
|
+
from anyio.streams.stapled import StapledObjectStream
|
|
10
11
|
from wsproto.frame_protocol import CloseReason
|
|
11
12
|
|
|
12
13
|
from .._models import Request, Response
|
|
@@ -45,12 +46,8 @@ class ASGIWebSocketAsyncNetworkStream:
|
|
|
45
46
|
) -> None:
|
|
46
47
|
self.app = app
|
|
47
48
|
self.scope = scope
|
|
48
|
-
self._receive_queue = anyio.
|
|
49
|
-
|
|
50
|
-
)
|
|
51
|
-
self._send_queue = anyio.streams.stapled.StapledObjectStream(
|
|
52
|
-
*anyio.create_memory_object_stream[Message](max_buffer_size=math.inf)
|
|
53
|
-
)
|
|
49
|
+
self._receive_queue = StapledObjectStream(*anyio.create_memory_object_stream[Message](max_buffer_size=math.inf))
|
|
50
|
+
self._send_queue = StapledObjectStream(*anyio.create_memory_object_stream[Message](max_buffer_size=math.inf))
|
|
54
51
|
self._task_group = task_group
|
|
55
52
|
self._initial_receive_timeout = initial_receive_timeout
|
|
56
53
|
self.connection = wsproto.WSConnection(wsproto.ConnectionType.SERVER)
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
[build-system]
|
|
2
|
-
requires = ["hatchling", "hatch-fancy-pypi-readme", "uv-dynamic-versioning>=0.
|
|
2
|
+
requires = ["hatchling", "hatch-fancy-pypi-readme", "uv-dynamic-versioning>=0.14.0"]
|
|
3
3
|
build-backend = "hatchling.build"
|
|
4
4
|
|
|
5
5
|
[tool.hatch.version]
|
|
@@ -38,15 +38,17 @@ classifiers = [
|
|
|
38
38
|
"Programming Language :: Python :: 3.12",
|
|
39
39
|
"Programming Language :: Python :: 3.13",
|
|
40
40
|
"Programming Language :: Python :: 3.14",
|
|
41
|
+
"Programming Language :: Python :: 3.15",
|
|
41
42
|
"Topic :: Internet :: WWW/HTTP",
|
|
42
43
|
]
|
|
43
44
|
dynamic = ["readme", "version", "dependencies"]
|
|
44
45
|
|
|
45
46
|
[tool.hatch.metadata.hooks.uv-dynamic-versioning]
|
|
46
47
|
dependencies = [
|
|
47
|
-
"truststore>=0.10",
|
|
48
|
-
"httpcore2=={{ version }}",
|
|
49
|
-
"anyio>=4.10",
|
|
48
|
+
"truststore>=0.10; sys_platform != 'emscripten'",
|
|
49
|
+
"httpcore2=={{ version }}; sys_platform != 'emscripten'",
|
|
50
|
+
"anyio>=4.10; sys_platform != 'emscripten'",
|
|
51
|
+
"httpx2-jsfetch; sys_platform == 'emscripten' and python_version >= '3.12'",
|
|
50
52
|
"idna>=3.18",
|
|
51
53
|
"typing_extensions>=4.5.0; python_version < '3.13'",
|
|
52
54
|
]
|
|
@@ -57,7 +59,7 @@ brotli = [
|
|
|
57
59
|
"brotlicffi; platform_python_implementation != 'CPython'",
|
|
58
60
|
]
|
|
59
61
|
cli = [
|
|
60
|
-
"click>=8.4",
|
|
62
|
+
"click>=8.4.2",
|
|
61
63
|
"pygments==2.*",
|
|
62
64
|
"rich>=10,<16",
|
|
63
65
|
]
|
httpx2-2.9.0/httpx2/_alias.py
DELETED
|
@@ -1,58 +0,0 @@
|
|
|
1
|
-
from __future__ import annotations
|
|
2
|
-
|
|
3
|
-
import importlib
|
|
4
|
-
import importlib.abc
|
|
5
|
-
import importlib.machinery
|
|
6
|
-
import importlib.util
|
|
7
|
-
import sys
|
|
8
|
-
from collections.abc import Sequence
|
|
9
|
-
from types import ModuleType
|
|
10
|
-
|
|
11
|
-
__all__ = ["alias_httpx"]
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
class _AliasLoader(importlib.abc.Loader):
|
|
15
|
-
_original_spec: importlib.machinery.ModuleSpec | None
|
|
16
|
-
|
|
17
|
-
def create_module(self, spec: importlib.machinery.ModuleSpec) -> ModuleType:
|
|
18
|
-
module = importlib.import_module("httpx2" + spec.name.removeprefix("httpx"))
|
|
19
|
-
self._original_spec = module.__spec__
|
|
20
|
-
return module
|
|
21
|
-
|
|
22
|
-
def exec_module(self, module: ModuleType) -> None:
|
|
23
|
-
module.__spec__ = self._original_spec
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
class _AliasFinder(importlib.abc.MetaPathFinder):
|
|
27
|
-
def find_spec(
|
|
28
|
-
self,
|
|
29
|
-
fullname: str,
|
|
30
|
-
path: Sequence[str] | None = None,
|
|
31
|
-
target: ModuleType | None = None,
|
|
32
|
-
) -> importlib.machinery.ModuleSpec | None:
|
|
33
|
-
if fullname != "httpx" and not fullname.startswith("httpx."):
|
|
34
|
-
return None
|
|
35
|
-
real_name = "httpx2" + fullname.removeprefix("httpx")
|
|
36
|
-
if real_name not in sys.modules and importlib.util.find_spec(real_name) is None:
|
|
37
|
-
return None
|
|
38
|
-
return importlib.machinery.ModuleSpec(fullname, _AliasLoader())
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
def alias_httpx() -> None:
|
|
42
|
-
"""
|
|
43
|
-
Make `import httpx` resolve to `httpx2`, process-wide.
|
|
44
|
-
|
|
45
|
-
Intended for applications migrating from `httpx`, so that dependencies still
|
|
46
|
-
importing `httpx` share the `httpx2` classes. Libraries should never call this.
|
|
47
|
-
|
|
48
|
-
Must be called before anything imports `httpx`. Calling it again is a no-op.
|
|
49
|
-
"""
|
|
50
|
-
import httpx2
|
|
51
|
-
|
|
52
|
-
existing = sys.modules.get("httpx")
|
|
53
|
-
if existing is not None and existing is not httpx2:
|
|
54
|
-
raise RuntimeError("httpx was already imported; call `alias_httpx()` before any `import httpx`.")
|
|
55
|
-
|
|
56
|
-
if not any(isinstance(finder, _AliasFinder) for finder in sys.meta_path):
|
|
57
|
-
sys.meta_path.insert(0, _AliasFinder())
|
|
58
|
-
sys.modules["httpx"] = httpx2
|
httpx2-2.9.0/httpx2/_sse.py
DELETED
|
@@ -1,158 +0,0 @@
|
|
|
1
|
-
"""
|
|
2
|
-
Server-sent events support, derived from httpx-sse (https://github.com/florimondmanca/httpx-sse).
|
|
3
|
-
|
|
4
|
-
Copyright (c) 2022 Florimond Manca, MIT License (https://github.com/florimondmanca/httpx-sse/blob/master/LICENSE).
|
|
5
|
-
"""
|
|
6
|
-
|
|
7
|
-
from __future__ import annotations
|
|
8
|
-
|
|
9
|
-
import json as jsonlib
|
|
10
|
-
from collections.abc import AsyncIterator, Iterator
|
|
11
|
-
from dataclasses import dataclass
|
|
12
|
-
|
|
13
|
-
from ._exceptions import TransportError
|
|
14
|
-
from ._models import Response
|
|
15
|
-
|
|
16
|
-
__all__ = ["EventSource", "SSEError", "ServerSentEvent"]
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
class SSEError(TransportError):
|
|
20
|
-
"""
|
|
21
|
-
An error that occurred while connecting to a server-sent events endpoint.
|
|
22
|
-
"""
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
@dataclass(frozen=True)
|
|
26
|
-
class ServerSentEvent:
|
|
27
|
-
event: str = "message"
|
|
28
|
-
data: str = ""
|
|
29
|
-
id: str = ""
|
|
30
|
-
retry: int | None = None
|
|
31
|
-
|
|
32
|
-
def json(self) -> object:
|
|
33
|
-
return jsonlib.loads(self.data)
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
class _SSEDecoder:
|
|
37
|
-
def __init__(self) -> None:
|
|
38
|
-
self._event = ""
|
|
39
|
-
self._data: list[str] = []
|
|
40
|
-
self._last_event_id = ""
|
|
41
|
-
self._retry: int | None = None
|
|
42
|
-
self._pending = False
|
|
43
|
-
|
|
44
|
-
def decode(self, line: str) -> ServerSentEvent | None:
|
|
45
|
-
if not line:
|
|
46
|
-
if not self._pending:
|
|
47
|
-
return None
|
|
48
|
-
|
|
49
|
-
sse = ServerSentEvent(
|
|
50
|
-
event=self._event or "message",
|
|
51
|
-
data="\n".join(self._data),
|
|
52
|
-
id=self._last_event_id,
|
|
53
|
-
retry=self._retry,
|
|
54
|
-
)
|
|
55
|
-
self._event = ""
|
|
56
|
-
self._data = []
|
|
57
|
-
self._retry = None
|
|
58
|
-
self._pending = False
|
|
59
|
-
return sse
|
|
60
|
-
|
|
61
|
-
if line.startswith(":"):
|
|
62
|
-
return None
|
|
63
|
-
|
|
64
|
-
fieldname, _, value = line.partition(":")
|
|
65
|
-
value = value[1:] if value.startswith(" ") else value
|
|
66
|
-
|
|
67
|
-
if fieldname == "event":
|
|
68
|
-
self._event = value
|
|
69
|
-
self._pending = True
|
|
70
|
-
elif fieldname == "data":
|
|
71
|
-
self._data.append(value)
|
|
72
|
-
self._pending = True
|
|
73
|
-
elif fieldname == "id":
|
|
74
|
-
if "\0" not in value:
|
|
75
|
-
self._last_event_id = value
|
|
76
|
-
self._pending = True
|
|
77
|
-
elif fieldname == "retry":
|
|
78
|
-
try:
|
|
79
|
-
self._retry = int(value)
|
|
80
|
-
self._pending = True
|
|
81
|
-
except ValueError:
|
|
82
|
-
pass
|
|
83
|
-
|
|
84
|
-
return None
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
class _SSELineDecoder:
|
|
88
|
-
def __init__(self) -> None:
|
|
89
|
-
self._buffer = ""
|
|
90
|
-
self._trailing_cr = False
|
|
91
|
-
|
|
92
|
-
def decode(self, text: str) -> list[str]:
|
|
93
|
-
if self._trailing_cr:
|
|
94
|
-
text = "\r" + text
|
|
95
|
-
self._trailing_cr = False
|
|
96
|
-
if text.endswith("\r"):
|
|
97
|
-
self._trailing_cr = True
|
|
98
|
-
text = text[:-1]
|
|
99
|
-
|
|
100
|
-
text = self._buffer + text.replace("\r\n", "\n").replace("\r", "\n")
|
|
101
|
-
lines = text.split("\n")
|
|
102
|
-
self._buffer = lines.pop()
|
|
103
|
-
return lines
|
|
104
|
-
|
|
105
|
-
def flush(self) -> list[str]:
|
|
106
|
-
if self._trailing_cr:
|
|
107
|
-
self._buffer += "\n"
|
|
108
|
-
self._trailing_cr = False
|
|
109
|
-
if not self._buffer:
|
|
110
|
-
return []
|
|
111
|
-
lines = self._buffer.split("\n")
|
|
112
|
-
self._buffer = ""
|
|
113
|
-
return lines
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
class EventSource:
|
|
117
|
-
def __init__(self, response: Response) -> None:
|
|
118
|
-
self._response = response
|
|
119
|
-
|
|
120
|
-
@property
|
|
121
|
-
def response(self) -> Response:
|
|
122
|
-
return self._response
|
|
123
|
-
|
|
124
|
-
def _check_content_type(self) -> None:
|
|
125
|
-
content_type, _, _ = self._response.headers.get("content-type", "").partition(";")
|
|
126
|
-
if content_type.strip().lower() != "text/event-stream":
|
|
127
|
-
raise SSEError(
|
|
128
|
-
f"Expected response with content type 'text/event-stream', got {content_type.strip()!r}.",
|
|
129
|
-
request=self._response.request,
|
|
130
|
-
)
|
|
131
|
-
|
|
132
|
-
def __iter__(self) -> Iterator[ServerSentEvent]:
|
|
133
|
-
self._check_content_type()
|
|
134
|
-
decoder = _SSEDecoder()
|
|
135
|
-
lines = _SSELineDecoder()
|
|
136
|
-
for chunk in self._response.iter_text():
|
|
137
|
-
for line in lines.decode(chunk):
|
|
138
|
-
sse = decoder.decode(line)
|
|
139
|
-
if sse is not None:
|
|
140
|
-
yield sse
|
|
141
|
-
for line in lines.flush():
|
|
142
|
-
sse = decoder.decode(line)
|
|
143
|
-
if sse is not None:
|
|
144
|
-
yield sse
|
|
145
|
-
|
|
146
|
-
async def __aiter__(self) -> AsyncIterator[ServerSentEvent]:
|
|
147
|
-
self._check_content_type()
|
|
148
|
-
decoder = _SSEDecoder()
|
|
149
|
-
lines = _SSELineDecoder()
|
|
150
|
-
async for chunk in self._response.aiter_text():
|
|
151
|
-
for line in lines.decode(chunk):
|
|
152
|
-
sse = decoder.decode(line)
|
|
153
|
-
if sse is not None:
|
|
154
|
-
yield sse
|
|
155
|
-
for line in lines.flush():
|
|
156
|
-
sse = decoder.decode(line)
|
|
157
|
-
if sse is not None:
|
|
158
|
-
yield sse
|
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
from .asgi import ASGITransport
|
|
2
|
-
from .base import AsyncBaseTransport, BaseTransport
|
|
3
|
-
from .default import AsyncHTTPTransport, HTTPTransport
|
|
4
|
-
from .mock import MockTransport
|
|
5
|
-
from .wsgi import WSGITransport
|
|
6
|
-
|
|
7
|
-
__all__ = [
|
|
8
|
-
"ASGITransport",
|
|
9
|
-
"AsyncBaseTransport",
|
|
10
|
-
"BaseTransport",
|
|
11
|
-
"AsyncHTTPTransport",
|
|
12
|
-
"HTTPTransport",
|
|
13
|
-
"MockTransport",
|
|
14
|
-
"WSGITransport",
|
|
15
|
-
]
|
|
@@ -1,35 +0,0 @@
|
|
|
1
|
-
"""
|
|
2
|
-
WebSocket support, derived from httpx-ws (https://github.com/frankie567/httpx-ws).
|
|
3
|
-
|
|
4
|
-
Copyright (c) 2021 François Voron, MIT License (https://github.com/frankie567/httpx-ws/blob/main/LICENSE).
|
|
5
|
-
"""
|
|
6
|
-
|
|
7
|
-
from ._api import (
|
|
8
|
-
AsyncWebSocketClient,
|
|
9
|
-
AsyncWebSocketSession,
|
|
10
|
-
JSONMode,
|
|
11
|
-
WebSocketClient,
|
|
12
|
-
WebSocketSession,
|
|
13
|
-
)
|
|
14
|
-
from ._exceptions import (
|
|
15
|
-
HTTPXWSException,
|
|
16
|
-
WebSocketDisconnect,
|
|
17
|
-
WebSocketInvalidTypeReceived,
|
|
18
|
-
WebSocketNetworkError,
|
|
19
|
-
WebSocketUpgradeError,
|
|
20
|
-
)
|
|
21
|
-
from ._transport import ASGIWebSocketTransport
|
|
22
|
-
|
|
23
|
-
__all__ = [
|
|
24
|
-
"ASGIWebSocketTransport",
|
|
25
|
-
"AsyncWebSocketClient",
|
|
26
|
-
"AsyncWebSocketSession",
|
|
27
|
-
"HTTPXWSException",
|
|
28
|
-
"JSONMode",
|
|
29
|
-
"WebSocketClient",
|
|
30
|
-
"WebSocketDisconnect",
|
|
31
|
-
"WebSocketInvalidTypeReceived",
|
|
32
|
-
"WebSocketNetworkError",
|
|
33
|
-
"WebSocketSession",
|
|
34
|
-
"WebSocketUpgradeError",
|
|
35
|
-
]
|
|
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
|
|
File without changes
|