Spaces:
Sleeping
Sleeping
Upload folder using huggingface_hub (part 9)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +4 -0
- .venv/lib/python3.12/site-packages/httpx2-2.16.0.dist-info/INSTALLER +1 -0
- .venv/lib/python3.12/site-packages/httpx2-2.16.0.dist-info/METADATA +230 -0
- .venv/lib/python3.12/site-packages/httpx2-2.16.0.dist-info/RECORD +40 -0
- .venv/lib/python3.12/site-packages/httpx2-2.16.0.dist-info/REQUESTED +0 -0
- .venv/lib/python3.12/site-packages/httpx2-2.16.0.dist-info/WHEEL +4 -0
- .venv/lib/python3.12/site-packages/httpx2-2.16.0.dist-info/entry_points.txt +2 -0
- .venv/lib/python3.12/site-packages/httpx2-2.16.0.dist-info/licenses/LICENSE.md +13 -0
- .venv/lib/python3.12/site-packages/httpx2/_auth.py +335 -0
- .venv/lib/python3.12/site-packages/httpx2/_client.py +2236 -0
- .venv/lib/python3.12/site-packages/httpx2/_config.py +221 -0
- .venv/lib/python3.12/site-packages/httpx2/_content.py +237 -0
- .venv/lib/python3.12/site-packages/httpx2/_cookies.py +74 -0
- .venv/lib/python3.12/site-packages/httpx2/_decoders.py +458 -0
- .venv/lib/python3.12/site-packages/httpx2/_exceptions.py +380 -0
- .venv/lib/python3.12/site-packages/httpx2/_main.py +483 -0
- .venv/lib/python3.12/site-packages/httpx2/_models.py +1274 -0
- .venv/lib/python3.12/site-packages/httpx2/_multipart.py +284 -0
- .venv/lib/python3.12/site-packages/httpx2/_sse.py +226 -0
- .venv/lib/python3.12/site-packages/httpx2/_status_codes.py +189 -0
- .venv/lib/python3.12/site-packages/httpx2/_transports/__init__.py +27 -0
- .venv/lib/python3.12/site-packages/httpx2/_transports/asgi.py +178 -0
- .venv/lib/python3.12/site-packages/httpx2/_transports/base.py +83 -0
- .venv/lib/python3.12/site-packages/httpx2/_transports/default.py +400 -0
- .venv/lib/python3.12/site-packages/httpx2/_transports/mock.py +40 -0
- .venv/lib/python3.12/site-packages/httpx2/_transports/wsgi.py +145 -0
- .venv/lib/python3.12/site-packages/httpx2/_types.py +86 -0
- .venv/lib/python3.12/site-packages/httpx2/_urlparse.py +502 -0
- .venv/lib/python3.12/site-packages/httpx2/_urls.py +689 -0
- .venv/lib/python3.12/site-packages/httpx2/_utils.py +282 -0
- .venv/lib/python3.12/site-packages/httpx2/py.typed +0 -0
- .venv/lib/python3.12/site-packages/httpx2/websockets/__init__.py +57 -0
- .venv/lib/python3.12/site-packages/httpx2/websockets/_api.py +1676 -0
- .venv/lib/python3.12/site-packages/httpx2/websockets/_exceptions.py +55 -0
- .venv/lib/python3.12/site-packages/httpx2/websockets/_ping.py +43 -0
- .venv/lib/python3.12/site-packages/httpx2/websockets/_transport.py +289 -0
- .venv/lib/python3.12/site-packages/huggingface_hub-2.4.0.dist-info/INSTALLER +1 -0
- .venv/lib/python3.12/site-packages/huggingface_hub-2.4.0.dist-info/METADATA +366 -0
- .venv/lib/python3.12/site-packages/huggingface_hub-2.4.0.dist-info/RECORD +195 -0
- .venv/lib/python3.12/site-packages/huggingface_hub-2.4.0.dist-info/REQUESTED +0 -0
- .venv/lib/python3.12/site-packages/huggingface_hub-2.4.0.dist-info/WHEEL +5 -0
- .venv/lib/python3.12/site-packages/huggingface_hub-2.4.0.dist-info/entry_points.txt +6 -0
- .venv/lib/python3.12/site-packages/huggingface_hub-2.4.0.dist-info/licenses/LICENSE +201 -0
- .venv/lib/python3.12/site-packages/huggingface_hub-2.4.0.dist-info/top_level.txt +1 -0
- .venv/lib/python3.12/site-packages/huggingface_hub/__init__.py +1849 -0
- .venv/lib/python3.12/site-packages/huggingface_hub/_bucket_live_follow.py +459 -0
- .venv/lib/python3.12/site-packages/huggingface_hub/_buckets.py +1256 -0
- .venv/lib/python3.12/site-packages/huggingface_hub/_commit_api.py +1080 -0
- .venv/lib/python3.12/site-packages/huggingface_hub/_commit_scheduler.py +353 -0
- .venv/lib/python3.12/site-packages/huggingface_hub/_dataset_viewer.py +173 -0
.gitattributes
CHANGED
|
@@ -73,3 +73,7 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 73 |
.venv/lib/python3.12/site-packages/gradio/templates/node/build/client/_app/immutable/chunks/DKvqWxTe2.js.br filter=lfs diff=lfs merge=lfs -text
|
| 74 |
.venv/lib/python3.12/site-packages/gradio/templates/node/build/client/_app/immutable/chunks/Dex_GJa32.js.br filter=lfs diff=lfs merge=lfs -text
|
| 75 |
.venv/lib/python3.12/site-packages/hf_xet/hf_xet.abi3.so filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
.venv/lib/python3.12/site-packages/gradio/templates/node/build/client/_app/immutable/chunks/DKvqWxTe2.js.br filter=lfs diff=lfs merge=lfs -text
|
| 74 |
.venv/lib/python3.12/site-packages/gradio/templates/node/build/client/_app/immutable/chunks/Dex_GJa32.js.br filter=lfs diff=lfs merge=lfs -text
|
| 75 |
.venv/lib/python3.12/site-packages/hf_xet/hf_xet.abi3.so filter=lfs diff=lfs merge=lfs -text
|
| 76 |
+
.venv/lib/python3.12/site-packages/jiter/jiter.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
| 77 |
+
.venv/lib/python3.12/site-packages/numpy/_core/_multiarray_tests.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
| 78 |
+
.venv/lib/python3.12/site-packages/numpy/_core/_multiarray_umath.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
| 79 |
+
.venv/lib/python3.12/site-packages/numpy/_core/_simd.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
.venv/lib/python3.12/site-packages/httpx2-2.16.0.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
uv
|
.venv/lib/python3.12/site-packages/httpx2-2.16.0.dist-info/METADATA
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.5
|
| 2 |
+
Name: httpx2
|
| 3 |
+
Version: 2.16.0
|
| 4 |
+
Summary: The next generation HTTP client.
|
| 5 |
+
Project-URL: Changelog, https://github.com/pydantic/httpx2/blob/main/src/httpx2/CHANGELOG.md
|
| 6 |
+
Project-URL: Homepage, https://github.com/pydantic/httpx2
|
| 7 |
+
Project-URL: Source, https://github.com/pydantic/httpx2
|
| 8 |
+
Author-email: Tom Christie <tom@tomchristie.com>
|
| 9 |
+
Maintainer-email: "Pydantic Services Inc." <engineering@pydantic.dev>
|
| 10 |
+
License-Expression: BSD-3-Clause
|
| 11 |
+
License-File: LICENSE.md
|
| 12 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 13 |
+
Classifier: Environment :: Web Environment
|
| 14 |
+
Classifier: Framework :: AnyIO
|
| 15 |
+
Classifier: Framework :: AsyncIO
|
| 16 |
+
Classifier: Framework :: Trio
|
| 17 |
+
Classifier: Intended Audience :: Developers
|
| 18 |
+
Classifier: License :: OSI Approved :: BSD License
|
| 19 |
+
Classifier: Operating System :: OS Independent
|
| 20 |
+
Classifier: Programming Language :: Python :: 3
|
| 21 |
+
Classifier: Programming Language :: Python :: 3 :: Only
|
| 22 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 23 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 24 |
+
Classifier: Programming Language :: Python :: 3.13
|
| 25 |
+
Classifier: Programming Language :: Python :: 3.14
|
| 26 |
+
Classifier: Programming Language :: Python :: 3.15
|
| 27 |
+
Classifier: Topic :: Internet :: WWW/HTTP
|
| 28 |
+
Requires-Python: >=3.11
|
| 29 |
+
Requires-Dist: anyio>=4.10; sys_platform != 'emscripten'
|
| 30 |
+
Requires-Dist: httpcore2==2.16.0; sys_platform != 'emscripten'
|
| 31 |
+
Requires-Dist: httpx2-jsfetch; sys_platform == 'emscripten' and python_version >= '3.12'
|
| 32 |
+
Requires-Dist: idna>=3.18
|
| 33 |
+
Requires-Dist: truststore>=0.10; sys_platform != 'emscripten'
|
| 34 |
+
Requires-Dist: typing-extensions>=4.5.0; python_version < '3.13'
|
| 35 |
+
Provides-Extra: brotli
|
| 36 |
+
Requires-Dist: brotli>=1.2.0; (platform_python_implementation == 'CPython') and extra == 'brotli'
|
| 37 |
+
Requires-Dist: brotlicffi>=1.2.0.2; (platform_python_implementation != 'CPython') and extra == 'brotli'
|
| 38 |
+
Provides-Extra: cli
|
| 39 |
+
Requires-Dist: click>=8.4.2; extra == 'cli'
|
| 40 |
+
Requires-Dist: pygments==2.*; extra == 'cli'
|
| 41 |
+
Requires-Dist: rich<16,>=10; extra == 'cli'
|
| 42 |
+
Provides-Extra: http2
|
| 43 |
+
Requires-Dist: h2<5,>=3; extra == 'http2'
|
| 44 |
+
Provides-Extra: socks
|
| 45 |
+
Requires-Dist: socksio==1.*; extra == 'socks'
|
| 46 |
+
Provides-Extra: ws
|
| 47 |
+
Requires-Dist: wsproto>=1.2; extra == 'ws'
|
| 48 |
+
Provides-Extra: zstd
|
| 49 |
+
Requires-Dist: backports-zstd>=1.0.0; (python_version <= '3.13') and extra == 'zstd'
|
| 50 |
+
Description-Content-Type: text/markdown
|
| 51 |
+
|
| 52 |
+
<h1 align="center">HTTPX2</h1>
|
| 53 |
+
|
| 54 |
+
<p align="center"><em>A next-generation HTTP client for Python.</em></p>
|
| 55 |
+
|
| 56 |
+
<p align="center">
|
| 57 |
+
<a href="https://github.com/pydantic/httpx2/actions"><img src="https://github.com/pydantic/httpx2/workflows/Test%20Suite/badge.svg" alt="Test Suite"></a>
|
| 58 |
+
<a href="https://pypi.org/project/httpx2/"><img src="https://badge.fury.io/py/httpx2.svg" alt="Package version"></a>
|
| 59 |
+
<a href="https://pydantic.dev/docs/logfire/join-slack/"><img src="https://img.shields.io/badge/Slack-Join%20Slack-4A154B?logo=slack" alt="Join Slack"></a>
|
| 60 |
+
</p>
|
| 61 |
+
|
| 62 |
+
HTTPX2 is a fully featured HTTP client library for Python. It includes **an integrated command line client**, has support for both **HTTP/1.1 and HTTP/2**, and provides both **sync and async APIs**.
|
| 63 |
+
|
| 64 |
+
> [!NOTE]
|
| 65 |
+
> 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.
|
| 66 |
+
>
|
| 67 |
+
> With HTTPX itself seeing limited activity recently, Pydantic is picking up stewardship under the HTTPX2 name so that users have a reliably maintained path forward - including timely security updates for a library that sits in the critical path of so many production systems. Our aim is to honour the original project's design, keep it stable for everyone relying on it, and continue evolving it carefully. Thank you to [@lovelydinosaur](https://github.com/lovelydinosaur) and every past contributor for laying such a strong foundation. 💙
|
| 68 |
+
|
| 69 |
+
---
|
| 70 |
+
|
| 71 |
+
Install HTTPX2 using pip:
|
| 72 |
+
|
| 73 |
+
```shell
|
| 74 |
+
pip install httpx2
|
| 75 |
+
```
|
| 76 |
+
|
| 77 |
+
Now, let's get started:
|
| 78 |
+
|
| 79 |
+
```pycon
|
| 80 |
+
>>> import httpx2
|
| 81 |
+
>>> r = httpx2.get('https://www.example.org/')
|
| 82 |
+
>>> r
|
| 83 |
+
<Response [200 OK]>
|
| 84 |
+
>>> r.status_code
|
| 85 |
+
200
|
| 86 |
+
>>> r.headers['content-type']
|
| 87 |
+
'text/html; charset=UTF-8'
|
| 88 |
+
>>> r.text
|
| 89 |
+
'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'
|
| 90 |
+
```
|
| 91 |
+
|
| 92 |
+
Or, using the command-line client.
|
| 93 |
+
|
| 94 |
+
```shell
|
| 95 |
+
pip install 'httpx2[cli]' # The command line client is an optional dependency.
|
| 96 |
+
```
|
| 97 |
+
|
| 98 |
+
Which now allows us to use HTTPX2 directly from the command-line:
|
| 99 |
+
|
| 100 |
+
```shell
|
| 101 |
+
httpx2 --help
|
| 102 |
+
```
|
| 103 |
+
|
| 104 |
+
## Features
|
| 105 |
+
|
| 106 |
+
HTTPX2 builds on the well-established usability of `requests`, and gives you:
|
| 107 |
+
|
| 108 |
+
* A broadly [requests-compatible API](https://pydantic.dev/docs/httpx2/guides/compatibility/).
|
| 109 |
+
* An integrated command-line client.
|
| 110 |
+
* HTTP/1.1 [and HTTP/2 support](https://pydantic.dev/docs/httpx2/guides/http2/).
|
| 111 |
+
* Standard synchronous interface, but with [async support if you need it](https://pydantic.dev/docs/httpx2/guides/async/).
|
| 112 |
+
* Ability to make requests directly to [WSGI applications](https://pydantic.dev/docs/httpx2/advanced/transports/#wsgi-transport) or [ASGI applications](https://pydantic.dev/docs/httpx2/advanced/transports/#asgi-transport).
|
| 113 |
+
* Strict timeouts everywhere.
|
| 114 |
+
* Fully type annotated.
|
| 115 |
+
* 100% test coverage.
|
| 116 |
+
|
| 117 |
+
Plus all the standard features of `requests`...
|
| 118 |
+
|
| 119 |
+
* International Domains and URLs
|
| 120 |
+
* Keep-Alive & Connection Pooling
|
| 121 |
+
* Sessions with Cookie Persistence
|
| 122 |
+
* Browser-style SSL Verification
|
| 123 |
+
* Basic/Digest Authentication
|
| 124 |
+
* Elegant Key/Value Cookies
|
| 125 |
+
* Automatic Decompression
|
| 126 |
+
* Automatic Content Decoding
|
| 127 |
+
* Unicode Response Bodies
|
| 128 |
+
* Multipart File Uploads
|
| 129 |
+
* HTTP(S) Proxy Support
|
| 130 |
+
* Connection Timeouts
|
| 131 |
+
* Streaming Downloads
|
| 132 |
+
* .netrc Support
|
| 133 |
+
* Chunked Requests
|
| 134 |
+
|
| 135 |
+
## Installation
|
| 136 |
+
|
| 137 |
+
Install with pip:
|
| 138 |
+
|
| 139 |
+
```shell
|
| 140 |
+
pip install httpx2
|
| 141 |
+
```
|
| 142 |
+
|
| 143 |
+
Or, to include the optional HTTP/2 support, use:
|
| 144 |
+
|
| 145 |
+
```shell
|
| 146 |
+
pip install httpx2[http2]
|
| 147 |
+
```
|
| 148 |
+
|
| 149 |
+
## Documentation
|
| 150 |
+
|
| 151 |
+
Project documentation is available at [https://pydantic.dev/docs/httpx2/](https://pydantic.dev/docs/httpx2/).
|
| 152 |
+
|
| 153 |
+
For a run-through of all the basics, head over to the [QuickStart](https://pydantic.dev/docs/httpx2/get-started/quickstart/).
|
| 154 |
+
|
| 155 |
+
For more advanced topics, see the [Advanced Usage](https://pydantic.dev/docs/httpx2/advanced/clients/) section, the [async support](https://pydantic.dev/docs/httpx2/guides/async/) section, or the [HTTP/2](https://pydantic.dev/docs/httpx2/guides/http2/) section.
|
| 156 |
+
|
| 157 |
+
The [Developer Interface](https://pydantic.dev/docs/httpx2/api/api/) provides a comprehensive API reference.
|
| 158 |
+
|
| 159 |
+
To find out about tools that integrate with HTTPX, see [Third Party Packages](https://pydantic.dev/docs/httpx2/community/third_party_packages/).
|
| 160 |
+
|
| 161 |
+
## Observability with Pydantic Logfire
|
| 162 |
+
|
| 163 |
+
Install Logfire with HTTPX instrumentation support:
|
| 164 |
+
|
| 165 |
+
```shell
|
| 166 |
+
pip install 'logfire[httpx]'
|
| 167 |
+
```
|
| 168 |
+
|
| 169 |
+
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:
|
| 170 |
+
|
| 171 |
+
```python
|
| 172 |
+
import logfire
|
| 173 |
+
import httpx2
|
| 174 |
+
|
| 175 |
+
logfire.configure()
|
| 176 |
+
logfire.instrument_httpx()
|
| 177 |
+
|
| 178 |
+
httpx2.get("https://pydantic.dev/")
|
| 179 |
+
```
|
| 180 |
+
|
| 181 |
+
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.
|
| 182 |
+
|
| 183 |
+
## Contribute
|
| 184 |
+
|
| 185 |
+
If you want to contribute with HTTPX2 check out the [Contributing Guide](https://pydantic.dev/docs/httpx2/community/contributing/) to learn how to start.
|
| 186 |
+
|
| 187 |
+
## Dependencies
|
| 188 |
+
|
| 189 |
+
The HTTPX2 project relies on these excellent libraries:
|
| 190 |
+
|
| 191 |
+
* `httpcore2` - The underlying transport implementation for `httpx2`.
|
| 192 |
+
* `h11` - HTTP/1.1 support.
|
| 193 |
+
* `anyio` - Structured concurrency primitives, used to support both `asyncio` and `trio`.
|
| 194 |
+
* `truststore` - SSL verification using the operating system's trust store.
|
| 195 |
+
* `idna` - Internationalized domain name support.
|
| 196 |
+
|
| 197 |
+
As well as these optional installs:
|
| 198 |
+
|
| 199 |
+
* `h2` - HTTP/2 support. *(Optional, with `httpx2[http2]`)*
|
| 200 |
+
* `socksio` - SOCKS proxy support. *(Optional, with `httpx2[socks]`)*
|
| 201 |
+
* `rich` - Rich terminal support. *(Optional, with `httpx2[cli]`)*
|
| 202 |
+
* `click` - Command line client support. *(Optional, with `httpx2[cli]`)*
|
| 203 |
+
* `brotli` or `brotlicffi` - Decoding for "brotli" compressed responses. *(Optional, with `httpx2[brotli]`)*
|
| 204 |
+
* `backports.zstd` - Decoding for "zstd" compressed responses on Python 3.13 and below. *(Optional, with `httpx2[zstd]`. On Python 3.14+, `zstd` is supported via the stdlib [`compression.zstd`](https://docs.python.org/3/library/compression.zstd.html) module when it is available, and the `httpx2[zstd]` extra installs nothing.)*
|
| 205 |
+
|
| 206 |
+
A huge amount of credit is due to `requests` for the API layout that
|
| 207 |
+
much of this work follows, as well as to `urllib3` for plenty of design
|
| 208 |
+
inspiration around the lower-level networking details.
|
| 209 |
+
|
| 210 |
+
---
|
| 211 |
+
|
| 212 |
+
<p align="center"><i>HTTPX2 is <a href="https://github.com/pydantic/httpx2/blob/main/LICENSE.md">BSD licensed</a> code.<br/>Designed & crafted with care.</i><br/>— 🦋 —</p>
|
| 213 |
+
|
| 214 |
+
## Release Information
|
| 215 |
+
|
| 216 |
+
## 2.16.0 (October 21st, 2026)
|
| 217 |
+
|
| 218 |
+
### Changed
|
| 219 |
+
|
| 220 |
+
* 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.
|
| 221 |
+
([#1285](https://github.com/pydantic/httpx2/pull/1285))
|
| 222 |
+
|
| 223 |
+
### Fixed
|
| 224 |
+
|
| 225 |
+
* 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.
|
| 226 |
+
([#1284](https://github.com/pydantic/httpx2/pull/1284))
|
| 227 |
+
|
| 228 |
+
---
|
| 229 |
+
|
| 230 |
+
[Full changelog](https://github.com/pydantic/httpx2/blob/main/src/httpx2/CHANGELOG.md)
|
.venv/lib/python3.12/site-packages/httpx2-2.16.0.dist-info/RECORD
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
../../../bin/httpx2,sha256=LeY-EMOSe91Lbs9qC2fXrMweON9Yv95xRm0pE7p47II,362
|
| 2 |
+
httpx2-2.16.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
|
| 3 |
+
httpx2-2.16.0.dist-info/METADATA,sha256=GS8gBGIA_1CRGnJ4wh377h4aTG-nlDInr-kjHSje_D8,10019
|
| 4 |
+
httpx2-2.16.0.dist-info/RECORD,,
|
| 5 |
+
httpx2-2.16.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 6 |
+
httpx2-2.16.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
| 7 |
+
httpx2-2.16.0.dist-info/entry_points.txt,sha256=3uiZorRQlQAFNoHaDxuMsmkdjt3rUTmuBz81tLXFdQY,45
|
| 8 |
+
httpx2-2.16.0.dist-info/licenses/LICENSE.md,sha256=fn1tuvf-Fg05_W6E_QLDPKuWvL6jTTaZjVRbzrShnDA,1589
|
| 9 |
+
httpx2/__init__.py,sha256=BfjyqGaJJhHp5NsWDrQ7GJUjqr1zGXNoqV3vb5eUozo,2661
|
| 10 |
+
httpx2/__version__.py,sha256=XWKDNx4TZNJGkuO6vv16RvfV8lhdgdMIbQ8Bt0cR4UQ,158
|
| 11 |
+
httpx2/_alias.py,sha256=Evn6S3BWugzd5XgDAYOsQf45_tAQpgae4JJ6U6n02Bw,2431
|
| 12 |
+
httpx2/_api.py,sha256=IhvMLaySB7-pEER2l_qCbSDjTmG28hVPXIJJMdiHze0,14794
|
| 13 |
+
httpx2/_auth.py,sha256=VUO3zJfK3GGOp3dnQqYrAu6Lkip-DpK2mutFPmVbjjA,11969
|
| 14 |
+
httpx2/_client.py,sha256=pDgPmEKjiJZDBhhnPM72ZIalzb1mU5h9WBuGnHLfm1M,75349
|
| 15 |
+
httpx2/_config.py,sha256=DAJBDxmJX4GmlCqtNE1L1dgEr5sBmo8tvLcn48R2oTA,7438
|
| 16 |
+
httpx2/_content.py,sha256=sNp9IVai11gXO_4P5Uka8XqrT_A8Ab5xkgRlKD4xeY0,8490
|
| 17 |
+
httpx2/_cookies.py,sha256=lMivxsZyHM5zBJHim6WVPJ5QBKeAW79pHh5jDtTl5_0,2965
|
| 18 |
+
httpx2/_decoders.py,sha256=C479GSHULT-xFz3Rr5TwZ0uUn2ih_afezn7QcgoIfAA,15046
|
| 19 |
+
httpx2/_exceptions.py,sha256=69TPZgHvTkkjV1P0y5DSVOmDkxwCRsKhCfhd_qTTaVc,8857
|
| 20 |
+
httpx2/_main.py,sha256=JT_VdROzHpKs8DNBIvXZXF2jYr6jxo0NVyk1FK6ff5A,15434
|
| 21 |
+
httpx2/_models.py,sha256=INk4VXTudl3jGI34fJJKknUmfF_dwzNuqerCiPo9T6k,45856
|
| 22 |
+
httpx2/_multipart.py,sha256=ksgIJarALvO7EcgDmc40GX6GyVO6XG0faszehXdRaTg,10018
|
| 23 |
+
httpx2/_sse.py,sha256=IZ1Lf6NrgoZa7FP5-n_VhKhk0eEYFkPZtOC8g5JpQCk,7552
|
| 24 |
+
httpx2/_status_codes.py,sha256=0CWpuD1dw8PYrt9f7epZ0bZZQEnmqe-z6FK_IzIeh14,6625
|
| 25 |
+
httpx2/_transports/__init__.py,sha256=e65w9X4RMK9O_0Q6kPqpXr1ijeEf6b9xbl4KfrAYDCI,711
|
| 26 |
+
httpx2/_transports/asgi.py,sha256=PWe4gtw8l2NqK5VusB4uprs6l46fJ4ewLX8FUEOozuk,5429
|
| 27 |
+
httpx2/_transports/base.py,sha256=KY5zBVbdG6ge2sE-j0ZKyJ1C1LWBZVHQnOg0BdQ6idE,2584
|
| 28 |
+
httpx2/_transports/default.py,sha256=j8Q6KILUca_3UTZqfyjpHF4xgxpLKao7tOZpMaIUjpc,13913
|
| 29 |
+
httpx2/_transports/mock.py,sha256=3LZowN_YXbXezA2P4D4g29bCemTiT5Gr8U_vBvxtgxs,1209
|
| 30 |
+
httpx2/_transports/wsgi.py,sha256=R5UApE_xXvl3BwKMgokN5irXiXGRFbOrtTdiKXFEBkI,4904
|
| 31 |
+
httpx2/_types.py,sha256=pVETNjBR2OoWs9-sY7tRTAQM8sZx8-kNwZ4DjZcEYZU,2671
|
| 32 |
+
httpx2/_urlparse.py,sha256=X-_rLDsC9QMIGc1FXr9DVRTYsLLB_SOdaCOtF2-DRIA,18323
|
| 33 |
+
httpx2/_urls.py,sha256=t2wZOCuWtmP8vHnwq2hLhLZ_g2Y36K3SMpU0u_3J8CY,23184
|
| 34 |
+
httpx2/_utils.py,sha256=-2nvGVPvYfJxZXPU-RbQXxGazILdRp5kJUJK98mF5R4,10524
|
| 35 |
+
httpx2/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 36 |
+
httpx2/websockets/__init__.py,sha256=K66d2Zczl0Ewa0ey0Q2ETx5utzVH6n5G6J22mR3GbV0,1826
|
| 37 |
+
httpx2/websockets/_api.py,sha256=pNdsYOmhqeq5k8_DrtXK-w5QDAcKEq1FNwgBWF3j0Gc,63283
|
| 38 |
+
httpx2/websockets/_exceptions.py,sha256=bpnBX9fDdkWh9jKWqqXAcQ_jsIPDRSuzUexxz_RPzqA,1290
|
| 39 |
+
httpx2/websockets/_ping.py,sha256=M6Xmbap01-ldl1ejejmkjJbBgK1ulBj-_oaUoKciqrM,1258
|
| 40 |
+
httpx2/websockets/_transport.py,sha256=pGtJcgy58Vi9246bj56yr-80qqpfUk6FapMFd8zw2Ls,11029
|
.venv/lib/python3.12/site-packages/httpx2-2.16.0.dist-info/REQUESTED
ADDED
|
File without changes
|
.venv/lib/python3.12/site-packages/httpx2-2.16.0.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: hatchling 1.32.4
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
.venv/lib/python3.12/site-packages/httpx2-2.16.0.dist-info/entry_points.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[console_scripts]
|
| 2 |
+
httpx2 = httpx2._main:main
|
.venv/lib/python3.12/site-packages/httpx2-2.16.0.dist-info/licenses/LICENSE.md
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Copyright © 2026 to present Pydantic Services Inc. and individual contributors.
|
| 2 |
+
Copyright © 2019, [Encode OSS Ltd](https://www.encode.io/).
|
| 3 |
+
All rights reserved.
|
| 4 |
+
|
| 5 |
+
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
| 6 |
+
|
| 7 |
+
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
| 8 |
+
|
| 9 |
+
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
| 10 |
+
|
| 11 |
+
* Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
|
| 12 |
+
|
| 13 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
.venv/lib/python3.12/site-packages/httpx2/_auth.py
ADDED
|
@@ -0,0 +1,335 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import hashlib
|
| 4 |
+
import os
|
| 5 |
+
import re
|
| 6 |
+
import time
|
| 7 |
+
import typing
|
| 8 |
+
from base64 import b64encode
|
| 9 |
+
from urllib.request import parse_http_list
|
| 10 |
+
|
| 11 |
+
from ._exceptions import ProtocolError
|
| 12 |
+
from ._models import Cookies, Request, Response
|
| 13 |
+
from ._utils import to_bytes, to_str
|
| 14 |
+
|
| 15 |
+
if typing.TYPE_CHECKING:
|
| 16 |
+
from collections.abc import Callable
|
| 17 |
+
from hashlib import _Hash
|
| 18 |
+
|
| 19 |
+
__all__ = ["Auth", "BasicAuth", "DigestAuth", "FunctionAuth", "NetRCAuth"]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class Auth:
|
| 23 |
+
"""
|
| 24 |
+
Base class for all authentication schemes.
|
| 25 |
+
|
| 26 |
+
To implement a custom authentication scheme, subclass `Auth` and override
|
| 27 |
+
the `.auth_flow()` method.
|
| 28 |
+
|
| 29 |
+
If the authentication scheme does I/O such as disk access or network calls, or uses
|
| 30 |
+
synchronization primitives such as locks, you should override `.sync_auth_flow()`
|
| 31 |
+
and/or `.async_auth_flow()` instead of `.auth_flow()` to provide specialized
|
| 32 |
+
implementations that will be used by `Client` and `AsyncClient` respectively.
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
requires_request_body = False
|
| 36 |
+
requires_response_body = False
|
| 37 |
+
|
| 38 |
+
def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:
|
| 39 |
+
"""
|
| 40 |
+
Execute the authentication flow.
|
| 41 |
+
|
| 42 |
+
To dispatch a request, `yield` it:
|
| 43 |
+
|
| 44 |
+
```
|
| 45 |
+
yield request
|
| 46 |
+
```
|
| 47 |
+
|
| 48 |
+
The client will `.send()` the response back into the flow generator. You can
|
| 49 |
+
access it like so:
|
| 50 |
+
|
| 51 |
+
```
|
| 52 |
+
response = yield request
|
| 53 |
+
```
|
| 54 |
+
|
| 55 |
+
A `return` (or reaching the end of the generator) will result in the
|
| 56 |
+
client returning the last response obtained from the server.
|
| 57 |
+
|
| 58 |
+
You can dispatch as many requests as is necessary.
|
| 59 |
+
"""
|
| 60 |
+
yield request
|
| 61 |
+
|
| 62 |
+
def sync_auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:
|
| 63 |
+
"""
|
| 64 |
+
Execute the authentication flow synchronously.
|
| 65 |
+
|
| 66 |
+
By default, this defers to `.auth_flow()`. You should override this method
|
| 67 |
+
when the authentication scheme does I/O and/or uses concurrency primitives.
|
| 68 |
+
"""
|
| 69 |
+
if self.requires_request_body:
|
| 70 |
+
request.read()
|
| 71 |
+
|
| 72 |
+
flow = self.auth_flow(request)
|
| 73 |
+
request = next(flow)
|
| 74 |
+
|
| 75 |
+
while True:
|
| 76 |
+
response = yield request
|
| 77 |
+
if self.requires_response_body:
|
| 78 |
+
response.read()
|
| 79 |
+
|
| 80 |
+
try:
|
| 81 |
+
request = flow.send(response)
|
| 82 |
+
except StopIteration:
|
| 83 |
+
break
|
| 84 |
+
|
| 85 |
+
async def async_auth_flow(self, request: Request) -> typing.AsyncGenerator[Request, Response]:
|
| 86 |
+
"""
|
| 87 |
+
Execute the authentication flow asynchronously.
|
| 88 |
+
|
| 89 |
+
By default, this defers to `.auth_flow()`. You should override this method
|
| 90 |
+
when the authentication scheme does I/O and/or uses concurrency primitives.
|
| 91 |
+
"""
|
| 92 |
+
if self.requires_request_body:
|
| 93 |
+
await request.aread()
|
| 94 |
+
|
| 95 |
+
flow = self.auth_flow(request)
|
| 96 |
+
request = next(flow)
|
| 97 |
+
|
| 98 |
+
while True:
|
| 99 |
+
response = yield request
|
| 100 |
+
if self.requires_response_body:
|
| 101 |
+
await response.aread()
|
| 102 |
+
|
| 103 |
+
try:
|
| 104 |
+
request = flow.send(response)
|
| 105 |
+
except StopIteration:
|
| 106 |
+
break
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class FunctionAuth(Auth):
|
| 110 |
+
"""
|
| 111 |
+
Allows the 'auth' argument to be passed as a simple callable function,
|
| 112 |
+
that takes the request, and returns a new, modified request.
|
| 113 |
+
"""
|
| 114 |
+
|
| 115 |
+
def __init__(self, func: typing.Callable[[Request], Request]) -> None:
|
| 116 |
+
self._func = func
|
| 117 |
+
|
| 118 |
+
def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:
|
| 119 |
+
yield self._func(request)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
class BasicAuth(Auth):
|
| 123 |
+
"""
|
| 124 |
+
Allows the 'auth' argument to be passed as a (username, password) pair,
|
| 125 |
+
and uses HTTP Basic authentication.
|
| 126 |
+
"""
|
| 127 |
+
|
| 128 |
+
def __init__(self, username: str | bytes, password: str | bytes) -> None:
|
| 129 |
+
self._auth_header = self._build_auth_header(username, password)
|
| 130 |
+
|
| 131 |
+
def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:
|
| 132 |
+
request.headers["Authorization"] = self._auth_header
|
| 133 |
+
yield request
|
| 134 |
+
|
| 135 |
+
def _build_auth_header(self, username: str | bytes, password: str | bytes) -> str:
|
| 136 |
+
userpass = b":".join((to_bytes(username), to_bytes(password)))
|
| 137 |
+
token = b64encode(userpass).decode()
|
| 138 |
+
return f"Basic {token}"
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
class NetRCAuth(Auth):
|
| 142 |
+
"""
|
| 143 |
+
Use a 'netrc' file to lookup basic auth credentials based on the url host.
|
| 144 |
+
"""
|
| 145 |
+
|
| 146 |
+
def __init__(self, file: str | None = None) -> None:
|
| 147 |
+
# Lazily import 'netrc'.
|
| 148 |
+
# There's no need for us to load this module unless 'NetRCAuth' is being used.
|
| 149 |
+
import netrc
|
| 150 |
+
|
| 151 |
+
self._netrc_info = netrc.netrc(file)
|
| 152 |
+
|
| 153 |
+
def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:
|
| 154 |
+
auth_info = self._netrc_info.authenticators(request.url.host)
|
| 155 |
+
if auth_info is None or not auth_info[2]:
|
| 156 |
+
# The netrc file did not have authentication credentials for this host.
|
| 157 |
+
yield request
|
| 158 |
+
else:
|
| 159 |
+
# Build a basic auth header with credentials from the netrc file.
|
| 160 |
+
request.headers["Authorization"] = self._build_auth_header(username=auth_info[0], password=auth_info[2])
|
| 161 |
+
yield request
|
| 162 |
+
|
| 163 |
+
def _build_auth_header(self, username: str | bytes, password: str | bytes) -> str:
|
| 164 |
+
userpass = b":".join((to_bytes(username), to_bytes(password)))
|
| 165 |
+
token = b64encode(userpass).decode()
|
| 166 |
+
return f"Basic {token}"
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
class DigestAuth(Auth):
|
| 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",
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
def __init__(self, username: str | bytes, password: str | bytes) -> None:
|
| 183 |
+
self._username = to_bytes(username)
|
| 184 |
+
self._password = to_bytes(password)
|
| 185 |
+
self._last_challenge: _DigestAuthChallenge | None = None
|
| 186 |
+
self._nonce_count = 1
|
| 187 |
+
|
| 188 |
+
def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:
|
| 189 |
+
if self._last_challenge:
|
| 190 |
+
request.headers["Authorization"] = self._build_auth_header(request, self._last_challenge)
|
| 191 |
+
|
| 192 |
+
response = yield request
|
| 193 |
+
|
| 194 |
+
if response.status_code != 401 or "www-authenticate" not in response.headers:
|
| 195 |
+
# If the response is not a 401 then we don't
|
| 196 |
+
# need to build an authenticated request.
|
| 197 |
+
return
|
| 198 |
+
|
| 199 |
+
for auth_header in response.headers.get_list("www-authenticate"):
|
| 200 |
+
if auth_header.lower().startswith("digest "):
|
| 201 |
+
break
|
| 202 |
+
else:
|
| 203 |
+
# If the response does not include a 'WWW-Authenticate: Digest ...'
|
| 204 |
+
# header, then we don't need to build an authenticated request.
|
| 205 |
+
return
|
| 206 |
+
|
| 207 |
+
self._last_challenge = self._parse_challenge(request, response, auth_header)
|
| 208 |
+
self._nonce_count = 1
|
| 209 |
+
|
| 210 |
+
request.headers["Authorization"] = self._build_auth_header(request, self._last_challenge)
|
| 211 |
+
if response.cookies:
|
| 212 |
+
Cookies(response.cookies).set_cookie_header(request=request)
|
| 213 |
+
yield request
|
| 214 |
+
|
| 215 |
+
def _parse_challenge(self, request: Request, response: Response, auth_header: str) -> _DigestAuthChallenge:
|
| 216 |
+
"""
|
| 217 |
+
Returns a challenge from a Digest WWW-Authenticate header.
|
| 218 |
+
These take the form of:
|
| 219 |
+
`Digest realm="realm@host.com",qop="auth,auth-int",nonce="abc",opaque="xyz"`
|
| 220 |
+
"""
|
| 221 |
+
scheme, _, fields = auth_header.partition(" ")
|
| 222 |
+
|
| 223 |
+
# This method should only ever have been called with a Digest auth header.
|
| 224 |
+
assert scheme.lower() == "digest"
|
| 225 |
+
|
| 226 |
+
header_dict: dict[str, str] = {}
|
| 227 |
+
for field in parse_http_list(fields):
|
| 228 |
+
key, value = field.strip().split("=", 1)
|
| 229 |
+
header_dict[key] = value.strip('"')
|
| 230 |
+
|
| 231 |
+
try:
|
| 232 |
+
realm = header_dict["realm"].encode()
|
| 233 |
+
nonce = header_dict["nonce"].encode()
|
| 234 |
+
algorithm = header_dict.get("algorithm", "MD5")
|
| 235 |
+
opaque = header_dict["opaque"].encode() if "opaque" in header_dict else None
|
| 236 |
+
qop = header_dict["qop"].encode() if "qop" in header_dict else None
|
| 237 |
+
return _DigestAuthChallenge(realm=realm, nonce=nonce, algorithm=algorithm, opaque=opaque, qop=qop)
|
| 238 |
+
except KeyError as exc:
|
| 239 |
+
message = "Malformed Digest WWW-Authenticate header"
|
| 240 |
+
raise ProtocolError(message, request=request) from exc
|
| 241 |
+
|
| 242 |
+
def _build_auth_header(self, request: Request, challenge: _DigestAuthChallenge) -> str:
|
| 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
|
| 250 |
+
|
| 251 |
+
def digest(data: bytes) -> bytes:
|
| 252 |
+
return hash_func(data).hexdigest().encode()
|
| 253 |
+
|
| 254 |
+
A1 = b":".join((self._username, challenge.realm, self._password))
|
| 255 |
+
|
| 256 |
+
path = request.url.raw_path
|
| 257 |
+
A2 = b":".join((request.method.encode(), path))
|
| 258 |
+
# TODO: implement auth-int
|
| 259 |
+
HA2 = digest(A2)
|
| 260 |
+
|
| 261 |
+
nc_value = b"%08x" % self._nonce_count
|
| 262 |
+
cnonce = self._get_client_nonce(self._nonce_count, challenge.nonce)
|
| 263 |
+
self._nonce_count += 1
|
| 264 |
+
|
| 265 |
+
HA1 = digest(A1)
|
| 266 |
+
if challenge.algorithm.lower().endswith("-sess"):
|
| 267 |
+
HA1 = digest(b":".join((HA1, challenge.nonce, cnonce)))
|
| 268 |
+
|
| 269 |
+
qop = self._resolve_qop(challenge.qop, request=request)
|
| 270 |
+
if qop is None:
|
| 271 |
+
# Following RFC 2069
|
| 272 |
+
digest_data = [HA1, challenge.nonce, HA2]
|
| 273 |
+
else:
|
| 274 |
+
# Following RFC 2617/7616
|
| 275 |
+
digest_data = [HA1, challenge.nonce, nc_value, cnonce, qop, HA2]
|
| 276 |
+
|
| 277 |
+
format_args = {
|
| 278 |
+
"username": self._username,
|
| 279 |
+
"realm": challenge.realm,
|
| 280 |
+
"nonce": challenge.nonce,
|
| 281 |
+
"uri": path,
|
| 282 |
+
"response": digest(b":".join(digest_data)),
|
| 283 |
+
"algorithm": challenge.algorithm.encode(),
|
| 284 |
+
}
|
| 285 |
+
if challenge.opaque:
|
| 286 |
+
format_args["opaque"] = challenge.opaque
|
| 287 |
+
if qop:
|
| 288 |
+
format_args["qop"] = b"auth"
|
| 289 |
+
format_args["nc"] = nc_value
|
| 290 |
+
format_args["cnonce"] = cnonce
|
| 291 |
+
|
| 292 |
+
return "Digest " + self._get_header_value(format_args)
|
| 293 |
+
|
| 294 |
+
def _get_client_nonce(self, nonce_count: int, nonce: bytes) -> bytes:
|
| 295 |
+
s = str(nonce_count).encode()
|
| 296 |
+
s += nonce
|
| 297 |
+
s += time.ctime().encode()
|
| 298 |
+
s += os.urandom(8)
|
| 299 |
+
|
| 300 |
+
return hashlib.sha1(s).hexdigest()[:16].encode()
|
| 301 |
+
|
| 302 |
+
def _get_header_value(self, header_fields: dict[str, bytes]) -> str:
|
| 303 |
+
NON_QUOTED_FIELDS = ("algorithm", "qop", "nc")
|
| 304 |
+
QUOTED_TEMPLATE = '{}="{}"'
|
| 305 |
+
NON_QUOTED_TEMPLATE = "{}={}"
|
| 306 |
+
|
| 307 |
+
header_value = ""
|
| 308 |
+
for i, (field, value) in enumerate(header_fields.items()):
|
| 309 |
+
if i > 0:
|
| 310 |
+
header_value += ", "
|
| 311 |
+
template = QUOTED_TEMPLATE if field not in NON_QUOTED_FIELDS else NON_QUOTED_TEMPLATE
|
| 312 |
+
header_value += template.format(field, to_str(value))
|
| 313 |
+
|
| 314 |
+
return header_value
|
| 315 |
+
|
| 316 |
+
def _resolve_qop(self, qop: bytes | None, request: Request) -> bytes | None:
|
| 317 |
+
if qop is None:
|
| 318 |
+
return None
|
| 319 |
+
qops = re.split(b", ?", qop)
|
| 320 |
+
if b"auth" in qops:
|
| 321 |
+
return b"auth"
|
| 322 |
+
|
| 323 |
+
if qops == [b"auth-int"]:
|
| 324 |
+
raise NotImplementedError("Digest auth-int support is not yet implemented")
|
| 325 |
+
|
| 326 |
+
message = f'Unexpected qop value "{qop!r}" in digest auth'
|
| 327 |
+
raise ProtocolError(message, request=request)
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
class _DigestAuthChallenge(typing.NamedTuple):
|
| 331 |
+
realm: bytes
|
| 332 |
+
nonce: bytes
|
| 333 |
+
algorithm: str
|
| 334 |
+
opaque: bytes | None
|
| 335 |
+
qop: bytes | None
|
.venv/lib/python3.12/site-packages/httpx2/_client.py
ADDED
|
@@ -0,0 +1,2236 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import datetime
|
| 4 |
+
import enum
|
| 5 |
+
import logging
|
| 6 |
+
import time
|
| 7 |
+
import typing
|
| 8 |
+
import warnings
|
| 9 |
+
from collections.abc import AsyncGenerator, Generator
|
| 10 |
+
from contextlib import asynccontextmanager, contextmanager
|
| 11 |
+
from types import TracebackType
|
| 12 |
+
|
| 13 |
+
from .__version__ import __version__
|
| 14 |
+
from ._auth import Auth, BasicAuth, FunctionAuth
|
| 15 |
+
from ._config import (
|
| 16 |
+
DEFAULT_KEEPALIVE_PING_INTERVAL_SECONDS,
|
| 17 |
+
DEFAULT_KEEPALIVE_PING_TIMEOUT_SECONDS,
|
| 18 |
+
DEFAULT_LIMITS,
|
| 19 |
+
DEFAULT_MAX_EVENT_SIZE_BYTES,
|
| 20 |
+
DEFAULT_MAX_MESSAGE_SIZE_BYTES,
|
| 21 |
+
DEFAULT_MAX_REDIRECTS,
|
| 22 |
+
DEFAULT_QUEUE_SIZE,
|
| 23 |
+
DEFAULT_TIMEOUT_CONFIG,
|
| 24 |
+
Limits,
|
| 25 |
+
Proxy,
|
| 26 |
+
Timeout,
|
| 27 |
+
)
|
| 28 |
+
from ._decoders import SUPPORTED_DECODERS
|
| 29 |
+
from ._exceptions import (
|
| 30 |
+
InvalidURL,
|
| 31 |
+
RemoteProtocolError,
|
| 32 |
+
TooManyRedirects,
|
| 33 |
+
request_context,
|
| 34 |
+
)
|
| 35 |
+
from ._models import Cookies, Headers, Request, Response
|
| 36 |
+
from ._sse import EventSource
|
| 37 |
+
from ._status_codes import codes
|
| 38 |
+
from ._transports import AsyncHTTPTransport, HTTPTransport
|
| 39 |
+
from ._transports.base import AsyncBaseTransport, BaseTransport
|
| 40 |
+
from ._types import (
|
| 41 |
+
AsyncByteStream,
|
| 42 |
+
AuthTypes,
|
| 43 |
+
CertTypes,
|
| 44 |
+
CookieTypes,
|
| 45 |
+
HeaderTypes,
|
| 46 |
+
ProxyTypes,
|
| 47 |
+
QueryParamTypes,
|
| 48 |
+
RequestContent,
|
| 49 |
+
RequestData,
|
| 50 |
+
RequestExtensions,
|
| 51 |
+
RequestFiles,
|
| 52 |
+
SyncByteStream,
|
| 53 |
+
TimeoutTypes,
|
| 54 |
+
)
|
| 55 |
+
from ._urls import URL, QueryParams
|
| 56 |
+
from ._utils import URLPattern, get_environment_proxies
|
| 57 |
+
|
| 58 |
+
if typing.TYPE_CHECKING:
|
| 59 |
+
import ssl # pragma: no cover
|
| 60 |
+
|
| 61 |
+
from .websockets._api import AsyncWebSocketSession, WebSocketSession
|
| 62 |
+
|
| 63 |
+
__all__ = ["USE_CLIENT_DEFAULT", "AsyncClient", "Client"]
|
| 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 |
+
|
| 71 |
+
def _is_https_redirect(url: URL, location: URL) -> bool:
|
| 72 |
+
"""
|
| 73 |
+
Return 'True' if 'location' is a HTTPS upgrade of 'url'
|
| 74 |
+
"""
|
| 75 |
+
origin = url.origin
|
| 76 |
+
location_origin = location.origin
|
| 77 |
+
|
| 78 |
+
return (
|
| 79 |
+
origin.host == location_origin.host
|
| 80 |
+
and origin.scheme == "http"
|
| 81 |
+
and origin.port == 80
|
| 82 |
+
and location_origin.scheme == "https"
|
| 83 |
+
and location_origin.port == 443
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class UseClientDefault:
|
| 88 |
+
"""
|
| 89 |
+
For some parameters such as `auth=...` and `timeout=...` we need to be able
|
| 90 |
+
to indicate the default "unset" state, in a way that is distinctly different
|
| 91 |
+
to using `None`.
|
| 92 |
+
|
| 93 |
+
The default "unset" state indicates that whatever default is set on the
|
| 94 |
+
client should be used. This is different to setting `None`, which
|
| 95 |
+
explicitly disables the parameter, possibly overriding a client default.
|
| 96 |
+
|
| 97 |
+
For example we use `timeout=USE_CLIENT_DEFAULT` in the `request()` signature.
|
| 98 |
+
Omitting the `timeout` parameter will send a request using whatever default
|
| 99 |
+
timeout has been configured on the client. Including `timeout=None` will
|
| 100 |
+
ensure no timeout is used.
|
| 101 |
+
|
| 102 |
+
Note that user code shouldn't need to use the `USE_CLIENT_DEFAULT` constant,
|
| 103 |
+
but it is used internally when a parameter is not included.
|
| 104 |
+
"""
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
USE_CLIENT_DEFAULT = UseClientDefault()
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
logger = logging.getLogger("httpx2")
|
| 111 |
+
|
| 112 |
+
USER_AGENT = f"python-httpx2/{__version__}"
|
| 113 |
+
ACCEPT_ENCODING = ", ".join([key for key in SUPPORTED_DECODERS.keys() if key != "identity"])
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class ClientState(enum.Enum):
|
| 117 |
+
# UNOPENED:
|
| 118 |
+
# The client has been instantiated, but has not been used to send a request,
|
| 119 |
+
# or been opened by entering the context of a `with` block.
|
| 120 |
+
UNOPENED = 1
|
| 121 |
+
# OPENED:
|
| 122 |
+
# The client has either sent a request, or is within a `with` block.
|
| 123 |
+
OPENED = 2
|
| 124 |
+
# CLOSED:
|
| 125 |
+
# The client has either exited the `with` block, or `close()` has
|
| 126 |
+
# been called explicitly.
|
| 127 |
+
CLOSED = 3
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
class BoundSyncStream(SyncByteStream):
|
| 131 |
+
"""
|
| 132 |
+
A byte stream that tracks elapsed time for a response. Once closed, the
|
| 133 |
+
elapsed time is available via the `elapsed` attribute, and the response
|
| 134 |
+
can read it back from `response.stream.elapsed`.
|
| 135 |
+
"""
|
| 136 |
+
|
| 137 |
+
def __init__(self, stream: SyncByteStream, start: float) -> None:
|
| 138 |
+
self._stream = stream
|
| 139 |
+
self._start = start
|
| 140 |
+
self.elapsed: datetime.timedelta | None = None
|
| 141 |
+
|
| 142 |
+
def __iter__(self) -> typing.Iterator[bytes]:
|
| 143 |
+
yield from self._stream
|
| 144 |
+
|
| 145 |
+
def close(self) -> None:
|
| 146 |
+
self.elapsed = datetime.timedelta(seconds=time.perf_counter() - self._start)
|
| 147 |
+
self._stream.close()
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class BoundAsyncStream(AsyncByteStream):
|
| 151 |
+
"""
|
| 152 |
+
An async byte stream that tracks elapsed time for a response. Once closed,
|
| 153 |
+
the elapsed time is available via the `elapsed` attribute, and the response
|
| 154 |
+
can read it back from `response.stream.elapsed`.
|
| 155 |
+
"""
|
| 156 |
+
|
| 157 |
+
def __init__(self, stream: AsyncByteStream, start: float) -> None:
|
| 158 |
+
self._stream = stream
|
| 159 |
+
self._start = start
|
| 160 |
+
self.elapsed: datetime.timedelta | None = None
|
| 161 |
+
|
| 162 |
+
async def __aiter__(self) -> typing.AsyncIterator[bytes]:
|
| 163 |
+
stream = self._stream.__aiter__()
|
| 164 |
+
try:
|
| 165 |
+
async for chunk in stream:
|
| 166 |
+
yield chunk
|
| 167 |
+
finally:
|
| 168 |
+
if isinstance(stream, AsyncGenerator):
|
| 169 |
+
await stream.aclose()
|
| 170 |
+
|
| 171 |
+
async def aclose(self) -> None:
|
| 172 |
+
self.elapsed = datetime.timedelta(seconds=time.perf_counter() - self._start)
|
| 173 |
+
await self._stream.aclose()
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
EventHook = typing.Callable[..., typing.Any]
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
class BaseClient:
|
| 180 |
+
def __init__(
|
| 181 |
+
self,
|
| 182 |
+
*,
|
| 183 |
+
auth: AuthTypes | None = None,
|
| 184 |
+
params: QueryParamTypes | None = None,
|
| 185 |
+
headers: HeaderTypes | None = None,
|
| 186 |
+
cookies: CookieTypes | None = None,
|
| 187 |
+
timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
|
| 188 |
+
follow_redirects: bool = False,
|
| 189 |
+
max_redirects: int = DEFAULT_MAX_REDIRECTS,
|
| 190 |
+
event_hooks: None | (typing.Mapping[str, list[EventHook]]) = None,
|
| 191 |
+
base_url: URL | str = "",
|
| 192 |
+
trust_env: bool = True,
|
| 193 |
+
default_encoding: str | typing.Callable[[bytes], str | None] = "utf-8",
|
| 194 |
+
) -> None:
|
| 195 |
+
event_hooks = {} if event_hooks is None else event_hooks
|
| 196 |
+
|
| 197 |
+
self._base_url = self._enforce_trailing_slash(URL(base_url))
|
| 198 |
+
|
| 199 |
+
self._auth = self._build_auth(auth)
|
| 200 |
+
self._params = QueryParams(params)
|
| 201 |
+
self.headers = Headers(headers)
|
| 202 |
+
self._cookies = Cookies(cookies)
|
| 203 |
+
self._timeout = Timeout(timeout)
|
| 204 |
+
self.follow_redirects = follow_redirects
|
| 205 |
+
self.max_redirects = max_redirects
|
| 206 |
+
self._event_hooks = {
|
| 207 |
+
"request": list(event_hooks.get("request", [])),
|
| 208 |
+
"response": list(event_hooks.get("response", [])),
|
| 209 |
+
}
|
| 210 |
+
self._trust_env = trust_env
|
| 211 |
+
self._default_encoding = default_encoding
|
| 212 |
+
self._state = ClientState.UNOPENED
|
| 213 |
+
|
| 214 |
+
@property
|
| 215 |
+
def is_closed(self) -> bool:
|
| 216 |
+
"""
|
| 217 |
+
Check if the client being closed
|
| 218 |
+
"""
|
| 219 |
+
return self._state == ClientState.CLOSED
|
| 220 |
+
|
| 221 |
+
@property
|
| 222 |
+
def trust_env(self) -> bool:
|
| 223 |
+
return self._trust_env
|
| 224 |
+
|
| 225 |
+
def _enforce_trailing_slash(self, url: URL) -> URL:
|
| 226 |
+
if url.raw_path.endswith(b"/"):
|
| 227 |
+
return url
|
| 228 |
+
return url.copy_with(raw_path=url.raw_path + b"/")
|
| 229 |
+
|
| 230 |
+
def _get_proxy_map(self, proxy: ProxyTypes | None, allow_env_proxies: bool) -> dict[str, Proxy | None]:
|
| 231 |
+
if proxy is None:
|
| 232 |
+
if allow_env_proxies:
|
| 233 |
+
return {key: None if url is None else Proxy(url=url) for key, url in get_environment_proxies().items()}
|
| 234 |
+
return {}
|
| 235 |
+
else:
|
| 236 |
+
proxy = Proxy(url=proxy) if isinstance(proxy, (str, URL)) else proxy
|
| 237 |
+
return {"all://": proxy}
|
| 238 |
+
|
| 239 |
+
@property
|
| 240 |
+
def timeout(self) -> Timeout:
|
| 241 |
+
return self._timeout
|
| 242 |
+
|
| 243 |
+
@timeout.setter
|
| 244 |
+
def timeout(self, timeout: TimeoutTypes) -> None:
|
| 245 |
+
self._timeout = Timeout(timeout)
|
| 246 |
+
|
| 247 |
+
@property
|
| 248 |
+
def event_hooks(self) -> dict[str, list[EventHook]]:
|
| 249 |
+
return self._event_hooks
|
| 250 |
+
|
| 251 |
+
@event_hooks.setter
|
| 252 |
+
def event_hooks(self, event_hooks: dict[str, list[EventHook]]) -> None:
|
| 253 |
+
self._event_hooks = {
|
| 254 |
+
"request": list(event_hooks.get("request", [])),
|
| 255 |
+
"response": list(event_hooks.get("response", [])),
|
| 256 |
+
}
|
| 257 |
+
|
| 258 |
+
@property
|
| 259 |
+
def auth(self) -> Auth | None:
|
| 260 |
+
"""
|
| 261 |
+
Authentication class used when none is passed at the request-level.
|
| 262 |
+
|
| 263 |
+
See also [Authentication][0].
|
| 264 |
+
|
| 265 |
+
[0]: quickstart.md#authentication
|
| 266 |
+
"""
|
| 267 |
+
return self._auth
|
| 268 |
+
|
| 269 |
+
@auth.setter
|
| 270 |
+
def auth(self, auth: AuthTypes) -> None:
|
| 271 |
+
self._auth = self._build_auth(auth)
|
| 272 |
+
|
| 273 |
+
@property
|
| 274 |
+
def base_url(self) -> URL:
|
| 275 |
+
"""
|
| 276 |
+
Base URL to use when sending requests with relative URLs.
|
| 277 |
+
"""
|
| 278 |
+
return self._base_url
|
| 279 |
+
|
| 280 |
+
@base_url.setter
|
| 281 |
+
def base_url(self, url: URL | str) -> None:
|
| 282 |
+
self._base_url = self._enforce_trailing_slash(URL(url))
|
| 283 |
+
|
| 284 |
+
@property
|
| 285 |
+
def headers(self) -> Headers:
|
| 286 |
+
"""
|
| 287 |
+
HTTP headers to include when sending requests.
|
| 288 |
+
"""
|
| 289 |
+
return self._headers
|
| 290 |
+
|
| 291 |
+
@headers.setter
|
| 292 |
+
def headers(self, headers: HeaderTypes) -> None:
|
| 293 |
+
client_headers = Headers(
|
| 294 |
+
{
|
| 295 |
+
b"Accept": b"*/*",
|
| 296 |
+
b"Accept-Encoding": ACCEPT_ENCODING.encode("ascii"),
|
| 297 |
+
b"Connection": b"keep-alive",
|
| 298 |
+
b"User-Agent": USER_AGENT.encode("ascii"),
|
| 299 |
+
}
|
| 300 |
+
)
|
| 301 |
+
client_headers.update(headers)
|
| 302 |
+
self._headers = client_headers
|
| 303 |
+
|
| 304 |
+
@property
|
| 305 |
+
def cookies(self) -> Cookies:
|
| 306 |
+
"""
|
| 307 |
+
Cookie values to include when sending requests.
|
| 308 |
+
"""
|
| 309 |
+
return self._cookies
|
| 310 |
+
|
| 311 |
+
@cookies.setter
|
| 312 |
+
def cookies(self, cookies: CookieTypes) -> None:
|
| 313 |
+
self._cookies = Cookies(cookies)
|
| 314 |
+
|
| 315 |
+
@property
|
| 316 |
+
def params(self) -> QueryParams:
|
| 317 |
+
"""
|
| 318 |
+
Query parameters to include in the URL when sending requests.
|
| 319 |
+
"""
|
| 320 |
+
return self._params
|
| 321 |
+
|
| 322 |
+
@params.setter
|
| 323 |
+
def params(self, params: QueryParamTypes) -> None:
|
| 324 |
+
self._params = QueryParams(params)
|
| 325 |
+
|
| 326 |
+
def build_request(
|
| 327 |
+
self,
|
| 328 |
+
method: str,
|
| 329 |
+
url: URL | str,
|
| 330 |
+
*,
|
| 331 |
+
content: RequestContent | None = None,
|
| 332 |
+
data: RequestData | None = None,
|
| 333 |
+
files: RequestFiles | None = None,
|
| 334 |
+
json: typing.Any | None = None,
|
| 335 |
+
params: QueryParamTypes | None = None,
|
| 336 |
+
headers: HeaderTypes | None = None,
|
| 337 |
+
cookies: CookieTypes | None = None,
|
| 338 |
+
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 339 |
+
extensions: RequestExtensions | None = None,
|
| 340 |
+
) -> Request:
|
| 341 |
+
"""
|
| 342 |
+
Build and return a request instance.
|
| 343 |
+
|
| 344 |
+
* The `params`, `headers` and `cookies` arguments
|
| 345 |
+
are merged with any values set on the client.
|
| 346 |
+
* The `url` argument is merged with any `base_url` set on the client.
|
| 347 |
+
|
| 348 |
+
See also: [Request instances][0]
|
| 349 |
+
|
| 350 |
+
[0]: advanced/clients.md#request-instances
|
| 351 |
+
"""
|
| 352 |
+
url = self._merge_url(url)
|
| 353 |
+
headers = self._merge_headers(headers)
|
| 354 |
+
cookies = self._merge_cookies(cookies)
|
| 355 |
+
params = self._merge_queryparams(params)
|
| 356 |
+
extensions = {} if extensions is None else extensions
|
| 357 |
+
if "timeout" not in extensions:
|
| 358 |
+
timeout = self.timeout if isinstance(timeout, UseClientDefault) else Timeout(timeout)
|
| 359 |
+
extensions = dict(**extensions, timeout=timeout.as_dict())
|
| 360 |
+
return Request(
|
| 361 |
+
method,
|
| 362 |
+
url,
|
| 363 |
+
content=content,
|
| 364 |
+
data=data,
|
| 365 |
+
files=files,
|
| 366 |
+
json=json,
|
| 367 |
+
params=params,
|
| 368 |
+
headers=headers,
|
| 369 |
+
cookies=cookies,
|
| 370 |
+
extensions=extensions,
|
| 371 |
+
)
|
| 372 |
+
|
| 373 |
+
def _merge_url(self, url: URL | str) -> URL:
|
| 374 |
+
"""
|
| 375 |
+
Merge a URL argument together with any 'base_url' on the client,
|
| 376 |
+
to create the URL used for the outgoing request.
|
| 377 |
+
"""
|
| 378 |
+
merge_url = URL(url)
|
| 379 |
+
if merge_url.is_relative_url:
|
| 380 |
+
# To merge URLs we always append to the base URL. To get this
|
| 381 |
+
# behaviour correct we always ensure the base URL ends in a '/'
|
| 382 |
+
# separator, and strip any leading '/' from the merge URL.
|
| 383 |
+
#
|
| 384 |
+
# So, eg...
|
| 385 |
+
#
|
| 386 |
+
# >>> client = Client(base_url="https://www.example.com/subpath")
|
| 387 |
+
# >>> client.base_url
|
| 388 |
+
# URL('https://www.example.com/subpath/')
|
| 389 |
+
# >>> client.build_request("GET", "/path").url
|
| 390 |
+
# URL('https://www.example.com/subpath/path')
|
| 391 |
+
merge_raw_path = self.base_url.raw_path + merge_url.raw_path.lstrip(b"/")
|
| 392 |
+
return self.base_url.copy_with(raw_path=merge_raw_path)
|
| 393 |
+
return merge_url
|
| 394 |
+
|
| 395 |
+
def _merge_cookies(self, cookies: CookieTypes | None = None) -> Cookies:
|
| 396 |
+
"""
|
| 397 |
+
Merge a cookies argument together with any cookies on the client,
|
| 398 |
+
to create the cookies used for the outgoing request.
|
| 399 |
+
"""
|
| 400 |
+
if not cookies:
|
| 401 |
+
return self.cookies
|
| 402 |
+
merged_cookies = Cookies(self.cookies)
|
| 403 |
+
merged_cookies.update(cookies)
|
| 404 |
+
return merged_cookies
|
| 405 |
+
|
| 406 |
+
def _merge_headers(self, headers: HeaderTypes | None = None) -> HeaderTypes | None:
|
| 407 |
+
"""
|
| 408 |
+
Merge a headers argument together with any headers on the client,
|
| 409 |
+
to create the headers used for the outgoing request.
|
| 410 |
+
"""
|
| 411 |
+
merged_headers = Headers(self.headers)
|
| 412 |
+
merged_headers.update(headers)
|
| 413 |
+
return merged_headers
|
| 414 |
+
|
| 415 |
+
def _merge_queryparams(self, params: QueryParamTypes | None = None) -> QueryParamTypes | None:
|
| 416 |
+
"""
|
| 417 |
+
Merge a queryparams argument together with any queryparams on the client,
|
| 418 |
+
to create the queryparams used for the outgoing request.
|
| 419 |
+
"""
|
| 420 |
+
if params or self.params:
|
| 421 |
+
merged_queryparams = QueryParams(self.params)
|
| 422 |
+
return merged_queryparams.merge(params)
|
| 423 |
+
return params
|
| 424 |
+
|
| 425 |
+
def _build_auth(self, auth: AuthTypes | None) -> Auth | None:
|
| 426 |
+
if auth is None:
|
| 427 |
+
return None
|
| 428 |
+
elif isinstance(auth, tuple):
|
| 429 |
+
return BasicAuth(username=auth[0], password=auth[1])
|
| 430 |
+
elif isinstance(auth, Auth):
|
| 431 |
+
return auth
|
| 432 |
+
elif callable(auth):
|
| 433 |
+
return FunctionAuth(func=auth)
|
| 434 |
+
else:
|
| 435 |
+
raise TypeError(f'Invalid "auth" argument: {auth!r}')
|
| 436 |
+
|
| 437 |
+
def _build_request_auth(
|
| 438 |
+
self,
|
| 439 |
+
request: Request,
|
| 440 |
+
auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
|
| 441 |
+
) -> Auth:
|
| 442 |
+
auth = self._auth if isinstance(auth, UseClientDefault) else self._build_auth(auth)
|
| 443 |
+
|
| 444 |
+
if auth is not None:
|
| 445 |
+
return auth
|
| 446 |
+
|
| 447 |
+
username, password = request.url.username, request.url.password
|
| 448 |
+
if username or password:
|
| 449 |
+
return BasicAuth(username=username, password=password)
|
| 450 |
+
|
| 451 |
+
return Auth()
|
| 452 |
+
|
| 453 |
+
def _build_redirect_request(self, request: Request, response: Response) -> Request:
|
| 454 |
+
"""
|
| 455 |
+
Given a request and a redirect response, return a new request that
|
| 456 |
+
should be used to effect the redirect.
|
| 457 |
+
"""
|
| 458 |
+
method = self._redirect_method(request, response)
|
| 459 |
+
url = self._redirect_url(request, response)
|
| 460 |
+
headers = self._redirect_headers(request, url, method)
|
| 461 |
+
stream = self._redirect_stream(request, method)
|
| 462 |
+
return Request(
|
| 463 |
+
method=method,
|
| 464 |
+
url=url,
|
| 465 |
+
headers=headers,
|
| 466 |
+
cookies=self.cookies,
|
| 467 |
+
stream=stream,
|
| 468 |
+
extensions=request.extensions,
|
| 469 |
+
)
|
| 470 |
+
|
| 471 |
+
def _redirect_method(self, request: Request, response: Response) -> str:
|
| 472 |
+
"""
|
| 473 |
+
When being redirected we may want to change the method of the request
|
| 474 |
+
based on certain specs or browser behavior.
|
| 475 |
+
"""
|
| 476 |
+
method = request.method
|
| 477 |
+
|
| 478 |
+
# https://tools.ietf.org/html/rfc7231#section-6.4.4
|
| 479 |
+
if response.status_code == codes.SEE_OTHER and method != "HEAD":
|
| 480 |
+
method = "GET"
|
| 481 |
+
|
| 482 |
+
# Do what the browsers do, despite standards...
|
| 483 |
+
# Turn 302s into GETs.
|
| 484 |
+
# QUERY is excluded, per RFC 10008 Section 2.5.
|
| 485 |
+
# https://datatracker.ietf.org/doc/html/rfc10008#section-2.5
|
| 486 |
+
if response.status_code == codes.FOUND and method not in ("HEAD", "QUERY"):
|
| 487 |
+
method = "GET"
|
| 488 |
+
|
| 489 |
+
# If a POST is responded to with a 301, turn it into a GET.
|
| 490 |
+
# This bizarre behaviour is explained in 'requests' issue 1704.
|
| 491 |
+
if response.status_code == codes.MOVED_PERMANENTLY and method == "POST":
|
| 492 |
+
method = "GET"
|
| 493 |
+
|
| 494 |
+
return method
|
| 495 |
+
|
| 496 |
+
def _redirect_url(self, request: Request, response: Response) -> URL:
|
| 497 |
+
"""
|
| 498 |
+
Return the URL for the redirect to follow.
|
| 499 |
+
"""
|
| 500 |
+
location = response.headers["Location"]
|
| 501 |
+
|
| 502 |
+
try:
|
| 503 |
+
url = URL(location)
|
| 504 |
+
except InvalidURL as exc:
|
| 505 |
+
raise RemoteProtocolError(f"Invalid URL in location header: {exc}.", request=request) from None
|
| 506 |
+
|
| 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)
|
| 511 |
+
|
| 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)
|
| 516 |
+
|
| 517 |
+
# Attach previous fragment if needed (RFC 7231 7.1.2)
|
| 518 |
+
if request.url.fragment and not url.fragment:
|
| 519 |
+
url = url.copy_with(fragment=request.url.fragment)
|
| 520 |
+
|
| 521 |
+
return url
|
| 522 |
+
|
| 523 |
+
def _redirect_headers(self, request: Request, url: URL, method: str) -> Headers:
|
| 524 |
+
"""
|
| 525 |
+
Return the headers that should be used for the redirect request.
|
| 526 |
+
"""
|
| 527 |
+
headers = Headers(request.headers)
|
| 528 |
+
|
| 529 |
+
if url.origin != request.url.origin:
|
| 530 |
+
if not _is_https_redirect(request.url, url):
|
| 531 |
+
# Strip Authorization headers when responses are redirected
|
| 532 |
+
# away from the origin. (Except for direct HTTP to HTTPS redirects.)
|
| 533 |
+
headers.pop("Authorization", None)
|
| 534 |
+
|
| 535 |
+
# Update the Host header.
|
| 536 |
+
headers["Host"] = url.netloc.decode("ascii")
|
| 537 |
+
|
| 538 |
+
if method != request.method and method == "GET":
|
| 539 |
+
# If we've switch to a 'GET' request, then strip any headers which
|
| 540 |
+
# are only relevant to the request body.
|
| 541 |
+
headers.pop("Content-Length", None)
|
| 542 |
+
headers.pop("Transfer-Encoding", None)
|
| 543 |
+
|
| 544 |
+
# We should use the client cookie store to determine any cookie header,
|
| 545 |
+
# rather than whatever was on the original outgoing request.
|
| 546 |
+
headers.pop("Cookie", None)
|
| 547 |
+
|
| 548 |
+
return headers
|
| 549 |
+
|
| 550 |
+
def _redirect_stream(self, request: Request, method: str) -> SyncByteStream | AsyncByteStream | None:
|
| 551 |
+
"""
|
| 552 |
+
Return the body that should be used for the redirect request.
|
| 553 |
+
"""
|
| 554 |
+
if method != request.method and method == "GET":
|
| 555 |
+
return None
|
| 556 |
+
|
| 557 |
+
return request.stream
|
| 558 |
+
|
| 559 |
+
def _set_timeout(self, request: Request) -> None:
|
| 560 |
+
if "timeout" not in request.extensions:
|
| 561 |
+
timeout = self.timeout if isinstance(self.timeout, UseClientDefault) else Timeout(self.timeout)
|
| 562 |
+
request.extensions = dict(**request.extensions, timeout=timeout.as_dict())
|
| 563 |
+
|
| 564 |
+
|
| 565 |
+
class Client(BaseClient):
|
| 566 |
+
"""
|
| 567 |
+
An HTTP client, with connection pooling, HTTP/2, redirects, cookie persistence, etc.
|
| 568 |
+
|
| 569 |
+
It can be shared between threads.
|
| 570 |
+
|
| 571 |
+
Usage:
|
| 572 |
+
|
| 573 |
+
```python
|
| 574 |
+
>>> client = httpx2.Client()
|
| 575 |
+
>>> response = client.get('https://example.org')
|
| 576 |
+
```
|
| 577 |
+
|
| 578 |
+
**Parameters:**
|
| 579 |
+
|
| 580 |
+
* **auth** - *(optional)* An authentication class to use when sending
|
| 581 |
+
requests.
|
| 582 |
+
* **params** - *(optional)* Query parameters to include in request URLs, as
|
| 583 |
+
a string, dictionary, or sequence of two-tuples.
|
| 584 |
+
* **headers** - *(optional)* Dictionary of HTTP headers to include when
|
| 585 |
+
sending requests.
|
| 586 |
+
* **cookies** - *(optional)* Dictionary of Cookie items to include when
|
| 587 |
+
sending requests.
|
| 588 |
+
* **verify** - *(optional)* Either `True` to use an SSL context with the
|
| 589 |
+
default CA bundle, `False` to disable verification, or an instance of
|
| 590 |
+
`ssl.SSLContext` to use a custom context.
|
| 591 |
+
* **http2** - *(optional)* A boolean indicating if HTTP/2 support should be
|
| 592 |
+
enabled. Defaults to `False`.
|
| 593 |
+
* **proxy** - *(optional)* A proxy URL where all the traffic should be routed.
|
| 594 |
+
* **mounts** - *(optional)* A dictionary mapping URL patterns to transports,
|
| 595 |
+
used to route requests through specific transports based on the URL.
|
| 596 |
+
* **timeout** - *(optional)* The timeout configuration to use when sending
|
| 597 |
+
requests.
|
| 598 |
+
* **limits** - *(optional)* The limits configuration to use.
|
| 599 |
+
* **max_redirects** - *(optional)* The maximum number of redirect responses
|
| 600 |
+
that should be followed.
|
| 601 |
+
* **base_url** - *(optional)* A URL to use as the base when building
|
| 602 |
+
request URLs.
|
| 603 |
+
* **transport** - *(optional)* A transport class to use for sending requests
|
| 604 |
+
over the network.
|
| 605 |
+
* **trust_env** - *(optional)* Enables or disables usage of environment
|
| 606 |
+
variables for configuration.
|
| 607 |
+
* **default_encoding** - *(optional)* The default encoding to use for decoding
|
| 608 |
+
response text, if no charset information is included in a response Content-Type
|
| 609 |
+
header. Set to a callable for automatic character set detection. Default: "utf-8".
|
| 610 |
+
"""
|
| 611 |
+
|
| 612 |
+
def __init__(
|
| 613 |
+
self,
|
| 614 |
+
*,
|
| 615 |
+
auth: AuthTypes | None = None,
|
| 616 |
+
params: QueryParamTypes | None = None,
|
| 617 |
+
headers: HeaderTypes | None = None,
|
| 618 |
+
cookies: CookieTypes | None = None,
|
| 619 |
+
verify: ssl.SSLContext | str | bool = True,
|
| 620 |
+
cert: CertTypes | None = None,
|
| 621 |
+
trust_env: bool = True,
|
| 622 |
+
http1: bool = True,
|
| 623 |
+
http2: bool = False,
|
| 624 |
+
proxy: ProxyTypes | None = None,
|
| 625 |
+
mounts: None | (typing.Mapping[str, BaseTransport | None]) = None,
|
| 626 |
+
timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
|
| 627 |
+
follow_redirects: bool = False,
|
| 628 |
+
limits: Limits = DEFAULT_LIMITS,
|
| 629 |
+
max_redirects: int = DEFAULT_MAX_REDIRECTS,
|
| 630 |
+
event_hooks: None | (typing.Mapping[str, list[EventHook]]) = None,
|
| 631 |
+
base_url: URL | str = "",
|
| 632 |
+
transport: BaseTransport | None = None,
|
| 633 |
+
default_encoding: str | typing.Callable[[bytes], str | None] = "utf-8",
|
| 634 |
+
) -> None:
|
| 635 |
+
super().__init__(
|
| 636 |
+
auth=auth,
|
| 637 |
+
params=params,
|
| 638 |
+
headers=headers,
|
| 639 |
+
cookies=cookies,
|
| 640 |
+
timeout=timeout,
|
| 641 |
+
follow_redirects=follow_redirects,
|
| 642 |
+
max_redirects=max_redirects,
|
| 643 |
+
event_hooks=event_hooks,
|
| 644 |
+
base_url=base_url,
|
| 645 |
+
trust_env=trust_env,
|
| 646 |
+
default_encoding=default_encoding,
|
| 647 |
+
)
|
| 648 |
+
|
| 649 |
+
if http2:
|
| 650 |
+
try:
|
| 651 |
+
import h2 # noqa
|
| 652 |
+
except ImportError: # pragma: no cover
|
| 653 |
+
raise ImportError(
|
| 654 |
+
"Using http2=True, but the 'h2' package is not installed. "
|
| 655 |
+
"Make sure to install httpx using `pip install httpx[http2]`."
|
| 656 |
+
) from None
|
| 657 |
+
|
| 658 |
+
allow_env_proxies = trust_env and transport is None
|
| 659 |
+
proxy_map = self._get_proxy_map(proxy, allow_env_proxies)
|
| 660 |
+
|
| 661 |
+
self._transport = self._init_transport(
|
| 662 |
+
verify=verify,
|
| 663 |
+
cert=cert,
|
| 664 |
+
trust_env=trust_env,
|
| 665 |
+
http1=http1,
|
| 666 |
+
http2=http2,
|
| 667 |
+
limits=limits,
|
| 668 |
+
transport=transport,
|
| 669 |
+
)
|
| 670 |
+
self._mounts: dict[URLPattern, BaseTransport | None] = {
|
| 671 |
+
URLPattern(key): None
|
| 672 |
+
if proxy is None
|
| 673 |
+
else self._init_proxy_transport(
|
| 674 |
+
proxy,
|
| 675 |
+
verify=verify,
|
| 676 |
+
cert=cert,
|
| 677 |
+
trust_env=trust_env,
|
| 678 |
+
http1=http1,
|
| 679 |
+
http2=http2,
|
| 680 |
+
limits=limits,
|
| 681 |
+
)
|
| 682 |
+
for key, proxy in proxy_map.items()
|
| 683 |
+
}
|
| 684 |
+
if mounts is not None:
|
| 685 |
+
self._mounts.update({URLPattern(key): transport for key, transport in mounts.items()})
|
| 686 |
+
|
| 687 |
+
self._mounts = dict(sorted(self._mounts.items()))
|
| 688 |
+
|
| 689 |
+
def _init_transport(
|
| 690 |
+
self,
|
| 691 |
+
verify: ssl.SSLContext | str | bool = True,
|
| 692 |
+
cert: CertTypes | None = None,
|
| 693 |
+
trust_env: bool = True,
|
| 694 |
+
http1: bool = True,
|
| 695 |
+
http2: bool = False,
|
| 696 |
+
limits: Limits = DEFAULT_LIMITS,
|
| 697 |
+
transport: BaseTransport | None = None,
|
| 698 |
+
) -> BaseTransport:
|
| 699 |
+
if transport is not None:
|
| 700 |
+
return transport
|
| 701 |
+
|
| 702 |
+
return HTTPTransport(
|
| 703 |
+
verify=verify,
|
| 704 |
+
cert=cert,
|
| 705 |
+
trust_env=trust_env,
|
| 706 |
+
http1=http1,
|
| 707 |
+
http2=http2,
|
| 708 |
+
limits=limits,
|
| 709 |
+
)
|
| 710 |
+
|
| 711 |
+
def _init_proxy_transport(
|
| 712 |
+
self,
|
| 713 |
+
proxy: Proxy,
|
| 714 |
+
verify: ssl.SSLContext | str | bool = True,
|
| 715 |
+
cert: CertTypes | None = None,
|
| 716 |
+
trust_env: bool = True,
|
| 717 |
+
http1: bool = True,
|
| 718 |
+
http2: bool = False,
|
| 719 |
+
limits: Limits = DEFAULT_LIMITS,
|
| 720 |
+
) -> BaseTransport:
|
| 721 |
+
return HTTPTransport(
|
| 722 |
+
verify=verify,
|
| 723 |
+
cert=cert,
|
| 724 |
+
trust_env=trust_env,
|
| 725 |
+
http1=http1,
|
| 726 |
+
http2=http2,
|
| 727 |
+
limits=limits,
|
| 728 |
+
proxy=proxy,
|
| 729 |
+
)
|
| 730 |
+
|
| 731 |
+
def _transport_for_url(self, url: URL) -> BaseTransport:
|
| 732 |
+
"""
|
| 733 |
+
Returns the transport instance that should be used for a given URL.
|
| 734 |
+
This will either be the standard connection pool, or a proxy.
|
| 735 |
+
"""
|
| 736 |
+
for pattern, transport in self._mounts.items():
|
| 737 |
+
if pattern.matches(url):
|
| 738 |
+
return self._transport if transport is None else transport
|
| 739 |
+
|
| 740 |
+
return self._transport
|
| 741 |
+
|
| 742 |
+
def request(
|
| 743 |
+
self,
|
| 744 |
+
method: str,
|
| 745 |
+
url: URL | str,
|
| 746 |
+
*,
|
| 747 |
+
content: RequestContent | None = None,
|
| 748 |
+
data: RequestData | None = None,
|
| 749 |
+
files: RequestFiles | None = None,
|
| 750 |
+
json: typing.Any | None = None,
|
| 751 |
+
params: QueryParamTypes | None = None,
|
| 752 |
+
headers: HeaderTypes | None = None,
|
| 753 |
+
cookies: CookieTypes | None = None,
|
| 754 |
+
auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
|
| 755 |
+
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 756 |
+
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 757 |
+
extensions: RequestExtensions | None = None,
|
| 758 |
+
) -> Response:
|
| 759 |
+
"""
|
| 760 |
+
Build and send a request.
|
| 761 |
+
|
| 762 |
+
Equivalent to:
|
| 763 |
+
|
| 764 |
+
```python
|
| 765 |
+
request = client.build_request(...)
|
| 766 |
+
response = client.send(request, ...)
|
| 767 |
+
```
|
| 768 |
+
|
| 769 |
+
See `Client.build_request()`, `Client.send()` and
|
| 770 |
+
[Merging of configuration][0] for how the various parameters
|
| 771 |
+
are merged with client-level configuration.
|
| 772 |
+
|
| 773 |
+
[0]: advanced/clients.md#merging-of-configuration
|
| 774 |
+
"""
|
| 775 |
+
if cookies is not None:
|
| 776 |
+
message = (
|
| 777 |
+
"Setting per-request cookies=<...> is being deprecated, because "
|
| 778 |
+
"the expected behaviour on cookie persistence is ambiguous. Set "
|
| 779 |
+
"cookies directly on the client instance instead."
|
| 780 |
+
)
|
| 781 |
+
warnings.warn(message, DeprecationWarning, stacklevel=2)
|
| 782 |
+
|
| 783 |
+
request = self.build_request(
|
| 784 |
+
method=method,
|
| 785 |
+
url=url,
|
| 786 |
+
content=content,
|
| 787 |
+
data=data,
|
| 788 |
+
files=files,
|
| 789 |
+
json=json,
|
| 790 |
+
params=params,
|
| 791 |
+
headers=headers,
|
| 792 |
+
cookies=cookies,
|
| 793 |
+
timeout=timeout,
|
| 794 |
+
extensions=extensions,
|
| 795 |
+
)
|
| 796 |
+
return self.send(request, auth=auth, follow_redirects=follow_redirects)
|
| 797 |
+
|
| 798 |
+
@contextmanager
|
| 799 |
+
def stream(
|
| 800 |
+
self,
|
| 801 |
+
method: str,
|
| 802 |
+
url: URL | str,
|
| 803 |
+
*,
|
| 804 |
+
content: RequestContent | None = None,
|
| 805 |
+
data: RequestData | None = None,
|
| 806 |
+
files: RequestFiles | None = None,
|
| 807 |
+
json: typing.Any | None = None,
|
| 808 |
+
params: QueryParamTypes | None = None,
|
| 809 |
+
headers: HeaderTypes | None = None,
|
| 810 |
+
cookies: CookieTypes | None = None,
|
| 811 |
+
auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
|
| 812 |
+
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 813 |
+
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 814 |
+
extensions: RequestExtensions | None = None,
|
| 815 |
+
) -> Generator[Response]:
|
| 816 |
+
"""
|
| 817 |
+
Alternative to `httpx2.request()` that streams the response body
|
| 818 |
+
instead of loading it into memory at once.
|
| 819 |
+
|
| 820 |
+
**Parameters**: See `httpx2.request`.
|
| 821 |
+
|
| 822 |
+
See also: [Streaming Responses][0]
|
| 823 |
+
|
| 824 |
+
[0]: quickstart.md#streaming-responses
|
| 825 |
+
"""
|
| 826 |
+
request = self.build_request(
|
| 827 |
+
method=method,
|
| 828 |
+
url=url,
|
| 829 |
+
content=content,
|
| 830 |
+
data=data,
|
| 831 |
+
files=files,
|
| 832 |
+
json=json,
|
| 833 |
+
params=params,
|
| 834 |
+
headers=headers,
|
| 835 |
+
cookies=cookies,
|
| 836 |
+
timeout=timeout,
|
| 837 |
+
extensions=extensions,
|
| 838 |
+
)
|
| 839 |
+
response = self.send(
|
| 840 |
+
request=request,
|
| 841 |
+
auth=auth,
|
| 842 |
+
follow_redirects=follow_redirects,
|
| 843 |
+
stream=True,
|
| 844 |
+
)
|
| 845 |
+
try:
|
| 846 |
+
yield response
|
| 847 |
+
finally:
|
| 848 |
+
response.close()
|
| 849 |
+
|
| 850 |
+
@contextmanager
|
| 851 |
+
def sse(
|
| 852 |
+
self,
|
| 853 |
+
url: URL | str,
|
| 854 |
+
*,
|
| 855 |
+
method: str = "GET",
|
| 856 |
+
content: RequestContent | None = None,
|
| 857 |
+
data: RequestData | None = None,
|
| 858 |
+
files: RequestFiles | None = None,
|
| 859 |
+
json: typing.Any | None = None,
|
| 860 |
+
params: QueryParamTypes | None = None,
|
| 861 |
+
headers: HeaderTypes | None = None,
|
| 862 |
+
cookies: CookieTypes | None = None,
|
| 863 |
+
auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
|
| 864 |
+
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 865 |
+
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 866 |
+
extensions: RequestExtensions | None = None,
|
| 867 |
+
max_event_size: int | None = DEFAULT_MAX_EVENT_SIZE_BYTES,
|
| 868 |
+
) -> Generator[EventSource]:
|
| 869 |
+
"""
|
| 870 |
+
Connect to a server-sent events endpoint and yield an `EventSource`.
|
| 871 |
+
|
| 872 |
+
Iterating the `EventSource` yields `ServerSentEvent` instances.
|
| 873 |
+
|
| 874 |
+
**Parameters**: See `httpx2.request`.
|
| 875 |
+
"""
|
| 876 |
+
with self.stream(
|
| 877 |
+
method,
|
| 878 |
+
url,
|
| 879 |
+
content=content,
|
| 880 |
+
data=data,
|
| 881 |
+
files=files,
|
| 882 |
+
json=json,
|
| 883 |
+
params=params,
|
| 884 |
+
headers={"Accept": "text/event-stream", "Cache-Control": "no-store"} | Headers(headers),
|
| 885 |
+
cookies=cookies,
|
| 886 |
+
auth=auth,
|
| 887 |
+
follow_redirects=follow_redirects,
|
| 888 |
+
timeout=timeout,
|
| 889 |
+
extensions=extensions,
|
| 890 |
+
) as response:
|
| 891 |
+
yield EventSource(response, max_event_size=max_event_size)
|
| 892 |
+
|
| 893 |
+
@contextmanager
|
| 894 |
+
def websocket(
|
| 895 |
+
self,
|
| 896 |
+
url: URL | str,
|
| 897 |
+
*,
|
| 898 |
+
max_message_size_bytes: int = DEFAULT_MAX_MESSAGE_SIZE_BYTES,
|
| 899 |
+
queue_size: int = DEFAULT_QUEUE_SIZE,
|
| 900 |
+
keepalive_ping_interval_seconds: float | None = DEFAULT_KEEPALIVE_PING_INTERVAL_SECONDS,
|
| 901 |
+
keepalive_ping_timeout_seconds: float | None = DEFAULT_KEEPALIVE_PING_TIMEOUT_SECONDS,
|
| 902 |
+
subprotocols: list[str] | None = None,
|
| 903 |
+
params: QueryParamTypes | None = None,
|
| 904 |
+
headers: HeaderTypes | None = None,
|
| 905 |
+
cookies: CookieTypes | None = None,
|
| 906 |
+
auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
|
| 907 |
+
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 908 |
+
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 909 |
+
extensions: RequestExtensions | None = None,
|
| 910 |
+
) -> Generator[WebSocketSession]:
|
| 911 |
+
"""
|
| 912 |
+
Open a WebSocket session, using this client's configuration.
|
| 913 |
+
|
| 914 |
+
The session is closed automatically when exiting the context manager.
|
| 915 |
+
|
| 916 |
+
```python
|
| 917 |
+
with httpx2.Client() as client:
|
| 918 |
+
with client.websocket("ws://localhost:8000/ws") as ws:
|
| 919 |
+
ws.send_text("Hello!")
|
| 920 |
+
message = ws.receive_text()
|
| 921 |
+
```
|
| 922 |
+
"""
|
| 923 |
+
try:
|
| 924 |
+
from .websockets._api import connect_ws
|
| 925 |
+
except ImportError: # pragma: no cover
|
| 926 |
+
raise ImportError(
|
| 927 |
+
"WebSocket support requires the `wsproto` package. Install it with `pip install httpx2[ws]`."
|
| 928 |
+
)
|
| 929 |
+
|
| 930 |
+
with connect_ws(
|
| 931 |
+
str(url),
|
| 932 |
+
self,
|
| 933 |
+
max_message_size_bytes=max_message_size_bytes,
|
| 934 |
+
queue_size=queue_size,
|
| 935 |
+
keepalive_ping_interval_seconds=keepalive_ping_interval_seconds,
|
| 936 |
+
keepalive_ping_timeout_seconds=keepalive_ping_timeout_seconds,
|
| 937 |
+
subprotocols=subprotocols,
|
| 938 |
+
params=params,
|
| 939 |
+
headers=headers,
|
| 940 |
+
cookies=cookies,
|
| 941 |
+
auth=auth,
|
| 942 |
+
follow_redirects=follow_redirects,
|
| 943 |
+
timeout=timeout,
|
| 944 |
+
extensions=extensions,
|
| 945 |
+
) as session:
|
| 946 |
+
yield session
|
| 947 |
+
|
| 948 |
+
def send(
|
| 949 |
+
self,
|
| 950 |
+
request: Request,
|
| 951 |
+
*,
|
| 952 |
+
stream: bool = False,
|
| 953 |
+
auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
|
| 954 |
+
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 955 |
+
) -> Response:
|
| 956 |
+
"""
|
| 957 |
+
Send a request.
|
| 958 |
+
|
| 959 |
+
The request is sent as-is, unmodified.
|
| 960 |
+
|
| 961 |
+
Typically you'll want to build one with `Client.build_request()`
|
| 962 |
+
so that any client-level configuration is merged into the request,
|
| 963 |
+
but passing an explicit `httpx2.Request()` is supported as well.
|
| 964 |
+
|
| 965 |
+
See also: [Request instances][0]
|
| 966 |
+
|
| 967 |
+
[0]: advanced/clients.md#request-instances
|
| 968 |
+
"""
|
| 969 |
+
if self._state == ClientState.CLOSED:
|
| 970 |
+
raise RuntimeError("Cannot send a request, as the client has been closed.")
|
| 971 |
+
|
| 972 |
+
self._state = ClientState.OPENED
|
| 973 |
+
follow_redirects = self.follow_redirects if isinstance(follow_redirects, UseClientDefault) else follow_redirects
|
| 974 |
+
|
| 975 |
+
self._set_timeout(request)
|
| 976 |
+
|
| 977 |
+
auth = self._build_request_auth(request, auth)
|
| 978 |
+
|
| 979 |
+
response = self._send_handling_auth(
|
| 980 |
+
request,
|
| 981 |
+
auth=auth,
|
| 982 |
+
follow_redirects=follow_redirects,
|
| 983 |
+
history=[],
|
| 984 |
+
)
|
| 985 |
+
try:
|
| 986 |
+
if not stream:
|
| 987 |
+
response.read()
|
| 988 |
+
|
| 989 |
+
return response
|
| 990 |
+
|
| 991 |
+
except BaseException as exc:
|
| 992 |
+
response.close()
|
| 993 |
+
raise exc
|
| 994 |
+
|
| 995 |
+
def _send_handling_auth(
|
| 996 |
+
self,
|
| 997 |
+
request: Request,
|
| 998 |
+
auth: Auth,
|
| 999 |
+
follow_redirects: bool,
|
| 1000 |
+
history: list[Response],
|
| 1001 |
+
) -> Response:
|
| 1002 |
+
auth_flow = auth.sync_auth_flow(request)
|
| 1003 |
+
try:
|
| 1004 |
+
request = next(auth_flow)
|
| 1005 |
+
|
| 1006 |
+
while True:
|
| 1007 |
+
response = self._send_handling_redirects(
|
| 1008 |
+
request,
|
| 1009 |
+
follow_redirects=follow_redirects,
|
| 1010 |
+
history=history,
|
| 1011 |
+
)
|
| 1012 |
+
try:
|
| 1013 |
+
try:
|
| 1014 |
+
next_request = auth_flow.send(response)
|
| 1015 |
+
except StopIteration:
|
| 1016 |
+
return response
|
| 1017 |
+
|
| 1018 |
+
response.history = list(history)
|
| 1019 |
+
response.read()
|
| 1020 |
+
request = next_request
|
| 1021 |
+
history.append(response)
|
| 1022 |
+
|
| 1023 |
+
except BaseException as exc:
|
| 1024 |
+
response.close()
|
| 1025 |
+
raise exc
|
| 1026 |
+
finally:
|
| 1027 |
+
auth_flow.close()
|
| 1028 |
+
|
| 1029 |
+
def _send_handling_redirects(
|
| 1030 |
+
self,
|
| 1031 |
+
request: Request,
|
| 1032 |
+
follow_redirects: bool,
|
| 1033 |
+
history: list[Response],
|
| 1034 |
+
) -> Response:
|
| 1035 |
+
while True:
|
| 1036 |
+
if len(history) > self.max_redirects:
|
| 1037 |
+
raise TooManyRedirects("Exceeded maximum allowed redirects.", request=request)
|
| 1038 |
+
|
| 1039 |
+
for hook in self._event_hooks["request"]:
|
| 1040 |
+
hook(request)
|
| 1041 |
+
|
| 1042 |
+
response = self._send_single_request(request)
|
| 1043 |
+
try:
|
| 1044 |
+
for hook in self._event_hooks["response"]:
|
| 1045 |
+
hook(response)
|
| 1046 |
+
response.history = list(history)
|
| 1047 |
+
|
| 1048 |
+
if not response.has_redirect_location:
|
| 1049 |
+
return response
|
| 1050 |
+
|
| 1051 |
+
request = self._build_redirect_request(request, response)
|
| 1052 |
+
history = history + [response]
|
| 1053 |
+
|
| 1054 |
+
if follow_redirects:
|
| 1055 |
+
response.read()
|
| 1056 |
+
else:
|
| 1057 |
+
response.next_request = request
|
| 1058 |
+
return response
|
| 1059 |
+
|
| 1060 |
+
except BaseException as exc:
|
| 1061 |
+
response.close()
|
| 1062 |
+
raise exc
|
| 1063 |
+
|
| 1064 |
+
def _send_single_request(self, request: Request) -> Response:
|
| 1065 |
+
"""
|
| 1066 |
+
Sends a single request, without handling any redirections.
|
| 1067 |
+
"""
|
| 1068 |
+
transport = self._transport_for_url(request.url)
|
| 1069 |
+
start = time.perf_counter()
|
| 1070 |
+
|
| 1071 |
+
if not isinstance(request.stream, SyncByteStream):
|
| 1072 |
+
raise RuntimeError("Attempted to send an async request with a sync Client instance.")
|
| 1073 |
+
|
| 1074 |
+
with request_context(request=request):
|
| 1075 |
+
response = transport.handle_request(request)
|
| 1076 |
+
|
| 1077 |
+
assert isinstance(response.stream, SyncByteStream)
|
| 1078 |
+
|
| 1079 |
+
response.request = request
|
| 1080 |
+
response.stream = BoundSyncStream(response.stream, start=start)
|
| 1081 |
+
self.cookies.extract_cookies(response)
|
| 1082 |
+
response.default_encoding = self._default_encoding
|
| 1083 |
+
|
| 1084 |
+
logger.info(
|
| 1085 |
+
'HTTP Request: %s %s "%s %d %s"',
|
| 1086 |
+
request.method,
|
| 1087 |
+
request.url,
|
| 1088 |
+
response.http_version,
|
| 1089 |
+
response.status_code,
|
| 1090 |
+
response.reason_phrase,
|
| 1091 |
+
)
|
| 1092 |
+
|
| 1093 |
+
return response
|
| 1094 |
+
|
| 1095 |
+
def get(
|
| 1096 |
+
self,
|
| 1097 |
+
url: URL | str,
|
| 1098 |
+
*,
|
| 1099 |
+
params: QueryParamTypes | None = None,
|
| 1100 |
+
headers: HeaderTypes | None = None,
|
| 1101 |
+
cookies: CookieTypes | None = None,
|
| 1102 |
+
auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
|
| 1103 |
+
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1104 |
+
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1105 |
+
extensions: RequestExtensions | None = None,
|
| 1106 |
+
) -> Response:
|
| 1107 |
+
"""
|
| 1108 |
+
Send a `GET` request.
|
| 1109 |
+
|
| 1110 |
+
**Parameters**: See `httpx2.request`.
|
| 1111 |
+
"""
|
| 1112 |
+
return self.request(
|
| 1113 |
+
"GET",
|
| 1114 |
+
url,
|
| 1115 |
+
params=params,
|
| 1116 |
+
headers=headers,
|
| 1117 |
+
cookies=cookies,
|
| 1118 |
+
auth=auth,
|
| 1119 |
+
follow_redirects=follow_redirects,
|
| 1120 |
+
timeout=timeout,
|
| 1121 |
+
extensions=extensions,
|
| 1122 |
+
)
|
| 1123 |
+
|
| 1124 |
+
def options(
|
| 1125 |
+
self,
|
| 1126 |
+
url: URL | str,
|
| 1127 |
+
*,
|
| 1128 |
+
params: QueryParamTypes | None = None,
|
| 1129 |
+
headers: HeaderTypes | None = None,
|
| 1130 |
+
cookies: CookieTypes | None = None,
|
| 1131 |
+
auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1132 |
+
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1133 |
+
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1134 |
+
extensions: RequestExtensions | None = None,
|
| 1135 |
+
) -> Response:
|
| 1136 |
+
"""
|
| 1137 |
+
Send an `OPTIONS` request.
|
| 1138 |
+
|
| 1139 |
+
**Parameters**: See `httpx2.request`.
|
| 1140 |
+
"""
|
| 1141 |
+
return self.request(
|
| 1142 |
+
"OPTIONS",
|
| 1143 |
+
url,
|
| 1144 |
+
params=params,
|
| 1145 |
+
headers=headers,
|
| 1146 |
+
cookies=cookies,
|
| 1147 |
+
auth=auth,
|
| 1148 |
+
follow_redirects=follow_redirects,
|
| 1149 |
+
timeout=timeout,
|
| 1150 |
+
extensions=extensions,
|
| 1151 |
+
)
|
| 1152 |
+
|
| 1153 |
+
def head(
|
| 1154 |
+
self,
|
| 1155 |
+
url: URL | str,
|
| 1156 |
+
*,
|
| 1157 |
+
params: QueryParamTypes | None = None,
|
| 1158 |
+
headers: HeaderTypes | None = None,
|
| 1159 |
+
cookies: CookieTypes | None = None,
|
| 1160 |
+
auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1161 |
+
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1162 |
+
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1163 |
+
extensions: RequestExtensions | None = None,
|
| 1164 |
+
) -> Response:
|
| 1165 |
+
"""
|
| 1166 |
+
Send a `HEAD` request.
|
| 1167 |
+
|
| 1168 |
+
**Parameters**: See `httpx2.request`.
|
| 1169 |
+
"""
|
| 1170 |
+
return self.request(
|
| 1171 |
+
"HEAD",
|
| 1172 |
+
url,
|
| 1173 |
+
params=params,
|
| 1174 |
+
headers=headers,
|
| 1175 |
+
cookies=cookies,
|
| 1176 |
+
auth=auth,
|
| 1177 |
+
follow_redirects=follow_redirects,
|
| 1178 |
+
timeout=timeout,
|
| 1179 |
+
extensions=extensions,
|
| 1180 |
+
)
|
| 1181 |
+
|
| 1182 |
+
def post(
|
| 1183 |
+
self,
|
| 1184 |
+
url: URL | str,
|
| 1185 |
+
*,
|
| 1186 |
+
content: RequestContent | None = None,
|
| 1187 |
+
data: RequestData | None = None,
|
| 1188 |
+
files: RequestFiles | None = None,
|
| 1189 |
+
json: typing.Any | None = None,
|
| 1190 |
+
params: QueryParamTypes | None = None,
|
| 1191 |
+
headers: HeaderTypes | None = None,
|
| 1192 |
+
cookies: CookieTypes | None = None,
|
| 1193 |
+
auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1194 |
+
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1195 |
+
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1196 |
+
extensions: RequestExtensions | None = None,
|
| 1197 |
+
) -> Response:
|
| 1198 |
+
"""
|
| 1199 |
+
Send a `POST` request.
|
| 1200 |
+
|
| 1201 |
+
**Parameters**: See `httpx2.request`.
|
| 1202 |
+
"""
|
| 1203 |
+
return self.request(
|
| 1204 |
+
"POST",
|
| 1205 |
+
url,
|
| 1206 |
+
content=content,
|
| 1207 |
+
data=data,
|
| 1208 |
+
files=files,
|
| 1209 |
+
json=json,
|
| 1210 |
+
params=params,
|
| 1211 |
+
headers=headers,
|
| 1212 |
+
cookies=cookies,
|
| 1213 |
+
auth=auth,
|
| 1214 |
+
follow_redirects=follow_redirects,
|
| 1215 |
+
timeout=timeout,
|
| 1216 |
+
extensions=extensions,
|
| 1217 |
+
)
|
| 1218 |
+
|
| 1219 |
+
def put(
|
| 1220 |
+
self,
|
| 1221 |
+
url: URL | str,
|
| 1222 |
+
*,
|
| 1223 |
+
content: RequestContent | None = None,
|
| 1224 |
+
data: RequestData | None = None,
|
| 1225 |
+
files: RequestFiles | None = None,
|
| 1226 |
+
json: typing.Any | None = None,
|
| 1227 |
+
params: QueryParamTypes | None = None,
|
| 1228 |
+
headers: HeaderTypes | None = None,
|
| 1229 |
+
cookies: CookieTypes | None = None,
|
| 1230 |
+
auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1231 |
+
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1232 |
+
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1233 |
+
extensions: RequestExtensions | None = None,
|
| 1234 |
+
) -> Response:
|
| 1235 |
+
"""
|
| 1236 |
+
Send a `PUT` request.
|
| 1237 |
+
|
| 1238 |
+
**Parameters**: See `httpx2.request`.
|
| 1239 |
+
"""
|
| 1240 |
+
return self.request(
|
| 1241 |
+
"PUT",
|
| 1242 |
+
url,
|
| 1243 |
+
content=content,
|
| 1244 |
+
data=data,
|
| 1245 |
+
files=files,
|
| 1246 |
+
json=json,
|
| 1247 |
+
params=params,
|
| 1248 |
+
headers=headers,
|
| 1249 |
+
cookies=cookies,
|
| 1250 |
+
auth=auth,
|
| 1251 |
+
follow_redirects=follow_redirects,
|
| 1252 |
+
timeout=timeout,
|
| 1253 |
+
extensions=extensions,
|
| 1254 |
+
)
|
| 1255 |
+
|
| 1256 |
+
def patch(
|
| 1257 |
+
self,
|
| 1258 |
+
url: URL | str,
|
| 1259 |
+
*,
|
| 1260 |
+
content: RequestContent | None = None,
|
| 1261 |
+
data: RequestData | None = None,
|
| 1262 |
+
files: RequestFiles | None = None,
|
| 1263 |
+
json: typing.Any | None = None,
|
| 1264 |
+
params: QueryParamTypes | None = None,
|
| 1265 |
+
headers: HeaderTypes | None = None,
|
| 1266 |
+
cookies: CookieTypes | None = None,
|
| 1267 |
+
auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1268 |
+
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1269 |
+
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1270 |
+
extensions: RequestExtensions | None = None,
|
| 1271 |
+
) -> Response:
|
| 1272 |
+
"""
|
| 1273 |
+
Send a `PATCH` request.
|
| 1274 |
+
|
| 1275 |
+
**Parameters**: See `httpx2.request`.
|
| 1276 |
+
"""
|
| 1277 |
+
return self.request(
|
| 1278 |
+
"PATCH",
|
| 1279 |
+
url,
|
| 1280 |
+
content=content,
|
| 1281 |
+
data=data,
|
| 1282 |
+
files=files,
|
| 1283 |
+
json=json,
|
| 1284 |
+
params=params,
|
| 1285 |
+
headers=headers,
|
| 1286 |
+
cookies=cookies,
|
| 1287 |
+
auth=auth,
|
| 1288 |
+
follow_redirects=follow_redirects,
|
| 1289 |
+
timeout=timeout,
|
| 1290 |
+
extensions=extensions,
|
| 1291 |
+
)
|
| 1292 |
+
|
| 1293 |
+
def delete(
|
| 1294 |
+
self,
|
| 1295 |
+
url: URL | str,
|
| 1296 |
+
*,
|
| 1297 |
+
params: QueryParamTypes | None = None,
|
| 1298 |
+
headers: HeaderTypes | None = None,
|
| 1299 |
+
cookies: CookieTypes | None = None,
|
| 1300 |
+
auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1301 |
+
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1302 |
+
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1303 |
+
extensions: RequestExtensions | None = None,
|
| 1304 |
+
) -> Response:
|
| 1305 |
+
"""
|
| 1306 |
+
Send a `DELETE` request.
|
| 1307 |
+
|
| 1308 |
+
**Parameters**: See `httpx2.request`.
|
| 1309 |
+
"""
|
| 1310 |
+
return self.request(
|
| 1311 |
+
"DELETE",
|
| 1312 |
+
url,
|
| 1313 |
+
params=params,
|
| 1314 |
+
headers=headers,
|
| 1315 |
+
cookies=cookies,
|
| 1316 |
+
auth=auth,
|
| 1317 |
+
follow_redirects=follow_redirects,
|
| 1318 |
+
timeout=timeout,
|
| 1319 |
+
extensions=extensions,
|
| 1320 |
+
)
|
| 1321 |
+
|
| 1322 |
+
def query(
|
| 1323 |
+
self,
|
| 1324 |
+
url: URL | str,
|
| 1325 |
+
*,
|
| 1326 |
+
content: RequestContent | None = None,
|
| 1327 |
+
data: RequestData | None = None,
|
| 1328 |
+
files: RequestFiles | None = None,
|
| 1329 |
+
json: typing.Any | None = None,
|
| 1330 |
+
params: QueryParamTypes | None = None,
|
| 1331 |
+
headers: HeaderTypes | None = None,
|
| 1332 |
+
cookies: CookieTypes | None = None,
|
| 1333 |
+
auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1334 |
+
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1335 |
+
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1336 |
+
extensions: RequestExtensions | None = None,
|
| 1337 |
+
) -> Response:
|
| 1338 |
+
"""
|
| 1339 |
+
Send a `QUERY` request.
|
| 1340 |
+
|
| 1341 |
+
**Parameters**: See `httpx2.request`.
|
| 1342 |
+
"""
|
| 1343 |
+
return self.request(
|
| 1344 |
+
"QUERY",
|
| 1345 |
+
url,
|
| 1346 |
+
content=content,
|
| 1347 |
+
data=data,
|
| 1348 |
+
files=files,
|
| 1349 |
+
json=json,
|
| 1350 |
+
params=params,
|
| 1351 |
+
headers=headers,
|
| 1352 |
+
cookies=cookies,
|
| 1353 |
+
auth=auth,
|
| 1354 |
+
follow_redirects=follow_redirects,
|
| 1355 |
+
timeout=timeout,
|
| 1356 |
+
extensions=extensions,
|
| 1357 |
+
)
|
| 1358 |
+
|
| 1359 |
+
def close(self) -> None:
|
| 1360 |
+
"""
|
| 1361 |
+
Close transport and proxies.
|
| 1362 |
+
"""
|
| 1363 |
+
if self._state != ClientState.CLOSED:
|
| 1364 |
+
self._state = ClientState.CLOSED
|
| 1365 |
+
|
| 1366 |
+
self._transport.close()
|
| 1367 |
+
for transport in self._mounts.values():
|
| 1368 |
+
if transport is not None:
|
| 1369 |
+
transport.close()
|
| 1370 |
+
|
| 1371 |
+
def __enter__(self: T) -> T:
|
| 1372 |
+
if self._state != ClientState.UNOPENED:
|
| 1373 |
+
msg = {
|
| 1374 |
+
ClientState.OPENED: "Cannot open a client instance more than once.",
|
| 1375 |
+
ClientState.CLOSED: ("Cannot reopen a client instance, once it has been closed."),
|
| 1376 |
+
}[self._state]
|
| 1377 |
+
raise RuntimeError(msg)
|
| 1378 |
+
|
| 1379 |
+
self._state = ClientState.OPENED
|
| 1380 |
+
|
| 1381 |
+
self._transport.__enter__()
|
| 1382 |
+
for transport in self._mounts.values():
|
| 1383 |
+
if transport is not None:
|
| 1384 |
+
transport.__enter__()
|
| 1385 |
+
return self
|
| 1386 |
+
|
| 1387 |
+
def __exit__(
|
| 1388 |
+
self,
|
| 1389 |
+
exc_type: type[BaseException] | None = None,
|
| 1390 |
+
exc_value: BaseException | None = None,
|
| 1391 |
+
traceback: TracebackType | None = None,
|
| 1392 |
+
) -> None:
|
| 1393 |
+
self._state = ClientState.CLOSED
|
| 1394 |
+
|
| 1395 |
+
self._transport.__exit__(exc_type, exc_value, traceback)
|
| 1396 |
+
for transport in self._mounts.values():
|
| 1397 |
+
if transport is not None:
|
| 1398 |
+
transport.__exit__(exc_type, exc_value, traceback)
|
| 1399 |
+
|
| 1400 |
+
|
| 1401 |
+
class AsyncClient(BaseClient):
|
| 1402 |
+
"""
|
| 1403 |
+
An asynchronous HTTP client, with connection pooling, HTTP/2, redirects,
|
| 1404 |
+
cookie persistence, etc.
|
| 1405 |
+
|
| 1406 |
+
It can be shared between tasks.
|
| 1407 |
+
|
| 1408 |
+
Usage:
|
| 1409 |
+
|
| 1410 |
+
```python
|
| 1411 |
+
>>> async with httpx2.AsyncClient() as client:
|
| 1412 |
+
>>> response = await client.get('https://example.org')
|
| 1413 |
+
```
|
| 1414 |
+
|
| 1415 |
+
**Parameters:**
|
| 1416 |
+
|
| 1417 |
+
* **auth** - *(optional)* An authentication class to use when sending
|
| 1418 |
+
requests.
|
| 1419 |
+
* **params** - *(optional)* Query parameters to include in request URLs, as
|
| 1420 |
+
a string, dictionary, or sequence of two-tuples.
|
| 1421 |
+
* **headers** - *(optional)* Dictionary of HTTP headers to include when
|
| 1422 |
+
sending requests.
|
| 1423 |
+
* **cookies** - *(optional)* Dictionary of Cookie items to include when
|
| 1424 |
+
sending requests.
|
| 1425 |
+
* **verify** - *(optional)* Either `True` to use an SSL context with the
|
| 1426 |
+
default CA bundle, `False` to disable verification, or an instance of
|
| 1427 |
+
`ssl.SSLContext` to use a custom context.
|
| 1428 |
+
* **http2** - *(optional)* A boolean indicating if HTTP/2 support should be
|
| 1429 |
+
enabled. Defaults to `False`.
|
| 1430 |
+
* **proxy** - *(optional)* A proxy URL where all the traffic should be routed.
|
| 1431 |
+
* **mounts** - *(optional)* A dictionary mapping URL patterns to transports,
|
| 1432 |
+
used to route requests through specific transports based on the URL.
|
| 1433 |
+
* **timeout** - *(optional)* The timeout configuration to use when sending
|
| 1434 |
+
requests.
|
| 1435 |
+
* **limits** - *(optional)* The limits configuration to use.
|
| 1436 |
+
* **max_redirects** - *(optional)* The maximum number of redirect responses
|
| 1437 |
+
that should be followed.
|
| 1438 |
+
* **base_url** - *(optional)* A URL to use as the base when building
|
| 1439 |
+
request URLs.
|
| 1440 |
+
* **transport** - *(optional)* A transport class to use for sending requests
|
| 1441 |
+
over the network.
|
| 1442 |
+
* **trust_env** - *(optional)* Enables or disables usage of environment
|
| 1443 |
+
variables for configuration.
|
| 1444 |
+
* **default_encoding** - *(optional)* The default encoding to use for decoding
|
| 1445 |
+
response text, if no charset information is included in a response Content-Type
|
| 1446 |
+
header. Set to a callable for automatic character set detection. Default: "utf-8".
|
| 1447 |
+
"""
|
| 1448 |
+
|
| 1449 |
+
def __init__(
|
| 1450 |
+
self,
|
| 1451 |
+
*,
|
| 1452 |
+
auth: AuthTypes | None = None,
|
| 1453 |
+
params: QueryParamTypes | None = None,
|
| 1454 |
+
headers: HeaderTypes | None = None,
|
| 1455 |
+
cookies: CookieTypes | None = None,
|
| 1456 |
+
verify: ssl.SSLContext | str | bool = True,
|
| 1457 |
+
cert: CertTypes | None = None,
|
| 1458 |
+
http1: bool = True,
|
| 1459 |
+
http2: bool = False,
|
| 1460 |
+
proxy: ProxyTypes | None = None,
|
| 1461 |
+
mounts: None | (typing.Mapping[str, AsyncBaseTransport | None]) = None,
|
| 1462 |
+
timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
|
| 1463 |
+
follow_redirects: bool = False,
|
| 1464 |
+
limits: Limits = DEFAULT_LIMITS,
|
| 1465 |
+
max_redirects: int = DEFAULT_MAX_REDIRECTS,
|
| 1466 |
+
event_hooks: None | (typing.Mapping[str, list[EventHook]]) = None,
|
| 1467 |
+
base_url: URL | str = "",
|
| 1468 |
+
transport: AsyncBaseTransport | None = None,
|
| 1469 |
+
trust_env: bool = True,
|
| 1470 |
+
default_encoding: str | typing.Callable[[bytes], str | None] = "utf-8",
|
| 1471 |
+
) -> None:
|
| 1472 |
+
super().__init__(
|
| 1473 |
+
auth=auth,
|
| 1474 |
+
params=params,
|
| 1475 |
+
headers=headers,
|
| 1476 |
+
cookies=cookies,
|
| 1477 |
+
timeout=timeout,
|
| 1478 |
+
follow_redirects=follow_redirects,
|
| 1479 |
+
max_redirects=max_redirects,
|
| 1480 |
+
event_hooks=event_hooks,
|
| 1481 |
+
base_url=base_url,
|
| 1482 |
+
trust_env=trust_env,
|
| 1483 |
+
default_encoding=default_encoding,
|
| 1484 |
+
)
|
| 1485 |
+
|
| 1486 |
+
if http2:
|
| 1487 |
+
try:
|
| 1488 |
+
import h2 # noqa
|
| 1489 |
+
except ImportError: # pragma: no cover
|
| 1490 |
+
raise ImportError(
|
| 1491 |
+
"Using http2=True, but the 'h2' package is not installed. "
|
| 1492 |
+
"Make sure to install httpx using `pip install httpx[http2]`."
|
| 1493 |
+
) from None
|
| 1494 |
+
|
| 1495 |
+
allow_env_proxies = trust_env and transport is None
|
| 1496 |
+
proxy_map = self._get_proxy_map(proxy, allow_env_proxies)
|
| 1497 |
+
|
| 1498 |
+
self._transport = self._init_transport(
|
| 1499 |
+
verify=verify,
|
| 1500 |
+
cert=cert,
|
| 1501 |
+
trust_env=trust_env,
|
| 1502 |
+
http1=http1,
|
| 1503 |
+
http2=http2,
|
| 1504 |
+
limits=limits,
|
| 1505 |
+
transport=transport,
|
| 1506 |
+
)
|
| 1507 |
+
|
| 1508 |
+
self._mounts: dict[URLPattern, AsyncBaseTransport | None] = {
|
| 1509 |
+
URLPattern(key): None
|
| 1510 |
+
if proxy is None
|
| 1511 |
+
else self._init_proxy_transport(
|
| 1512 |
+
proxy,
|
| 1513 |
+
verify=verify,
|
| 1514 |
+
cert=cert,
|
| 1515 |
+
trust_env=trust_env,
|
| 1516 |
+
http1=http1,
|
| 1517 |
+
http2=http2,
|
| 1518 |
+
limits=limits,
|
| 1519 |
+
)
|
| 1520 |
+
for key, proxy in proxy_map.items()
|
| 1521 |
+
}
|
| 1522 |
+
if mounts is not None:
|
| 1523 |
+
self._mounts.update({URLPattern(key): transport for key, transport in mounts.items()})
|
| 1524 |
+
self._mounts = dict(sorted(self._mounts.items()))
|
| 1525 |
+
|
| 1526 |
+
def _init_transport(
|
| 1527 |
+
self,
|
| 1528 |
+
verify: ssl.SSLContext | str | bool = True,
|
| 1529 |
+
cert: CertTypes | None = None,
|
| 1530 |
+
trust_env: bool = True,
|
| 1531 |
+
http1: bool = True,
|
| 1532 |
+
http2: bool = False,
|
| 1533 |
+
limits: Limits = DEFAULT_LIMITS,
|
| 1534 |
+
transport: AsyncBaseTransport | None = None,
|
| 1535 |
+
) -> AsyncBaseTransport:
|
| 1536 |
+
if transport is not None:
|
| 1537 |
+
return transport
|
| 1538 |
+
|
| 1539 |
+
return AsyncHTTPTransport(
|
| 1540 |
+
verify=verify,
|
| 1541 |
+
cert=cert,
|
| 1542 |
+
trust_env=trust_env,
|
| 1543 |
+
http1=http1,
|
| 1544 |
+
http2=http2,
|
| 1545 |
+
limits=limits,
|
| 1546 |
+
)
|
| 1547 |
+
|
| 1548 |
+
def _init_proxy_transport(
|
| 1549 |
+
self,
|
| 1550 |
+
proxy: Proxy,
|
| 1551 |
+
verify: ssl.SSLContext | str | bool = True,
|
| 1552 |
+
cert: CertTypes | None = None,
|
| 1553 |
+
trust_env: bool = True,
|
| 1554 |
+
http1: bool = True,
|
| 1555 |
+
http2: bool = False,
|
| 1556 |
+
limits: Limits = DEFAULT_LIMITS,
|
| 1557 |
+
) -> AsyncBaseTransport:
|
| 1558 |
+
return AsyncHTTPTransport(
|
| 1559 |
+
verify=verify,
|
| 1560 |
+
cert=cert,
|
| 1561 |
+
trust_env=trust_env,
|
| 1562 |
+
http1=http1,
|
| 1563 |
+
http2=http2,
|
| 1564 |
+
limits=limits,
|
| 1565 |
+
proxy=proxy,
|
| 1566 |
+
)
|
| 1567 |
+
|
| 1568 |
+
def _transport_for_url(self, url: URL) -> AsyncBaseTransport:
|
| 1569 |
+
"""
|
| 1570 |
+
Returns the transport instance that should be used for a given URL.
|
| 1571 |
+
This will either be the standard connection pool, or a proxy.
|
| 1572 |
+
"""
|
| 1573 |
+
for pattern, transport in self._mounts.items():
|
| 1574 |
+
if pattern.matches(url):
|
| 1575 |
+
return self._transport if transport is None else transport
|
| 1576 |
+
|
| 1577 |
+
return self._transport
|
| 1578 |
+
|
| 1579 |
+
async def request(
|
| 1580 |
+
self,
|
| 1581 |
+
method: str,
|
| 1582 |
+
url: URL | str,
|
| 1583 |
+
*,
|
| 1584 |
+
content: RequestContent | None = None,
|
| 1585 |
+
data: RequestData | None = None,
|
| 1586 |
+
files: RequestFiles | None = None,
|
| 1587 |
+
json: typing.Any | None = None,
|
| 1588 |
+
params: QueryParamTypes | None = None,
|
| 1589 |
+
headers: HeaderTypes | None = None,
|
| 1590 |
+
cookies: CookieTypes | None = None,
|
| 1591 |
+
auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
|
| 1592 |
+
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1593 |
+
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1594 |
+
extensions: RequestExtensions | None = None,
|
| 1595 |
+
) -> Response:
|
| 1596 |
+
"""
|
| 1597 |
+
Build and send a request.
|
| 1598 |
+
|
| 1599 |
+
Equivalent to:
|
| 1600 |
+
|
| 1601 |
+
```python
|
| 1602 |
+
request = client.build_request(...)
|
| 1603 |
+
response = await client.send(request, ...)
|
| 1604 |
+
```
|
| 1605 |
+
|
| 1606 |
+
See `AsyncClient.build_request()`, `AsyncClient.send()`
|
| 1607 |
+
and [Merging of configuration][0] for how the various parameters
|
| 1608 |
+
are merged with client-level configuration.
|
| 1609 |
+
|
| 1610 |
+
[0]: advanced/clients.md#merging-of-configuration
|
| 1611 |
+
"""
|
| 1612 |
+
|
| 1613 |
+
if cookies is not None: # pragma: no cover
|
| 1614 |
+
message = (
|
| 1615 |
+
"Setting per-request cookies=<...> is being deprecated, because "
|
| 1616 |
+
"the expected behaviour on cookie persistence is ambiguous. Set "
|
| 1617 |
+
"cookies directly on the client instance instead."
|
| 1618 |
+
)
|
| 1619 |
+
warnings.warn(message, DeprecationWarning, stacklevel=2)
|
| 1620 |
+
|
| 1621 |
+
request = self.build_request(
|
| 1622 |
+
method=method,
|
| 1623 |
+
url=url,
|
| 1624 |
+
content=content,
|
| 1625 |
+
data=data,
|
| 1626 |
+
files=files,
|
| 1627 |
+
json=json,
|
| 1628 |
+
params=params,
|
| 1629 |
+
headers=headers,
|
| 1630 |
+
cookies=cookies,
|
| 1631 |
+
timeout=timeout,
|
| 1632 |
+
extensions=extensions,
|
| 1633 |
+
)
|
| 1634 |
+
return await self.send(request, auth=auth, follow_redirects=follow_redirects)
|
| 1635 |
+
|
| 1636 |
+
@asynccontextmanager
|
| 1637 |
+
async def stream(
|
| 1638 |
+
self,
|
| 1639 |
+
method: str,
|
| 1640 |
+
url: URL | str,
|
| 1641 |
+
*,
|
| 1642 |
+
content: RequestContent | None = None,
|
| 1643 |
+
data: RequestData | None = None,
|
| 1644 |
+
files: RequestFiles | None = None,
|
| 1645 |
+
json: typing.Any | None = None,
|
| 1646 |
+
params: QueryParamTypes | None = None,
|
| 1647 |
+
headers: HeaderTypes | None = None,
|
| 1648 |
+
cookies: CookieTypes | None = None,
|
| 1649 |
+
auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
|
| 1650 |
+
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1651 |
+
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1652 |
+
extensions: RequestExtensions | None = None,
|
| 1653 |
+
) -> AsyncGenerator[Response]:
|
| 1654 |
+
"""
|
| 1655 |
+
Alternative to `httpx2.request()` that streams the response body
|
| 1656 |
+
instead of loading it into memory at once.
|
| 1657 |
+
|
| 1658 |
+
**Parameters**: See `httpx2.request`.
|
| 1659 |
+
|
| 1660 |
+
See also: [Streaming Responses][0]
|
| 1661 |
+
|
| 1662 |
+
[0]: quickstart.md#streaming-responses
|
| 1663 |
+
"""
|
| 1664 |
+
request = self.build_request(
|
| 1665 |
+
method=method,
|
| 1666 |
+
url=url,
|
| 1667 |
+
content=content,
|
| 1668 |
+
data=data,
|
| 1669 |
+
files=files,
|
| 1670 |
+
json=json,
|
| 1671 |
+
params=params,
|
| 1672 |
+
headers=headers,
|
| 1673 |
+
cookies=cookies,
|
| 1674 |
+
timeout=timeout,
|
| 1675 |
+
extensions=extensions,
|
| 1676 |
+
)
|
| 1677 |
+
response = await self.send(
|
| 1678 |
+
request=request,
|
| 1679 |
+
auth=auth,
|
| 1680 |
+
follow_redirects=follow_redirects,
|
| 1681 |
+
stream=True,
|
| 1682 |
+
)
|
| 1683 |
+
try:
|
| 1684 |
+
yield response
|
| 1685 |
+
finally:
|
| 1686 |
+
await response.aclose()
|
| 1687 |
+
|
| 1688 |
+
@asynccontextmanager
|
| 1689 |
+
async def sse(
|
| 1690 |
+
self,
|
| 1691 |
+
url: URL | str,
|
| 1692 |
+
*,
|
| 1693 |
+
method: str = "GET",
|
| 1694 |
+
content: RequestContent | None = None,
|
| 1695 |
+
data: RequestData | None = None,
|
| 1696 |
+
files: RequestFiles | None = None,
|
| 1697 |
+
json: typing.Any | None = None,
|
| 1698 |
+
params: QueryParamTypes | None = None,
|
| 1699 |
+
headers: HeaderTypes | None = None,
|
| 1700 |
+
cookies: CookieTypes | None = None,
|
| 1701 |
+
auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
|
| 1702 |
+
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1703 |
+
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1704 |
+
extensions: RequestExtensions | None = None,
|
| 1705 |
+
max_event_size: int | None = DEFAULT_MAX_EVENT_SIZE_BYTES,
|
| 1706 |
+
) -> AsyncGenerator[EventSource]:
|
| 1707 |
+
"""
|
| 1708 |
+
Connect to a server-sent events endpoint and yield an `EventSource`.
|
| 1709 |
+
|
| 1710 |
+
Iterating the `EventSource` yields `ServerSentEvent` instances.
|
| 1711 |
+
|
| 1712 |
+
**Parameters**: See `httpx2.request`.
|
| 1713 |
+
"""
|
| 1714 |
+
async with self.stream(
|
| 1715 |
+
method,
|
| 1716 |
+
url,
|
| 1717 |
+
content=content,
|
| 1718 |
+
data=data,
|
| 1719 |
+
files=files,
|
| 1720 |
+
json=json,
|
| 1721 |
+
params=params,
|
| 1722 |
+
headers={"Accept": "text/event-stream", "Cache-Control": "no-store"} | Headers(headers),
|
| 1723 |
+
cookies=cookies,
|
| 1724 |
+
auth=auth,
|
| 1725 |
+
follow_redirects=follow_redirects,
|
| 1726 |
+
timeout=timeout,
|
| 1727 |
+
extensions=extensions,
|
| 1728 |
+
) as response:
|
| 1729 |
+
yield EventSource(response, max_event_size=max_event_size)
|
| 1730 |
+
|
| 1731 |
+
@asynccontextmanager
|
| 1732 |
+
async def websocket(
|
| 1733 |
+
self,
|
| 1734 |
+
url: URL | str,
|
| 1735 |
+
*,
|
| 1736 |
+
max_message_size_bytes: int = DEFAULT_MAX_MESSAGE_SIZE_BYTES,
|
| 1737 |
+
queue_size: int = DEFAULT_QUEUE_SIZE,
|
| 1738 |
+
keepalive_ping_interval_seconds: float | None = DEFAULT_KEEPALIVE_PING_INTERVAL_SECONDS,
|
| 1739 |
+
keepalive_ping_timeout_seconds: float | None = DEFAULT_KEEPALIVE_PING_TIMEOUT_SECONDS,
|
| 1740 |
+
subprotocols: list[str] | None = None,
|
| 1741 |
+
params: QueryParamTypes | None = None,
|
| 1742 |
+
headers: HeaderTypes | None = None,
|
| 1743 |
+
cookies: CookieTypes | None = None,
|
| 1744 |
+
auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
|
| 1745 |
+
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1746 |
+
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1747 |
+
extensions: RequestExtensions | None = None,
|
| 1748 |
+
) -> AsyncGenerator[AsyncWebSocketSession]:
|
| 1749 |
+
"""
|
| 1750 |
+
Open a WebSocket session, using this client's configuration.
|
| 1751 |
+
|
| 1752 |
+
The session is closed automatically when exiting the context manager.
|
| 1753 |
+
|
| 1754 |
+
```python
|
| 1755 |
+
async with httpx2.AsyncClient() as client:
|
| 1756 |
+
async with client.websocket("ws://localhost:8000/ws") as ws:
|
| 1757 |
+
await ws.send_text("Hello!")
|
| 1758 |
+
message = await ws.receive_text()
|
| 1759 |
+
```
|
| 1760 |
+
"""
|
| 1761 |
+
try:
|
| 1762 |
+
from .websockets._api import aconnect_ws
|
| 1763 |
+
except ImportError: # pragma: no cover
|
| 1764 |
+
raise ImportError(
|
| 1765 |
+
"WebSocket support requires the `wsproto` package. Install it with `pip install httpx2[ws]`."
|
| 1766 |
+
)
|
| 1767 |
+
|
| 1768 |
+
async with aconnect_ws(
|
| 1769 |
+
str(url),
|
| 1770 |
+
self,
|
| 1771 |
+
max_message_size_bytes=max_message_size_bytes,
|
| 1772 |
+
queue_size=queue_size,
|
| 1773 |
+
keepalive_ping_interval_seconds=keepalive_ping_interval_seconds,
|
| 1774 |
+
keepalive_ping_timeout_seconds=keepalive_ping_timeout_seconds,
|
| 1775 |
+
subprotocols=subprotocols,
|
| 1776 |
+
params=params,
|
| 1777 |
+
headers=headers,
|
| 1778 |
+
cookies=cookies,
|
| 1779 |
+
auth=auth,
|
| 1780 |
+
follow_redirects=follow_redirects,
|
| 1781 |
+
timeout=timeout,
|
| 1782 |
+
extensions=extensions,
|
| 1783 |
+
) as session:
|
| 1784 |
+
yield session
|
| 1785 |
+
|
| 1786 |
+
async def send(
|
| 1787 |
+
self,
|
| 1788 |
+
request: Request,
|
| 1789 |
+
*,
|
| 1790 |
+
stream: bool = False,
|
| 1791 |
+
auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
|
| 1792 |
+
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1793 |
+
) -> Response:
|
| 1794 |
+
"""
|
| 1795 |
+
Send a request.
|
| 1796 |
+
|
| 1797 |
+
The request is sent as-is, unmodified.
|
| 1798 |
+
|
| 1799 |
+
Typically you'll want to build one with `AsyncClient.build_request()`
|
| 1800 |
+
so that any client-level configuration is merged into the request,
|
| 1801 |
+
but passing an explicit `httpx2.Request()` is supported as well.
|
| 1802 |
+
|
| 1803 |
+
See also: [Request instances][0]
|
| 1804 |
+
|
| 1805 |
+
[0]: advanced/clients.md#request-instances
|
| 1806 |
+
"""
|
| 1807 |
+
if self._state == ClientState.CLOSED:
|
| 1808 |
+
raise RuntimeError("Cannot send a request, as the client has been closed.")
|
| 1809 |
+
|
| 1810 |
+
self._state = ClientState.OPENED
|
| 1811 |
+
follow_redirects = self.follow_redirects if isinstance(follow_redirects, UseClientDefault) else follow_redirects
|
| 1812 |
+
|
| 1813 |
+
self._set_timeout(request)
|
| 1814 |
+
|
| 1815 |
+
auth = self._build_request_auth(request, auth)
|
| 1816 |
+
|
| 1817 |
+
response = await self._send_handling_auth(
|
| 1818 |
+
request,
|
| 1819 |
+
auth=auth,
|
| 1820 |
+
follow_redirects=follow_redirects,
|
| 1821 |
+
history=[],
|
| 1822 |
+
)
|
| 1823 |
+
try:
|
| 1824 |
+
if not stream:
|
| 1825 |
+
await response.aread()
|
| 1826 |
+
|
| 1827 |
+
return response
|
| 1828 |
+
|
| 1829 |
+
except BaseException as exc:
|
| 1830 |
+
await response.aclose()
|
| 1831 |
+
raise exc
|
| 1832 |
+
|
| 1833 |
+
async def _send_handling_auth(
|
| 1834 |
+
self,
|
| 1835 |
+
request: Request,
|
| 1836 |
+
auth: Auth,
|
| 1837 |
+
follow_redirects: bool,
|
| 1838 |
+
history: list[Response],
|
| 1839 |
+
) -> Response:
|
| 1840 |
+
auth_flow = auth.async_auth_flow(request)
|
| 1841 |
+
try:
|
| 1842 |
+
request = await auth_flow.__anext__()
|
| 1843 |
+
|
| 1844 |
+
while True:
|
| 1845 |
+
response = await self._send_handling_redirects(
|
| 1846 |
+
request,
|
| 1847 |
+
follow_redirects=follow_redirects,
|
| 1848 |
+
history=history,
|
| 1849 |
+
)
|
| 1850 |
+
try:
|
| 1851 |
+
try:
|
| 1852 |
+
next_request = await auth_flow.asend(response)
|
| 1853 |
+
except StopAsyncIteration:
|
| 1854 |
+
return response
|
| 1855 |
+
|
| 1856 |
+
response.history = list(history)
|
| 1857 |
+
await response.aread()
|
| 1858 |
+
request = next_request
|
| 1859 |
+
history.append(response)
|
| 1860 |
+
|
| 1861 |
+
except BaseException as exc:
|
| 1862 |
+
await response.aclose()
|
| 1863 |
+
raise exc
|
| 1864 |
+
finally:
|
| 1865 |
+
await auth_flow.aclose()
|
| 1866 |
+
|
| 1867 |
+
async def _send_handling_redirects(
|
| 1868 |
+
self,
|
| 1869 |
+
request: Request,
|
| 1870 |
+
follow_redirects: bool,
|
| 1871 |
+
history: list[Response],
|
| 1872 |
+
) -> Response:
|
| 1873 |
+
while True:
|
| 1874 |
+
if len(history) > self.max_redirects:
|
| 1875 |
+
raise TooManyRedirects("Exceeded maximum allowed redirects.", request=request)
|
| 1876 |
+
|
| 1877 |
+
for hook in self._event_hooks["request"]:
|
| 1878 |
+
await hook(request)
|
| 1879 |
+
|
| 1880 |
+
response = await self._send_single_request(request)
|
| 1881 |
+
try:
|
| 1882 |
+
for hook in self._event_hooks["response"]:
|
| 1883 |
+
await hook(response)
|
| 1884 |
+
|
| 1885 |
+
response.history = list(history)
|
| 1886 |
+
|
| 1887 |
+
if not response.has_redirect_location:
|
| 1888 |
+
return response
|
| 1889 |
+
|
| 1890 |
+
request = self._build_redirect_request(request, response)
|
| 1891 |
+
history = history + [response]
|
| 1892 |
+
|
| 1893 |
+
if follow_redirects:
|
| 1894 |
+
await response.aread()
|
| 1895 |
+
else:
|
| 1896 |
+
response.next_request = request
|
| 1897 |
+
return response
|
| 1898 |
+
|
| 1899 |
+
except BaseException as exc:
|
| 1900 |
+
await response.aclose()
|
| 1901 |
+
raise exc
|
| 1902 |
+
|
| 1903 |
+
async def _send_single_request(self, request: Request) -> Response:
|
| 1904 |
+
"""
|
| 1905 |
+
Sends a single request, without handling any redirections.
|
| 1906 |
+
"""
|
| 1907 |
+
transport = self._transport_for_url(request.url)
|
| 1908 |
+
start = time.perf_counter()
|
| 1909 |
+
|
| 1910 |
+
if not isinstance(request.stream, AsyncByteStream):
|
| 1911 |
+
raise RuntimeError("Attempted to send a sync request with an AsyncClient instance.")
|
| 1912 |
+
|
| 1913 |
+
with request_context(request=request):
|
| 1914 |
+
response = await transport.handle_async_request(request)
|
| 1915 |
+
|
| 1916 |
+
assert isinstance(response.stream, AsyncByteStream)
|
| 1917 |
+
response.request = request
|
| 1918 |
+
response.stream = BoundAsyncStream(response.stream, start=start)
|
| 1919 |
+
self.cookies.extract_cookies(response)
|
| 1920 |
+
response.default_encoding = self._default_encoding
|
| 1921 |
+
|
| 1922 |
+
logger.info(
|
| 1923 |
+
'HTTP Request: %s %s "%s %d %s"',
|
| 1924 |
+
request.method,
|
| 1925 |
+
request.url,
|
| 1926 |
+
response.http_version,
|
| 1927 |
+
response.status_code,
|
| 1928 |
+
response.reason_phrase,
|
| 1929 |
+
)
|
| 1930 |
+
|
| 1931 |
+
return response
|
| 1932 |
+
|
| 1933 |
+
async def get(
|
| 1934 |
+
self,
|
| 1935 |
+
url: URL | str,
|
| 1936 |
+
*,
|
| 1937 |
+
params: QueryParamTypes | None = None,
|
| 1938 |
+
headers: HeaderTypes | None = None,
|
| 1939 |
+
cookies: CookieTypes | None = None,
|
| 1940 |
+
auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
|
| 1941 |
+
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1942 |
+
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1943 |
+
extensions: RequestExtensions | None = None,
|
| 1944 |
+
) -> Response:
|
| 1945 |
+
"""
|
| 1946 |
+
Send a `GET` request.
|
| 1947 |
+
|
| 1948 |
+
**Parameters**: See `httpx2.request`.
|
| 1949 |
+
"""
|
| 1950 |
+
return await self.request(
|
| 1951 |
+
"GET",
|
| 1952 |
+
url,
|
| 1953 |
+
params=params,
|
| 1954 |
+
headers=headers,
|
| 1955 |
+
cookies=cookies,
|
| 1956 |
+
auth=auth,
|
| 1957 |
+
follow_redirects=follow_redirects,
|
| 1958 |
+
timeout=timeout,
|
| 1959 |
+
extensions=extensions,
|
| 1960 |
+
)
|
| 1961 |
+
|
| 1962 |
+
async def options(
|
| 1963 |
+
self,
|
| 1964 |
+
url: URL | str,
|
| 1965 |
+
*,
|
| 1966 |
+
params: QueryParamTypes | None = None,
|
| 1967 |
+
headers: HeaderTypes | None = None,
|
| 1968 |
+
cookies: CookieTypes | None = None,
|
| 1969 |
+
auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1970 |
+
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1971 |
+
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1972 |
+
extensions: RequestExtensions | None = None,
|
| 1973 |
+
) -> Response:
|
| 1974 |
+
"""
|
| 1975 |
+
Send an `OPTIONS` request.
|
| 1976 |
+
|
| 1977 |
+
**Parameters**: See `httpx2.request`.
|
| 1978 |
+
"""
|
| 1979 |
+
return await self.request(
|
| 1980 |
+
"OPTIONS",
|
| 1981 |
+
url,
|
| 1982 |
+
params=params,
|
| 1983 |
+
headers=headers,
|
| 1984 |
+
cookies=cookies,
|
| 1985 |
+
auth=auth,
|
| 1986 |
+
follow_redirects=follow_redirects,
|
| 1987 |
+
timeout=timeout,
|
| 1988 |
+
extensions=extensions,
|
| 1989 |
+
)
|
| 1990 |
+
|
| 1991 |
+
async def head(
|
| 1992 |
+
self,
|
| 1993 |
+
url: URL | str,
|
| 1994 |
+
*,
|
| 1995 |
+
params: QueryParamTypes | None = None,
|
| 1996 |
+
headers: HeaderTypes | None = None,
|
| 1997 |
+
cookies: CookieTypes | None = None,
|
| 1998 |
+
auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1999 |
+
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 2000 |
+
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 2001 |
+
extensions: RequestExtensions | None = None,
|
| 2002 |
+
) -> Response:
|
| 2003 |
+
"""
|
| 2004 |
+
Send a `HEAD` request.
|
| 2005 |
+
|
| 2006 |
+
**Parameters**: See `httpx2.request`.
|
| 2007 |
+
"""
|
| 2008 |
+
return await self.request(
|
| 2009 |
+
"HEAD",
|
| 2010 |
+
url,
|
| 2011 |
+
params=params,
|
| 2012 |
+
headers=headers,
|
| 2013 |
+
cookies=cookies,
|
| 2014 |
+
auth=auth,
|
| 2015 |
+
follow_redirects=follow_redirects,
|
| 2016 |
+
timeout=timeout,
|
| 2017 |
+
extensions=extensions,
|
| 2018 |
+
)
|
| 2019 |
+
|
| 2020 |
+
async def post(
|
| 2021 |
+
self,
|
| 2022 |
+
url: URL | str,
|
| 2023 |
+
*,
|
| 2024 |
+
content: RequestContent | None = None,
|
| 2025 |
+
data: RequestData | None = None,
|
| 2026 |
+
files: RequestFiles | None = None,
|
| 2027 |
+
json: typing.Any | None = None,
|
| 2028 |
+
params: QueryParamTypes | None = None,
|
| 2029 |
+
headers: HeaderTypes | None = None,
|
| 2030 |
+
cookies: CookieTypes | None = None,
|
| 2031 |
+
auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 2032 |
+
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 2033 |
+
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 2034 |
+
extensions: RequestExtensions | None = None,
|
| 2035 |
+
) -> Response:
|
| 2036 |
+
"""
|
| 2037 |
+
Send a `POST` request.
|
| 2038 |
+
|
| 2039 |
+
**Parameters**: See `httpx2.request`.
|
| 2040 |
+
"""
|
| 2041 |
+
return await self.request(
|
| 2042 |
+
"POST",
|
| 2043 |
+
url,
|
| 2044 |
+
content=content,
|
| 2045 |
+
data=data,
|
| 2046 |
+
files=files,
|
| 2047 |
+
json=json,
|
| 2048 |
+
params=params,
|
| 2049 |
+
headers=headers,
|
| 2050 |
+
cookies=cookies,
|
| 2051 |
+
auth=auth,
|
| 2052 |
+
follow_redirects=follow_redirects,
|
| 2053 |
+
timeout=timeout,
|
| 2054 |
+
extensions=extensions,
|
| 2055 |
+
)
|
| 2056 |
+
|
| 2057 |
+
async def put(
|
| 2058 |
+
self,
|
| 2059 |
+
url: URL | str,
|
| 2060 |
+
*,
|
| 2061 |
+
content: RequestContent | None = None,
|
| 2062 |
+
data: RequestData | None = None,
|
| 2063 |
+
files: RequestFiles | None = None,
|
| 2064 |
+
json: typing.Any | None = None,
|
| 2065 |
+
params: QueryParamTypes | None = None,
|
| 2066 |
+
headers: HeaderTypes | None = None,
|
| 2067 |
+
cookies: CookieTypes | None = None,
|
| 2068 |
+
auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 2069 |
+
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 2070 |
+
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 2071 |
+
extensions: RequestExtensions | None = None,
|
| 2072 |
+
) -> Response:
|
| 2073 |
+
"""
|
| 2074 |
+
Send a `PUT` request.
|
| 2075 |
+
|
| 2076 |
+
**Parameters**: See `httpx2.request`.
|
| 2077 |
+
"""
|
| 2078 |
+
return await self.request(
|
| 2079 |
+
"PUT",
|
| 2080 |
+
url,
|
| 2081 |
+
content=content,
|
| 2082 |
+
data=data,
|
| 2083 |
+
files=files,
|
| 2084 |
+
json=json,
|
| 2085 |
+
params=params,
|
| 2086 |
+
headers=headers,
|
| 2087 |
+
cookies=cookies,
|
| 2088 |
+
auth=auth,
|
| 2089 |
+
follow_redirects=follow_redirects,
|
| 2090 |
+
timeout=timeout,
|
| 2091 |
+
extensions=extensions,
|
| 2092 |
+
)
|
| 2093 |
+
|
| 2094 |
+
async def patch(
|
| 2095 |
+
self,
|
| 2096 |
+
url: URL | str,
|
| 2097 |
+
*,
|
| 2098 |
+
content: RequestContent | None = None,
|
| 2099 |
+
data: RequestData | None = None,
|
| 2100 |
+
files: RequestFiles | None = None,
|
| 2101 |
+
json: typing.Any | None = None,
|
| 2102 |
+
params: QueryParamTypes | None = None,
|
| 2103 |
+
headers: HeaderTypes | None = None,
|
| 2104 |
+
cookies: CookieTypes | None = None,
|
| 2105 |
+
auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 2106 |
+
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 2107 |
+
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 2108 |
+
extensions: RequestExtensions | None = None,
|
| 2109 |
+
) -> Response:
|
| 2110 |
+
"""
|
| 2111 |
+
Send a `PATCH` request.
|
| 2112 |
+
|
| 2113 |
+
**Parameters**: See `httpx2.request`.
|
| 2114 |
+
"""
|
| 2115 |
+
return await self.request(
|
| 2116 |
+
"PATCH",
|
| 2117 |
+
url,
|
| 2118 |
+
content=content,
|
| 2119 |
+
data=data,
|
| 2120 |
+
files=files,
|
| 2121 |
+
json=json,
|
| 2122 |
+
params=params,
|
| 2123 |
+
headers=headers,
|
| 2124 |
+
cookies=cookies,
|
| 2125 |
+
auth=auth,
|
| 2126 |
+
follow_redirects=follow_redirects,
|
| 2127 |
+
timeout=timeout,
|
| 2128 |
+
extensions=extensions,
|
| 2129 |
+
)
|
| 2130 |
+
|
| 2131 |
+
async def delete(
|
| 2132 |
+
self,
|
| 2133 |
+
url: URL | str,
|
| 2134 |
+
*,
|
| 2135 |
+
params: QueryParamTypes | None = None,
|
| 2136 |
+
headers: HeaderTypes | None = None,
|
| 2137 |
+
cookies: CookieTypes | None = None,
|
| 2138 |
+
auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 2139 |
+
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 2140 |
+
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 2141 |
+
extensions: RequestExtensions | None = None,
|
| 2142 |
+
) -> Response:
|
| 2143 |
+
"""
|
| 2144 |
+
Send a `DELETE` request.
|
| 2145 |
+
|
| 2146 |
+
**Parameters**: See `httpx2.request`.
|
| 2147 |
+
"""
|
| 2148 |
+
return await self.request(
|
| 2149 |
+
"DELETE",
|
| 2150 |
+
url,
|
| 2151 |
+
params=params,
|
| 2152 |
+
headers=headers,
|
| 2153 |
+
cookies=cookies,
|
| 2154 |
+
auth=auth,
|
| 2155 |
+
follow_redirects=follow_redirects,
|
| 2156 |
+
timeout=timeout,
|
| 2157 |
+
extensions=extensions,
|
| 2158 |
+
)
|
| 2159 |
+
|
| 2160 |
+
async def query(
|
| 2161 |
+
self,
|
| 2162 |
+
url: URL | str,
|
| 2163 |
+
*,
|
| 2164 |
+
content: RequestContent | None = None,
|
| 2165 |
+
data: RequestData | None = None,
|
| 2166 |
+
files: RequestFiles | None = None,
|
| 2167 |
+
json: typing.Any | None = None,
|
| 2168 |
+
params: QueryParamTypes | None = None,
|
| 2169 |
+
headers: HeaderTypes | None = None,
|
| 2170 |
+
cookies: CookieTypes | None = None,
|
| 2171 |
+
auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 2172 |
+
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 2173 |
+
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 2174 |
+
extensions: RequestExtensions | None = None,
|
| 2175 |
+
) -> Response:
|
| 2176 |
+
"""
|
| 2177 |
+
Send a `QUERY` request.
|
| 2178 |
+
|
| 2179 |
+
**Parameters**: See `httpx2.request`.
|
| 2180 |
+
"""
|
| 2181 |
+
return await self.request(
|
| 2182 |
+
"QUERY",
|
| 2183 |
+
url,
|
| 2184 |
+
content=content,
|
| 2185 |
+
data=data,
|
| 2186 |
+
files=files,
|
| 2187 |
+
json=json,
|
| 2188 |
+
params=params,
|
| 2189 |
+
headers=headers,
|
| 2190 |
+
cookies=cookies,
|
| 2191 |
+
auth=auth,
|
| 2192 |
+
follow_redirects=follow_redirects,
|
| 2193 |
+
timeout=timeout,
|
| 2194 |
+
extensions=extensions,
|
| 2195 |
+
)
|
| 2196 |
+
|
| 2197 |
+
async def aclose(self) -> None:
|
| 2198 |
+
"""
|
| 2199 |
+
Close transport and proxies.
|
| 2200 |
+
"""
|
| 2201 |
+
if self._state != ClientState.CLOSED:
|
| 2202 |
+
self._state = ClientState.CLOSED
|
| 2203 |
+
|
| 2204 |
+
await self._transport.aclose()
|
| 2205 |
+
for proxy in self._mounts.values():
|
| 2206 |
+
if proxy is not None:
|
| 2207 |
+
await proxy.aclose()
|
| 2208 |
+
|
| 2209 |
+
async def __aenter__(self: U) -> U:
|
| 2210 |
+
if self._state != ClientState.UNOPENED:
|
| 2211 |
+
msg = {
|
| 2212 |
+
ClientState.OPENED: "Cannot open a client instance more than once.",
|
| 2213 |
+
ClientState.CLOSED: ("Cannot reopen a client instance, once it has been closed."),
|
| 2214 |
+
}[self._state]
|
| 2215 |
+
raise RuntimeError(msg)
|
| 2216 |
+
|
| 2217 |
+
self._state = ClientState.OPENED
|
| 2218 |
+
|
| 2219 |
+
await self._transport.__aenter__()
|
| 2220 |
+
for proxy in self._mounts.values():
|
| 2221 |
+
if proxy is not None:
|
| 2222 |
+
await proxy.__aenter__()
|
| 2223 |
+
return self
|
| 2224 |
+
|
| 2225 |
+
async def __aexit__(
|
| 2226 |
+
self,
|
| 2227 |
+
exc_type: type[BaseException] | None = None,
|
| 2228 |
+
exc_value: BaseException | None = None,
|
| 2229 |
+
traceback: TracebackType | None = None,
|
| 2230 |
+
) -> None:
|
| 2231 |
+
self._state = ClientState.CLOSED
|
| 2232 |
+
|
| 2233 |
+
await self._transport.__aexit__(exc_type, exc_value, traceback)
|
| 2234 |
+
for proxy in self._mounts.values():
|
| 2235 |
+
if proxy is not None:
|
| 2236 |
+
await proxy.__aexit__(exc_type, exc_value, traceback)
|
.venv/lib/python3.12/site-packages/httpx2/_config.py
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import dataclasses
|
| 4 |
+
import os
|
| 5 |
+
import typing
|
| 6 |
+
|
| 7 |
+
from ._models import Headers
|
| 8 |
+
from ._types import CertTypes, HeaderTypes, TimeoutTypes
|
| 9 |
+
from ._urls import URL
|
| 10 |
+
|
| 11 |
+
if typing.TYPE_CHECKING:
|
| 12 |
+
import ssl # pragma: no cover
|
| 13 |
+
|
| 14 |
+
__all__ = ["Limits", "Proxy", "Timeout", "create_ssl_context"]
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class UnsetType:
|
| 18 |
+
pass # pragma: no cover
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
UNSET = UnsetType()
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def create_ssl_context(
|
| 25 |
+
verify: ssl.SSLContext | str | bool = True,
|
| 26 |
+
cert: CertTypes | None = None,
|
| 27 |
+
trust_env: bool = True,
|
| 28 |
+
) -> ssl.SSLContext:
|
| 29 |
+
import ssl
|
| 30 |
+
import warnings
|
| 31 |
+
|
| 32 |
+
import httpcore2
|
| 33 |
+
|
| 34 |
+
if verify is True:
|
| 35 |
+
ctx = httpcore2.default_ssl_context(_trust_env=trust_env)
|
| 36 |
+
elif verify is False:
|
| 37 |
+
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
| 38 |
+
ctx.check_hostname = False
|
| 39 |
+
ctx.verify_mode = ssl.CERT_NONE
|
| 40 |
+
elif isinstance(verify, str):
|
| 41 |
+
if cert:
|
| 42 |
+
raise TypeError(
|
| 43 |
+
"`verify=<str>` cannot be combined with `cert=...`. "
|
| 44 |
+
"Build an `ssl.SSLContext` and pass it as `verify=<ctx>`, "
|
| 45 |
+
"using `.load_cert_chain()` to configure the certificate chain."
|
| 46 |
+
)
|
| 47 |
+
message = (
|
| 48 |
+
"`verify=<str>` is deprecated. "
|
| 49 |
+
"Use `verify=ssl.create_default_context(cafile=...)` "
|
| 50 |
+
"or `verify=ssl.create_default_context(capath=...)` instead."
|
| 51 |
+
)
|
| 52 |
+
warnings.warn(message, DeprecationWarning)
|
| 53 |
+
if os.path.isdir(verify): # pragma: no cover
|
| 54 |
+
return ssl.create_default_context(capath=verify)
|
| 55 |
+
return ssl.create_default_context(cafile=verify)
|
| 56 |
+
else:
|
| 57 |
+
ctx = verify
|
| 58 |
+
|
| 59 |
+
if cert: # pragma: no cover
|
| 60 |
+
message = (
|
| 61 |
+
"`cert=...` is deprecated. Use `verify=<ssl_context>` instead,"
|
| 62 |
+
"with `.load_cert_chain()` to configure the certificate chain."
|
| 63 |
+
)
|
| 64 |
+
warnings.warn(message, DeprecationWarning)
|
| 65 |
+
if isinstance(cert, str):
|
| 66 |
+
ctx.load_cert_chain(cert)
|
| 67 |
+
else:
|
| 68 |
+
ctx.load_cert_chain(*cert)
|
| 69 |
+
|
| 70 |
+
return ctx
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
@dataclasses.dataclass(init=False, repr=False)
|
| 74 |
+
class Timeout:
|
| 75 |
+
"""
|
| 76 |
+
Timeout configuration.
|
| 77 |
+
|
| 78 |
+
**Usage**:
|
| 79 |
+
|
| 80 |
+
Timeout(None) # No timeouts.
|
| 81 |
+
Timeout(5.0) # 5s timeout on all operations.
|
| 82 |
+
Timeout(None, connect=5.0) # 5s timeout on connect, no other timeouts.
|
| 83 |
+
Timeout(5.0, connect=10.0) # 10s timeout on connect. 5s timeout elsewhere.
|
| 84 |
+
Timeout(5.0, pool=None) # No timeout on acquiring connection from pool.
|
| 85 |
+
# 5s timeout elsewhere.
|
| 86 |
+
"""
|
| 87 |
+
|
| 88 |
+
connect: float | None
|
| 89 |
+
read: float | None
|
| 90 |
+
write: float | None
|
| 91 |
+
pool: float | None
|
| 92 |
+
|
| 93 |
+
def __init__(
|
| 94 |
+
self,
|
| 95 |
+
timeout: TimeoutTypes | UnsetType = UNSET,
|
| 96 |
+
*,
|
| 97 |
+
connect: None | float | UnsetType = UNSET,
|
| 98 |
+
read: None | float | UnsetType = UNSET,
|
| 99 |
+
write: None | float | UnsetType = UNSET,
|
| 100 |
+
pool: None | float | UnsetType = UNSET,
|
| 101 |
+
) -> None:
|
| 102 |
+
if isinstance(timeout, Timeout):
|
| 103 |
+
# Passed as a single explicit Timeout.
|
| 104 |
+
assert connect is UNSET
|
| 105 |
+
assert read is UNSET
|
| 106 |
+
assert write is UNSET
|
| 107 |
+
assert pool is UNSET
|
| 108 |
+
self.connect = timeout.connect
|
| 109 |
+
self.read = timeout.read
|
| 110 |
+
self.write = timeout.write
|
| 111 |
+
self.pool = timeout.pool
|
| 112 |
+
elif isinstance(timeout, tuple):
|
| 113 |
+
# Passed as a tuple.
|
| 114 |
+
self.connect = timeout[0]
|
| 115 |
+
self.read = timeout[1]
|
| 116 |
+
self.write = None if len(timeout) < 3 else timeout[2]
|
| 117 |
+
self.pool = None if len(timeout) < 4 else timeout[3]
|
| 118 |
+
elif not (
|
| 119 |
+
isinstance(connect, UnsetType)
|
| 120 |
+
or isinstance(read, UnsetType)
|
| 121 |
+
or isinstance(write, UnsetType)
|
| 122 |
+
or isinstance(pool, UnsetType)
|
| 123 |
+
):
|
| 124 |
+
self.connect = connect
|
| 125 |
+
self.read = read
|
| 126 |
+
self.write = write
|
| 127 |
+
self.pool = pool
|
| 128 |
+
else:
|
| 129 |
+
if isinstance(timeout, UnsetType):
|
| 130 |
+
raise ValueError("httpx2.Timeout must either include a default, or set all four parameters explicitly.")
|
| 131 |
+
self.connect = timeout if isinstance(connect, UnsetType) else connect
|
| 132 |
+
self.read = timeout if isinstance(read, UnsetType) else read
|
| 133 |
+
self.write = timeout if isinstance(write, UnsetType) else write
|
| 134 |
+
self.pool = timeout if isinstance(pool, UnsetType) else pool
|
| 135 |
+
|
| 136 |
+
def as_dict(self) -> dict[str, float | None]:
|
| 137 |
+
return {
|
| 138 |
+
"connect": self.connect,
|
| 139 |
+
"read": self.read,
|
| 140 |
+
"write": self.write,
|
| 141 |
+
"pool": self.pool,
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
def __repr__(self) -> str:
|
| 145 |
+
class_name = self.__class__.__name__
|
| 146 |
+
if len({self.connect, self.read, self.write, self.pool}) == 1:
|
| 147 |
+
return f"{class_name}(timeout={self.connect})"
|
| 148 |
+
return f"{class_name}(connect={self.connect}, read={self.read}, write={self.write}, pool={self.pool})"
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
@dataclasses.dataclass(kw_only=True)
|
| 152 |
+
class Limits:
|
| 153 |
+
"""
|
| 154 |
+
Configuration for limits to various client behaviors.
|
| 155 |
+
|
| 156 |
+
**Parameters:**
|
| 157 |
+
|
| 158 |
+
* **max_connections** - The maximum number of concurrent connections that may be
|
| 159 |
+
established.
|
| 160 |
+
* **max_keepalive_connections** - Allow the connection pool to maintain
|
| 161 |
+
keep-alive connections below this point. Should be less than or equal
|
| 162 |
+
to `max_connections`.
|
| 163 |
+
* **keepalive_expiry** - Time limit on idle keep-alive connections in seconds.
|
| 164 |
+
"""
|
| 165 |
+
|
| 166 |
+
max_connections: int | None = None
|
| 167 |
+
max_keepalive_connections: int | None = None
|
| 168 |
+
keepalive_expiry: float | None = 5.0
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
class Proxy:
|
| 172 |
+
def __init__(
|
| 173 |
+
self,
|
| 174 |
+
url: URL | str,
|
| 175 |
+
*,
|
| 176 |
+
ssl_context: ssl.SSLContext | None = None,
|
| 177 |
+
auth: tuple[str, str] | None = None,
|
| 178 |
+
headers: HeaderTypes | None = None,
|
| 179 |
+
) -> None:
|
| 180 |
+
url = URL(url)
|
| 181 |
+
headers = Headers(headers)
|
| 182 |
+
|
| 183 |
+
if url.scheme not in ("http", "https", "socks5", "socks5h"):
|
| 184 |
+
raise ValueError(f"Unknown scheme for proxy URL {url!r}")
|
| 185 |
+
|
| 186 |
+
if url.username or url.password:
|
| 187 |
+
# Remove any auth credentials from the URL.
|
| 188 |
+
auth = (url.username, url.password)
|
| 189 |
+
url = url.copy_with(username=None, password=None)
|
| 190 |
+
|
| 191 |
+
self.url = url
|
| 192 |
+
self.auth = auth
|
| 193 |
+
self.headers = headers
|
| 194 |
+
self.ssl_context = ssl_context
|
| 195 |
+
|
| 196 |
+
@property
|
| 197 |
+
def raw_auth(self) -> tuple[bytes, bytes] | None:
|
| 198 |
+
# The proxy authentication as raw bytes.
|
| 199 |
+
return None if self.auth is None else (self.auth[0].encode("utf-8"), self.auth[1].encode("utf-8"))
|
| 200 |
+
|
| 201 |
+
def __repr__(self) -> str:
|
| 202 |
+
# The authentication is represented with the password component masked.
|
| 203 |
+
auth = (self.auth[0], "********") if self.auth else None
|
| 204 |
+
|
| 205 |
+
# Build a nice concise representation.
|
| 206 |
+
url_str = f"{str(self.url)!r}"
|
| 207 |
+
auth_str = f", auth={auth!r}" if auth else ""
|
| 208 |
+
headers_str = f", headers={dict(self.headers)!r}" if self.headers else ""
|
| 209 |
+
return f"Proxy({url_str}{auth_str}{headers_str})"
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
DEFAULT_TIMEOUT_CONFIG = Timeout(timeout=5.0)
|
| 213 |
+
DEFAULT_LIMITS = Limits(max_connections=100, max_keepalive_connections=20)
|
| 214 |
+
DEFAULT_MAX_REDIRECTS = 20
|
| 215 |
+
|
| 216 |
+
DEFAULT_MAX_EVENT_SIZE_BYTES = 1024 * 1024
|
| 217 |
+
|
| 218 |
+
DEFAULT_MAX_MESSAGE_SIZE_BYTES = 65_536
|
| 219 |
+
DEFAULT_QUEUE_SIZE = 512
|
| 220 |
+
DEFAULT_KEEPALIVE_PING_INTERVAL_SECONDS =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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import inspect
|
| 4 |
+
import warnings
|
| 5 |
+
from collections.abc import AsyncGenerator, AsyncIterable, AsyncIterator, Iterable, Iterator, Mapping
|
| 6 |
+
from json import dumps as json_dumps
|
| 7 |
+
from typing import (
|
| 8 |
+
Any,
|
| 9 |
+
)
|
| 10 |
+
from urllib.parse import urlencode
|
| 11 |
+
|
| 12 |
+
from ._exceptions import StreamClosed, StreamConsumed
|
| 13 |
+
from ._multipart import MultipartStream
|
| 14 |
+
from ._types import (
|
| 15 |
+
AsyncByteStream,
|
| 16 |
+
RequestContent,
|
| 17 |
+
RequestData,
|
| 18 |
+
RequestFiles,
|
| 19 |
+
ResponseContent,
|
| 20 |
+
SyncByteStream,
|
| 21 |
+
)
|
| 22 |
+
from ._utils import peek_filelike_remaining_length, primitive_value_to_str
|
| 23 |
+
|
| 24 |
+
__all__ = ["ByteStream"]
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class ByteStream(AsyncByteStream, SyncByteStream):
|
| 28 |
+
def __init__(self, stream: bytes) -> None:
|
| 29 |
+
self._stream = stream
|
| 30 |
+
|
| 31 |
+
def __iter__(self) -> Iterator[bytes]:
|
| 32 |
+
yield self._stream
|
| 33 |
+
|
| 34 |
+
async def __aiter__(self) -> AsyncIterator[bytes]:
|
| 35 |
+
yield self._stream
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class IteratorByteStream(SyncByteStream):
|
| 39 |
+
CHUNK_SIZE = 65_536
|
| 40 |
+
|
| 41 |
+
def __init__(self, stream: Iterable[bytes]) -> None:
|
| 42 |
+
self._stream = stream
|
| 43 |
+
self._is_stream_consumed = False
|
| 44 |
+
self._is_generator = inspect.isgenerator(stream)
|
| 45 |
+
|
| 46 |
+
def __iter__(self) -> Iterator[bytes]:
|
| 47 |
+
if self._is_stream_consumed and self._is_generator:
|
| 48 |
+
raise StreamConsumed()
|
| 49 |
+
|
| 50 |
+
self._is_stream_consumed = True
|
| 51 |
+
if hasattr(self._stream, "read"):
|
| 52 |
+
# File-like interfaces should use 'read' directly.
|
| 53 |
+
chunk = self._stream.read(self.CHUNK_SIZE)
|
| 54 |
+
while chunk:
|
| 55 |
+
yield chunk
|
| 56 |
+
chunk = self._stream.read(self.CHUNK_SIZE)
|
| 57 |
+
else:
|
| 58 |
+
# Otherwise iterate.
|
| 59 |
+
yield from self._stream
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class AsyncIteratorByteStream(AsyncByteStream):
|
| 63 |
+
CHUNK_SIZE = 65_536
|
| 64 |
+
|
| 65 |
+
def __init__(self, stream: AsyncIterable[bytes]) -> None:
|
| 66 |
+
self._stream = stream
|
| 67 |
+
self._is_stream_consumed = False
|
| 68 |
+
self._is_generator = inspect.isasyncgen(stream)
|
| 69 |
+
|
| 70 |
+
async def __aiter__(self) -> AsyncIterator[bytes]:
|
| 71 |
+
if self._is_stream_consumed and self._is_generator:
|
| 72 |
+
raise StreamConsumed()
|
| 73 |
+
|
| 74 |
+
self._is_stream_consumed = True
|
| 75 |
+
if hasattr(self._stream, "aread"):
|
| 76 |
+
# File-like interfaces should use 'aread' directly.
|
| 77 |
+
chunk = await self._stream.aread(self.CHUNK_SIZE)
|
| 78 |
+
while chunk:
|
| 79 |
+
yield chunk
|
| 80 |
+
chunk = await self._stream.aread(self.CHUNK_SIZE)
|
| 81 |
+
else:
|
| 82 |
+
# Otherwise iterate, making sure the wrapped stream is closed even if the
|
| 83 |
+
# consumer stops early (e.g. an exception is raised part-way through decoding).
|
| 84 |
+
stream = self._stream.__aiter__()
|
| 85 |
+
try:
|
| 86 |
+
async for part in stream:
|
| 87 |
+
yield part
|
| 88 |
+
finally:
|
| 89 |
+
if isinstance(stream, AsyncGenerator):
|
| 90 |
+
await stream.aclose()
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class UnattachedStream(AsyncByteStream, SyncByteStream):
|
| 94 |
+
"""
|
| 95 |
+
If a request or response is serialized using pickle, then it is no longer
|
| 96 |
+
attached to a stream for I/O purposes. Any stream operations should result
|
| 97 |
+
in `httpx2.StreamClosed`.
|
| 98 |
+
"""
|
| 99 |
+
|
| 100 |
+
def __iter__(self) -> Iterator[bytes]:
|
| 101 |
+
raise StreamClosed()
|
| 102 |
+
|
| 103 |
+
async def __aiter__(self) -> AsyncIterator[bytes]:
|
| 104 |
+
raise StreamClosed()
|
| 105 |
+
yield b"" # pragma: no cover
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def encode_content(
|
| 109 |
+
content: str | bytes | Iterable[bytes] | AsyncIterable[bytes],
|
| 110 |
+
) -> tuple[dict[str, str], SyncByteStream | AsyncByteStream]:
|
| 111 |
+
if isinstance(content, (bytes, str)):
|
| 112 |
+
body = content.encode("utf-8") if isinstance(content, str) else content
|
| 113 |
+
content_length = len(body)
|
| 114 |
+
headers = {"Content-Length": str(content_length)} if body else {}
|
| 115 |
+
return headers, ByteStream(body)
|
| 116 |
+
|
| 117 |
+
elif isinstance(content, Iterable) and not isinstance(content, dict):
|
| 118 |
+
# `not isinstance(content, dict)` is a bit oddly specific, but it
|
| 119 |
+
# catches a case that's easy for users to make in error, and would
|
| 120 |
+
# otherwise pass through here, like any other bytes-iterable,
|
| 121 |
+
# because `dict` happens to be iterable. See issue #2491.
|
| 122 |
+
content_length_or_none = peek_filelike_remaining_length(content)
|
| 123 |
+
|
| 124 |
+
if content_length_or_none is None:
|
| 125 |
+
headers = {"Transfer-Encoding": "chunked"}
|
| 126 |
+
else:
|
| 127 |
+
headers = {"Content-Length": str(content_length_or_none)}
|
| 128 |
+
return headers, IteratorByteStream(content)
|
| 129 |
+
|
| 130 |
+
elif isinstance(content, AsyncIterable):
|
| 131 |
+
headers = {"Transfer-Encoding": "chunked"}
|
| 132 |
+
return headers, AsyncIteratorByteStream(content)
|
| 133 |
+
|
| 134 |
+
raise TypeError(f"Unexpected type for 'content', {type(content)!r}")
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def encode_urlencoded_data(data: RequestData) -> tuple[dict[str, str], ByteStream]:
|
| 138 |
+
plain_data: list[tuple[str, str]] = []
|
| 139 |
+
for key, value in data.items():
|
| 140 |
+
if isinstance(value, (list, tuple)):
|
| 141 |
+
plain_data.extend([(key, primitive_value_to_str(item)) for item in value])
|
| 142 |
+
else:
|
| 143 |
+
plain_data.append((key, primitive_value_to_str(value)))
|
| 144 |
+
body = urlencode(plain_data, doseq=True).encode("utf-8")
|
| 145 |
+
content_length = str(len(body))
|
| 146 |
+
content_type = "application/x-www-form-urlencoded"
|
| 147 |
+
headers = {"Content-Length": content_length, "Content-Type": content_type}
|
| 148 |
+
return headers, ByteStream(body)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def encode_multipart_data(
|
| 152 |
+
data: RequestData, files: RequestFiles, boundary: bytes | None
|
| 153 |
+
) -> tuple[dict[str, str], MultipartStream]:
|
| 154 |
+
multipart = MultipartStream(data=data, files=files, boundary=boundary)
|
| 155 |
+
headers = multipart.get_headers()
|
| 156 |
+
return headers, multipart
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def encode_text(text: str) -> tuple[dict[str, str], ByteStream]:
|
| 160 |
+
body = text.encode("utf-8")
|
| 161 |
+
content_length = str(len(body))
|
| 162 |
+
content_type = "text/plain; charset=utf-8"
|
| 163 |
+
headers = {"Content-Length": content_length, "Content-Type": content_type}
|
| 164 |
+
return headers, ByteStream(body)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def encode_html(html: str) -> tuple[dict[str, str], ByteStream]:
|
| 168 |
+
body = html.encode("utf-8")
|
| 169 |
+
content_length = str(len(body))
|
| 170 |
+
content_type = "text/html; charset=utf-8"
|
| 171 |
+
headers = {"Content-Length": content_length, "Content-Type": content_type}
|
| 172 |
+
return headers, ByteStream(body)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def encode_json(json: Any) -> tuple[dict[str, str], ByteStream]:
|
| 176 |
+
body = json_dumps(json, ensure_ascii=False, separators=(",", ":"), allow_nan=False).encode("utf-8")
|
| 177 |
+
content_length = str(len(body))
|
| 178 |
+
content_type = "application/json"
|
| 179 |
+
headers = {"Content-Length": content_length, "Content-Type": content_type}
|
| 180 |
+
return headers, ByteStream(body)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def encode_request(
|
| 184 |
+
content: RequestContent | None = None,
|
| 185 |
+
data: RequestData | None = None,
|
| 186 |
+
files: RequestFiles | None = None,
|
| 187 |
+
json: Any | None = None,
|
| 188 |
+
boundary: bytes | None = None,
|
| 189 |
+
) -> tuple[dict[str, str], SyncByteStream | AsyncByteStream]:
|
| 190 |
+
"""
|
| 191 |
+
Handles encoding the given `content`, `data`, `files`, and `json`,
|
| 192 |
+
returning a two-tuple of (<headers>, <stream>).
|
| 193 |
+
"""
|
| 194 |
+
if data is not None and not isinstance(data, Mapping):
|
| 195 |
+
# We prefer to separate `content=<bytes|str|byte iterator|bytes aiterator>`
|
| 196 |
+
# for raw request content, and `data=<form data>` for url encoded or
|
| 197 |
+
# multipart form content.
|
| 198 |
+
#
|
| 199 |
+
# However for compat with requests, we *do* still support
|
| 200 |
+
# `data=<bytes...>` usages. We deal with that case here, treating it
|
| 201 |
+
# as if `content=<...>` had been supplied instead.
|
| 202 |
+
message = "Use 'content=<...>' to upload raw bytes/text content."
|
| 203 |
+
warnings.warn(message, DeprecationWarning, stacklevel=2)
|
| 204 |
+
return encode_content(data)
|
| 205 |
+
|
| 206 |
+
if content is not None:
|
| 207 |
+
return encode_content(content)
|
| 208 |
+
elif files:
|
| 209 |
+
return encode_multipart_data(data or {}, files, boundary)
|
| 210 |
+
elif data:
|
| 211 |
+
return encode_urlencoded_data(data)
|
| 212 |
+
elif json is not None:
|
| 213 |
+
return encode_json(json)
|
| 214 |
+
|
| 215 |
+
return {}, ByteStream(b"")
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def encode_response(
|
| 219 |
+
content: ResponseContent | None = None,
|
| 220 |
+
text: str | None = None,
|
| 221 |
+
html: str | None = None,
|
| 222 |
+
json: Any | None = None,
|
| 223 |
+
) -> tuple[dict[str, str], SyncByteStream | AsyncByteStream]:
|
| 224 |
+
"""
|
| 225 |
+
Handles encoding the given `content`, returning a two-tuple of
|
| 226 |
+
(<headers>, <stream>).
|
| 227 |
+
"""
|
| 228 |
+
if content is not None:
|
| 229 |
+
return encode_content(content)
|
| 230 |
+
elif text is not None:
|
| 231 |
+
return encode_text(text)
|
| 232 |
+
elif html is not None:
|
| 233 |
+
return encode_html(html)
|
| 234 |
+
elif json is not None:
|
| 235 |
+
return encode_json(json)
|
| 236 |
+
|
| 237 |
+
return {}, ByteStream(b"")
|
.venv/lib/python3.12/site-packages/httpx2/_cookies.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import threading
|
| 3 |
+
import time
|
| 4 |
+
import urllib.request
|
| 5 |
+
from http import cookiejar
|
| 6 |
+
from http.cookiejar import Cookie, CookieJar, CookiePolicy, DefaultCookiePolicy
|
| 7 |
+
from typing import TYPE_CHECKING
|
| 8 |
+
|
| 9 |
+
__all__ = ["IndexedCookieJar"]
|
| 10 |
+
|
| 11 |
+
# [RFC 1035](https://www.rfc-editor.org/rfc/rfc1035#section-2.3.4) caps DNS names at 255 octets;
|
| 12 |
+
# longer hosts fall back to scanning every stored domain.
|
| 13 |
+
MAX_HOST_LENGTH = 255
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class IndexedCookieJar(CookieJar):
|
| 17 |
+
"""
|
| 18 |
+
A `CookieJar` whose per-request cost does not grow with the number of stored cookies.
|
| 19 |
+
|
| 20 |
+
Compared to `CookieJar`, on each request it:
|
| 21 |
+
|
| 22 |
+
1. Looks up only the domains that can match the request host, instead of checking every stored domain.
|
| 23 |
+
2. Skips the expiry sweep until the earliest known expiry has passed, instead of checking every stored cookie.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
_cookies: dict[str, dict[str, dict[str, Cookie]]]
|
| 27 |
+
_cookies_lock: threading.RLock
|
| 28 |
+
_policy: CookiePolicy
|
| 29 |
+
_next_expiry: float = math.inf
|
| 30 |
+
|
| 31 |
+
if TYPE_CHECKING:
|
| 32 |
+
|
| 33 |
+
def _cookies_for_domain(self, domain: str, request: urllib.request.Request) -> list[Cookie]: ...
|
| 34 |
+
|
| 35 |
+
def set_cookie(self, cookie: Cookie) -> None:
|
| 36 |
+
with self._cookies_lock:
|
| 37 |
+
super().set_cookie(cookie)
|
| 38 |
+
if cookie.expires is not None:
|
| 39 |
+
self._next_expiry = min(self._next_expiry, cookie.expires)
|
| 40 |
+
|
| 41 |
+
def clear_expired_cookies(self) -> None:
|
| 42 |
+
if time.time() < self._next_expiry:
|
| 43 |
+
return
|
| 44 |
+
with self._cookies_lock:
|
| 45 |
+
super().clear_expired_cookies()
|
| 46 |
+
self._next_expiry = min((c.expires for c in self if c.expires is not None), default=math.inf)
|
| 47 |
+
|
| 48 |
+
def _cookies_for_request(self, request: urllib.request.Request) -> list[Cookie]:
|
| 49 |
+
hosts: tuple[str, str] = cookiejar.eff_request_host(request) # type: ignore[attr-defined]
|
| 50 |
+
uses_default_matching = type(self._policy).domain_return_ok is DefaultCookiePolicy.domain_return_ok
|
| 51 |
+
if not uses_default_matching or max(map(len, hosts)) > MAX_HOST_LENGTH:
|
| 52 |
+
return super()._cookies_for_request(request) # type: ignore[misc, no-any-return]
|
| 53 |
+
|
| 54 |
+
cookies: list[Cookie] = []
|
| 55 |
+
for domain in _matching_domains(hosts):
|
| 56 |
+
if domain in self._cookies:
|
| 57 |
+
cookies.extend(self._cookies_for_domain(domain, request))
|
| 58 |
+
return cookies
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _matching_domains(hosts: tuple[str, str]) -> dict[str, None]:
|
| 62 |
+
"""
|
| 63 |
+
Every cookie domain `DefaultCookiePolicy.domain_return_ok` can accept for these hosts, least specific first.
|
| 64 |
+
|
| 65 |
+
For `a.example.org` that is `""`, `.org`, `org`, `.example.org`, `example.org`, `.a.example.org`, `a.example.org`.
|
| 66 |
+
"""
|
| 67 |
+
domains = {"": None}
|
| 68 |
+
for host in hosts:
|
| 69 |
+
dotted = host if host.startswith(".") else f".{host}"
|
| 70 |
+
for index in range(len(dotted) - 1, -1, -1):
|
| 71 |
+
if dotted[index] == ".":
|
| 72 |
+
domains[dotted[index:]] = None
|
| 73 |
+
domains[dotted[index + 1 :]] = None
|
| 74 |
+
return domains
|
.venv/lib/python3.12/site-packages/httpx2/_decoders.py
ADDED
|
@@ -0,0 +1,458 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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otations
|
| 8 |
+
|
| 9 |
+
import codecs
|
| 10 |
+
import io
|
| 11 |
+
import itertools
|
| 12 |
+
import sys
|
| 13 |
+
import typing
|
| 14 |
+
import zlib
|
| 15 |
+
|
| 16 |
+
from ._exceptions import DecodingError
|
| 17 |
+
|
| 18 |
+
# Brotli support is optional
|
| 19 |
+
try:
|
| 20 |
+
# The C bindings in `brotli` are recommended for CPython.
|
| 21 |
+
import brotli
|
| 22 |
+
except ImportError: # pragma: no cover
|
| 23 |
+
try:
|
| 24 |
+
# The CFFI bindings in `brotlicffi` are recommended for PyPy
|
| 25 |
+
# and other environments.
|
| 26 |
+
import brotlicffi as brotli
|
| 27 |
+
except ImportError:
|
| 28 |
+
brotli = None
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# Zstandard support is optional on Python <= 3.13.
|
| 32 |
+
# On Python 3.14+, the stdlib includes an optional built-in zstd implementation.
|
| 33 |
+
if typing.TYPE_CHECKING:
|
| 34 |
+
if sys.version_info >= (3, 14):
|
| 35 |
+
from compression.zstd import ZstdDecompressor, ZstdError
|
| 36 |
+
else:
|
| 37 |
+
from backports.zstd import ZstdDecompressor, ZstdError
|
| 38 |
+
|
| 39 |
+
_zstandard_installed: bool
|
| 40 |
+
else: # pragma: no cover
|
| 41 |
+
try:
|
| 42 |
+
if sys.version_info >= (3, 14):
|
| 43 |
+
from compression.zstd import ZstdDecompressor, ZstdError
|
| 44 |
+
else:
|
| 45 |
+
from backports.zstd import ZstdDecompressor, ZstdError
|
| 46 |
+
|
| 47 |
+
_zstandard_installed = True
|
| 48 |
+
except ImportError:
|
| 49 |
+
_zstandard_installed = False
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
MAX_DECODE_CHUNK_SIZE = 2**20 # 1 MiB
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class Decompressor(typing.Protocol):
|
| 56 |
+
@property
|
| 57 |
+
def unconsumed_tail(self) -> bytes: ...
|
| 58 |
+
|
| 59 |
+
def decompress(self, data: bytes, max_length: int) -> bytes: ...
|
| 60 |
+
|
| 61 |
+
def flush(self) -> bytes: ...
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class ZlibDecompressor:
|
| 65 |
+
"""
|
| 66 |
+
Drain a `zlib`/`gzip` decompressor in bounded pieces so a small compressed
|
| 67 |
+
input cannot inflate to an unbounded buffer in a single call.
|
| 68 |
+
"""
|
| 69 |
+
|
| 70 |
+
def __init__(self, decompressor: Decompressor) -> None:
|
| 71 |
+
self.decompressor = decompressor
|
| 72 |
+
|
| 73 |
+
def decompress(self, data: bytes) -> typing.Iterator[bytes]:
|
| 74 |
+
decompressed = self.decompressor.decompress(data, MAX_DECODE_CHUNK_SIZE)
|
| 75 |
+
while decompressed:
|
| 76 |
+
yield decompressed
|
| 77 |
+
decompressed = self.decompressor.decompress(self.decompressor.unconsumed_tail, MAX_DECODE_CHUNK_SIZE)
|
| 78 |
+
|
| 79 |
+
def flush(self) -> bytes:
|
| 80 |
+
return self.decompressor.flush()
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class ContentDecoder:
|
| 84 |
+
def decode(self, data: bytes) -> typing.Iterator[bytes]:
|
| 85 |
+
raise NotImplementedError() # pragma: no cover
|
| 86 |
+
|
| 87 |
+
def flush(self) -> typing.Iterator[bytes]:
|
| 88 |
+
raise NotImplementedError() # pragma: no cover
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
class IdentityDecoder(ContentDecoder):
|
| 92 |
+
"""
|
| 93 |
+
Handle unencoded data.
|
| 94 |
+
"""
|
| 95 |
+
|
| 96 |
+
def decode(self, data: bytes) -> typing.Iterator[bytes]:
|
| 97 |
+
yield data
|
| 98 |
+
|
| 99 |
+
def flush(self) -> typing.Iterator[bytes]:
|
| 100 |
+
yield from ()
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class DeflateDecoder(ContentDecoder):
|
| 104 |
+
"""
|
| 105 |
+
Handle 'deflate' decoding.
|
| 106 |
+
|
| 107 |
+
See: https://stackoverflow.com/questions/1838699
|
| 108 |
+
"""
|
| 109 |
+
|
| 110 |
+
def __init__(self) -> None:
|
| 111 |
+
self.first_attempt = True
|
| 112 |
+
self.decompressor = ZlibDecompressor(zlib.decompressobj())
|
| 113 |
+
|
| 114 |
+
def decode(self, data: bytes) -> typing.Iterator[bytes]:
|
| 115 |
+
was_first_attempt = self.first_attempt
|
| 116 |
+
self.first_attempt = False
|
| 117 |
+
try:
|
| 118 |
+
yield from self.decompressor.decompress(data)
|
| 119 |
+
except zlib.error as exc:
|
| 120 |
+
if was_first_attempt:
|
| 121 |
+
self.decompressor = ZlibDecompressor(zlib.decompressobj(-zlib.MAX_WBITS))
|
| 122 |
+
yield from self.decode(data)
|
| 123 |
+
else:
|
| 124 |
+
raise DecodingError(str(exc)) from exc
|
| 125 |
+
|
| 126 |
+
def flush(self) -> typing.Iterator[bytes]:
|
| 127 |
+
try:
|
| 128 |
+
yield self.decompressor.flush()
|
| 129 |
+
except zlib.error as exc: # pragma: no cover
|
| 130 |
+
raise DecodingError(str(exc)) from exc
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
class GZipDecoder(ContentDecoder):
|
| 134 |
+
"""
|
| 135 |
+
Handle 'gzip' decoding.
|
| 136 |
+
|
| 137 |
+
See: https://stackoverflow.com/questions/1838699
|
| 138 |
+
"""
|
| 139 |
+
|
| 140 |
+
def __init__(self) -> None:
|
| 141 |
+
self.decompressor = ZlibDecompressor(zlib.decompressobj(zlib.MAX_WBITS | 16))
|
| 142 |
+
|
| 143 |
+
def decode(self, data: bytes) -> typing.Iterator[bytes]:
|
| 144 |
+
try:
|
| 145 |
+
yield from self.decompressor.decompress(data)
|
| 146 |
+
except zlib.error as exc:
|
| 147 |
+
raise DecodingError(str(exc)) from exc
|
| 148 |
+
|
| 149 |
+
def flush(self) -> typing.Iterator[bytes]:
|
| 150 |
+
try:
|
| 151 |
+
yield self.decompressor.flush()
|
| 152 |
+
except zlib.error as exc: # pragma: no cover
|
| 153 |
+
raise DecodingError(str(exc)) from exc
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
class BrotliDecoder(ContentDecoder):
|
| 157 |
+
"""
|
| 158 |
+
Handle 'brotli' decoding.
|
| 159 |
+
|
| 160 |
+
Requires `pip install brotlipy`. See: https://brotlipy.readthedocs.io/
|
| 161 |
+
or `pip install brotli`. See https://github.com/google/brotli
|
| 162 |
+
Supports both 'brotlipy' and 'Brotli' packages since they share an import
|
| 163 |
+
name. The top branches are for 'brotlipy' and bottom branches for 'Brotli'
|
| 164 |
+
"""
|
| 165 |
+
|
| 166 |
+
def __init__(self) -> None:
|
| 167 |
+
if brotli is None: # pragma: no cover
|
| 168 |
+
raise ImportError(
|
| 169 |
+
"Using 'BrotliDecoder', but neither of the 'brotlicffi' or 'brotli' "
|
| 170 |
+
"packages have been installed. "
|
| 171 |
+
"Make sure to install httpx using `pip install httpx[brotli]`."
|
| 172 |
+
) from None
|
| 173 |
+
|
| 174 |
+
self.decompressor = brotli.Decompressor()
|
| 175 |
+
self.seen_data = False
|
| 176 |
+
self._decompress: typing.Callable[..., bytes]
|
| 177 |
+
if hasattr(self.decompressor, "decompress"):
|
| 178 |
+
# The 'brotlicffi' package.
|
| 179 |
+
self._decompress = self.decompressor.decompress # pragma: no cover
|
| 180 |
+
else:
|
| 181 |
+
# The 'brotli' package.
|
| 182 |
+
self._decompress = self.decompressor.process
|
| 183 |
+
|
| 184 |
+
def decode(self, data: bytes) -> typing.Iterator[bytes]:
|
| 185 |
+
if not data:
|
| 186 |
+
return
|
| 187 |
+
self.seen_data = True
|
| 188 |
+
try:
|
| 189 |
+
# The C backend may allocate nearly twice the requested threshold.
|
| 190 |
+
output_buffer_limit = MAX_DECODE_CHUNK_SIZE // 2
|
| 191 |
+
decompressed = self._decompress(data, output_buffer_limit=output_buffer_limit)
|
| 192 |
+
while decompressed:
|
| 193 |
+
yield decompressed
|
| 194 |
+
decompressed = self._decompress(b"", output_buffer_limit=output_buffer_limit)
|
| 195 |
+
except brotli.error as exc:
|
| 196 |
+
raise DecodingError(str(exc)) from exc
|
| 197 |
+
|
| 198 |
+
def flush(self) -> typing.Iterator[bytes]:
|
| 199 |
+
if not self.seen_data:
|
| 200 |
+
return
|
| 201 |
+
try:
|
| 202 |
+
if hasattr(self.decompressor, "finish"):
|
| 203 |
+
# Only available in the 'brotlicffi' package.
|
| 204 |
+
|
| 205 |
+
# As the decompressor decompresses eagerly, this
|
| 206 |
+
# will never actually emit any data. However, it will potentially throw
|
| 207 |
+
# errors if a truncated or damaged data stream has been used.
|
| 208 |
+
self.decompressor.finish() # pragma: no cover
|
| 209 |
+
except brotli.error as exc: # pragma: no cover
|
| 210 |
+
raise DecodingError(str(exc)) from exc
|
| 211 |
+
yield from ()
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
class ZStandardDecoder(ContentDecoder):
|
| 215 |
+
"""Handle 'zstd' RFC 8878 decoding.
|
| 216 |
+
|
| 217 |
+
On Python 3.13 and below, this requires `pip install httpx2[zstd]`.
|
| 218 |
+
"""
|
| 219 |
+
|
| 220 |
+
# inspired by the ZstdDecoder implementation in urllib3
|
| 221 |
+
def __init__(self) -> None:
|
| 222 |
+
if not _zstandard_installed: # pragma: no cover
|
| 223 |
+
raise ImportError(
|
| 224 |
+
"Using 'ZStandardDecoder', ...Make sure to install httpx using `pip install httpx[zstd]`."
|
| 225 |
+
) from None
|
| 226 |
+
|
| 227 |
+
self.decompressor = ZstdDecompressor()
|
| 228 |
+
self.seen_data = False
|
| 229 |
+
|
| 230 |
+
def decode(self, data: bytes) -> typing.Iterator[bytes]:
|
| 231 |
+
if not data:
|
| 232 |
+
return
|
| 233 |
+
self.seen_data = True
|
| 234 |
+
try:
|
| 235 |
+
if self.decompressor.eof:
|
| 236 |
+
data = self.decompressor.unused_data + data
|
| 237 |
+
self.decompressor = ZstdDecompressor()
|
| 238 |
+
while True:
|
| 239 |
+
decompressed = self.decompressor.decompress(data, MAX_DECODE_CHUNK_SIZE)
|
| 240 |
+
while decompressed:
|
| 241 |
+
yield decompressed
|
| 242 |
+
if self.decompressor.needs_input or self.decompressor.eof:
|
| 243 |
+
break
|
| 244 |
+
decompressed = self.decompressor.decompress(b"", MAX_DECODE_CHUNK_SIZE)
|
| 245 |
+
if not (self.decompressor.eof and self.decompressor.unused_data):
|
| 246 |
+
break
|
| 247 |
+
data = self.decompressor.unused_data
|
| 248 |
+
self.decompressor = ZstdDecompressor()
|
| 249 |
+
except ZstdError as exc:
|
| 250 |
+
raise DecodingError(str(exc)) from exc
|
| 251 |
+
|
| 252 |
+
def flush(self) -> typing.Iterator[bytes]:
|
| 253 |
+
if not self.seen_data:
|
| 254 |
+
return
|
| 255 |
+
if not self.decompressor.eof:
|
| 256 |
+
raise DecodingError("Zstandard data is incomplete") # pragma: no cover
|
| 257 |
+
yield from ()
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
class MultiDecoder(ContentDecoder):
|
| 261 |
+
"""
|
| 262 |
+
Handle the case where multiple encodings have been applied.
|
| 263 |
+
"""
|
| 264 |
+
|
| 265 |
+
max_decode_links: typing.ClassVar[int] = 5
|
| 266 |
+
|
| 267 |
+
def __init__(self, encodings: typing.Sequence[str]) -> None:
|
| 268 |
+
"""
|
| 269 |
+
'encodings' should be the content codings in the order in which
|
| 270 |
+
each was applied.
|
| 271 |
+
"""
|
| 272 |
+
codings = [encoding for encoding in encodings if encoding in SUPPORTED_DECODERS]
|
| 273 |
+
if len(codings) > self.max_decode_links:
|
| 274 |
+
raise DecodingError(f"Cannot apply more than {self.max_decode_links} content encodings.")
|
| 275 |
+
# Note that we reverse the order for decoding.
|
| 276 |
+
self.children: list[ContentDecoder] = [SUPPORTED_DECODERS[coding]() for coding in reversed(codings)]
|
| 277 |
+
|
| 278 |
+
def decode(self, data: bytes) -> typing.Iterator[bytes]:
|
| 279 |
+
streams: typing.Iterator[bytes] = iter((data,))
|
| 280 |
+
for child in self.children:
|
| 281 |
+
streams = self._pipe(child.decode, streams)
|
| 282 |
+
yield from streams
|
| 283 |
+
|
| 284 |
+
def flush(self) -> typing.Iterator[bytes]:
|
| 285 |
+
streams: typing.Iterator[bytes] = iter(())
|
| 286 |
+
for child in self.children:
|
| 287 |
+
streams = itertools.chain(self._pipe(child.decode, streams), child.flush())
|
| 288 |
+
yield from streams
|
| 289 |
+
|
| 290 |
+
@staticmethod
|
| 291 |
+
def _pipe(
|
| 292 |
+
decode: typing.Callable[[bytes], typing.Iterator[bytes]],
|
| 293 |
+
upstream: typing.Iterator[bytes],
|
| 294 |
+
) -> typing.Iterator[bytes]:
|
| 295 |
+
for chunk in upstream:
|
| 296 |
+
yield from decode(chunk)
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
class ByteChunker:
|
| 300 |
+
"""
|
| 301 |
+
Handles returning byte content in fixed-size chunks.
|
| 302 |
+
"""
|
| 303 |
+
|
| 304 |
+
def __init__(self, chunk_size: int | None = None) -> None:
|
| 305 |
+
self._buffer = io.BytesIO()
|
| 306 |
+
self._chunk_size = chunk_size
|
| 307 |
+
|
| 308 |
+
def decode(self, content: bytes) -> list[bytes]:
|
| 309 |
+
if self._chunk_size is None:
|
| 310 |
+
return [content] if content else []
|
| 311 |
+
|
| 312 |
+
self._buffer.write(content)
|
| 313 |
+
if self._buffer.tell() >= self._chunk_size:
|
| 314 |
+
value = self._buffer.getvalue()
|
| 315 |
+
chunks = [value[i : i + self._chunk_size] for i in range(0, len(value), self._chunk_size)]
|
| 316 |
+
if len(chunks[-1]) == self._chunk_size:
|
| 317 |
+
self._buffer.seek(0)
|
| 318 |
+
self._buffer.truncate()
|
| 319 |
+
return chunks
|
| 320 |
+
else:
|
| 321 |
+
self._buffer.seek(0)
|
| 322 |
+
self._buffer.write(chunks[-1])
|
| 323 |
+
self._buffer.truncate()
|
| 324 |
+
return chunks[:-1]
|
| 325 |
+
else:
|
| 326 |
+
return []
|
| 327 |
+
|
| 328 |
+
def flush(self) -> list[bytes]:
|
| 329 |
+
value = self._buffer.getvalue()
|
| 330 |
+
self._buffer.seek(0)
|
| 331 |
+
self._buffer.truncate()
|
| 332 |
+
return [value] if value else []
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
class TextChunker:
|
| 336 |
+
"""
|
| 337 |
+
Handles returning text content in fixed-size chunks.
|
| 338 |
+
"""
|
| 339 |
+
|
| 340 |
+
def __init__(self, chunk_size: int | None = None) -> None:
|
| 341 |
+
self._buffer = io.StringIO()
|
| 342 |
+
self._chunk_size = chunk_size
|
| 343 |
+
|
| 344 |
+
def decode(self, content: str) -> list[str]:
|
| 345 |
+
if self._chunk_size is None:
|
| 346 |
+
return [content] if content else []
|
| 347 |
+
|
| 348 |
+
self._buffer.write(content)
|
| 349 |
+
if self._buffer.tell() >= self._chunk_size:
|
| 350 |
+
value = self._buffer.getvalue()
|
| 351 |
+
chunks = [value[i : i + self._chunk_size] for i in range(0, len(value), self._chunk_size)]
|
| 352 |
+
if len(chunks[-1]) == self._chunk_size:
|
| 353 |
+
self._buffer.seek(0)
|
| 354 |
+
self._buffer.truncate()
|
| 355 |
+
return chunks
|
| 356 |
+
else:
|
| 357 |
+
self._buffer.seek(0)
|
| 358 |
+
self._buffer.write(chunks[-1])
|
| 359 |
+
self._buffer.truncate()
|
| 360 |
+
return chunks[:-1]
|
| 361 |
+
else:
|
| 362 |
+
return []
|
| 363 |
+
|
| 364 |
+
def flush(self) -> list[str]:
|
| 365 |
+
value = self._buffer.getvalue()
|
| 366 |
+
self._buffer.seek(0)
|
| 367 |
+
self._buffer.truncate()
|
| 368 |
+
return [value] if value else []
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
class TextDecoder:
|
| 372 |
+
"""
|
| 373 |
+
Handles incrementally decoding bytes into text
|
| 374 |
+
"""
|
| 375 |
+
|
| 376 |
+
def __init__(self, encoding: str = "utf-8") -> None:
|
| 377 |
+
self.decoder = codecs.getincrementaldecoder(encoding)(errors="replace")
|
| 378 |
+
|
| 379 |
+
def decode(self, data: bytes) -> str:
|
| 380 |
+
return self.decoder.decode(data)
|
| 381 |
+
|
| 382 |
+
def flush(self) -> str:
|
| 383 |
+
return self.decoder.decode(b"", True)
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
class LineDecoder:
|
| 387 |
+
"""
|
| 388 |
+
Handles incrementally reading lines from text.
|
| 389 |
+
|
| 390 |
+
Has the same behaviour as the stdllib splitlines,
|
| 391 |
+
but handling the input iteratively.
|
| 392 |
+
"""
|
| 393 |
+
|
| 394 |
+
def __init__(self) -> None:
|
| 395 |
+
self.buffer: list[str] = []
|
| 396 |
+
self.trailing_cr: bool = False
|
| 397 |
+
|
| 398 |
+
def decode(self, text: str) -> list[str]:
|
| 399 |
+
# See https://docs.python.org/3/library/stdtypes.html#str.splitlines
|
| 400 |
+
NEWLINE_CHARS = "\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029"
|
| 401 |
+
|
| 402 |
+
# We always push a trailing `\r` into the next decode iteration.
|
| 403 |
+
if self.trailing_cr:
|
| 404 |
+
text = "\r" + text
|
| 405 |
+
self.trailing_cr = False
|
| 406 |
+
if text.endswith("\r"):
|
| 407 |
+
self.trailing_cr = True
|
| 408 |
+
text = text[:-1]
|
| 409 |
+
|
| 410 |
+
if not text:
|
| 411 |
+
# NOTE: the edge case input of empty text doesn't occur in practice,
|
| 412 |
+
# because other httpx internals filter out this value
|
| 413 |
+
return [] # pragma: no cover
|
| 414 |
+
|
| 415 |
+
trailing_newline = text[-1] in NEWLINE_CHARS
|
| 416 |
+
lines = text.splitlines()
|
| 417 |
+
|
| 418 |
+
if len(lines) == 1 and not trailing_newline:
|
| 419 |
+
# No new lines, buffer the input and continue.
|
| 420 |
+
self.buffer.append(lines[0])
|
| 421 |
+
return []
|
| 422 |
+
|
| 423 |
+
if self.buffer:
|
| 424 |
+
# Include any existing buffer in the first portion of the
|
| 425 |
+
# splitlines result.
|
| 426 |
+
lines = ["".join(self.buffer) + lines[0]] + lines[1:]
|
| 427 |
+
self.buffer = []
|
| 428 |
+
|
| 429 |
+
if not trailing_newline:
|
| 430 |
+
# If the last segment of splitlines is not newline terminated,
|
| 431 |
+
# then drop it from our output and start a new buffer.
|
| 432 |
+
self.buffer = [lines.pop()]
|
| 433 |
+
|
| 434 |
+
return lines
|
| 435 |
+
|
| 436 |
+
def flush(self) -> list[str]:
|
| 437 |
+
if not self.buffer and not self.trailing_cr:
|
| 438 |
+
return []
|
| 439 |
+
|
| 440 |
+
lines = ["".join(self.buffer)]
|
| 441 |
+
self.buffer = []
|
| 442 |
+
self.trailing_cr = False
|
| 443 |
+
return lines
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
SUPPORTED_DECODERS: dict[str, type[ContentDecoder]] = {
|
| 447 |
+
"identity": IdentityDecoder,
|
| 448 |
+
"gzip": GZipDecoder,
|
| 449 |
+
"deflate": DeflateDecoder,
|
| 450 |
+
"br": BrotliDecoder,
|
| 451 |
+
"zstd": ZStandardDecoder,
|
| 452 |
+
}
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
if brotli is None:
|
| 456 |
+
SUPPORTED_DECODERS.pop("br") # pragma: no cover
|
| 457 |
+
if not _zstandard_installed:
|
| 458 |
+
SUPPORTED_DECODERS.pop("zstd") # pragma: no cover
|
.venv/lib/python3.12/site-packages/httpx2/_exceptions.py
ADDED
|
@@ -0,0 +1,380 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
| 10 |
+
· WriteTimeout
|
| 11 |
+
· PoolTimeout
|
| 12 |
+
- NetworkError
|
| 13 |
+
· ConnectError
|
| 14 |
+
· ReadError
|
| 15 |
+
· WriteError
|
| 16 |
+
· CloseError
|
| 17 |
+
- ProtocolError
|
| 18 |
+
· LocalProtocolError
|
| 19 |
+
· RemoteProtocolError
|
| 20 |
+
- ProxyError
|
| 21 |
+
- UnsupportedProtocol
|
| 22 |
+
+ DecodingError
|
| 23 |
+
+ TooManyRedirects
|
| 24 |
+
x HTTPStatusError
|
| 25 |
+
* InvalidURL
|
| 26 |
+
* CookieConflict
|
| 27 |
+
* StreamError
|
| 28 |
+
x StreamConsumed
|
| 29 |
+
x StreamClosed
|
| 30 |
+
x ResponseNotRead
|
| 31 |
+
x RequestNotRead
|
| 32 |
+
"""
|
| 33 |
+
|
| 34 |
+
from __future__ import annotations
|
| 35 |
+
|
| 36 |
+
import contextlib
|
| 37 |
+
import typing
|
| 38 |
+
from collections.abc import Generator
|
| 39 |
+
|
| 40 |
+
if typing.TYPE_CHECKING:
|
| 41 |
+
from ._models import Request, Response # pragma: no cover
|
| 42 |
+
|
| 43 |
+
__all__ = [
|
| 44 |
+
"CloseError",
|
| 45 |
+
"ConnectError",
|
| 46 |
+
"ConnectTimeout",
|
| 47 |
+
"CookieConflict",
|
| 48 |
+
"DecodingError",
|
| 49 |
+
"HTTPError",
|
| 50 |
+
"HTTPStatusError",
|
| 51 |
+
"InvalidURL",
|
| 52 |
+
"LocalProtocolError",
|
| 53 |
+
"NetworkError",
|
| 54 |
+
"PoolTimeout",
|
| 55 |
+
"ProtocolError",
|
| 56 |
+
"ProxyError",
|
| 57 |
+
"ReadError",
|
| 58 |
+
"ReadTimeout",
|
| 59 |
+
"RemoteProtocolError",
|
| 60 |
+
"RequestError",
|
| 61 |
+
"RequestNotRead",
|
| 62 |
+
"ResponseNotRead",
|
| 63 |
+
"StreamClosed",
|
| 64 |
+
"StreamConsumed",
|
| 65 |
+
"StreamError",
|
| 66 |
+
"TimeoutException",
|
| 67 |
+
"TooManyRedirects",
|
| 68 |
+
"TransportError",
|
| 69 |
+
"UnsupportedProtocol",
|
| 70 |
+
"WriteError",
|
| 71 |
+
"WriteTimeout",
|
| 72 |
+
]
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class HTTPXDeprecationWarning(UserWarning):
|
| 76 |
+
"""A custom deprecation warning for HTTPX.
|
| 77 |
+
|
| 78 |
+
Unlike the built-in `DeprecationWarning`, this inherits from `UserWarning` to ensure it is visible by default,
|
| 79 |
+
helping users discover deprecated features without needing to enable warnings explicitly.
|
| 80 |
+
|
| 81 |
+
Reference: https://sethmlarson.dev/deprecations-via-warnings-dont-work-for-python-libraries
|
| 82 |
+
"""
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class HTTPError(Exception):
|
| 86 |
+
"""
|
| 87 |
+
Base class for `RequestError` and `HTTPStatusError`.
|
| 88 |
+
|
| 89 |
+
Useful for `try...except` blocks when issuing a request,
|
| 90 |
+
and then calling `.raise_for_status()`.
|
| 91 |
+
|
| 92 |
+
For example:
|
| 93 |
+
|
| 94 |
+
```
|
| 95 |
+
try:
|
| 96 |
+
response = httpx2.get("https://www.example.com")
|
| 97 |
+
response.raise_for_status()
|
| 98 |
+
except httpx2.HTTPError as exc:
|
| 99 |
+
print(f"HTTP Exception for {exc.request.url} - {exc}")
|
| 100 |
+
```
|
| 101 |
+
"""
|
| 102 |
+
|
| 103 |
+
def __init__(self, message: str) -> None:
|
| 104 |
+
super().__init__(message)
|
| 105 |
+
self._request: Request | None = None
|
| 106 |
+
|
| 107 |
+
@property
|
| 108 |
+
def request(self) -> Request:
|
| 109 |
+
if self._request is None:
|
| 110 |
+
raise RuntimeError("The .request property has not been set.")
|
| 111 |
+
return self._request
|
| 112 |
+
|
| 113 |
+
@request.setter
|
| 114 |
+
def request(self, request: Request) -> None:
|
| 115 |
+
self._request = request
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
class RequestError(HTTPError):
|
| 119 |
+
"""
|
| 120 |
+
Base class for all exceptions that may occur when issuing a `.request()`.
|
| 121 |
+
"""
|
| 122 |
+
|
| 123 |
+
def __init__(self, message: str, *, request: Request | None = None) -> None:
|
| 124 |
+
super().__init__(message)
|
| 125 |
+
# At the point an exception is raised we won't typically have a request
|
| 126 |
+
# instance to associate it with.
|
| 127 |
+
#
|
| 128 |
+
# The 'request_context' context manager is used within the Client and
|
| 129 |
+
# Response methods in order to ensure that any raised exceptions
|
| 130 |
+
# have a `.request` property set on them.
|
| 131 |
+
self._request = request
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
class TransportError(RequestError):
|
| 135 |
+
"""
|
| 136 |
+
Base class for all exceptions that occur at the level of the Transport API.
|
| 137 |
+
"""
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
# Timeout exceptions...
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
class TimeoutException(TransportError):
|
| 144 |
+
"""
|
| 145 |
+
The base class for timeout errors.
|
| 146 |
+
|
| 147 |
+
An operation has timed out.
|
| 148 |
+
"""
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
class ConnectTimeout(TimeoutException):
|
| 152 |
+
"""
|
| 153 |
+
Timed out while connecting to the host.
|
| 154 |
+
"""
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
class ReadTimeout(TimeoutException):
|
| 158 |
+
"""
|
| 159 |
+
Timed out while receiving data from the host.
|
| 160 |
+
"""
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
class WriteTimeout(TimeoutException):
|
| 164 |
+
"""
|
| 165 |
+
Timed out while sending data to the host.
|
| 166 |
+
"""
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
class PoolTimeout(TimeoutException):
|
| 170 |
+
"""
|
| 171 |
+
Timed out waiting to acquire a connection from the pool.
|
| 172 |
+
"""
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
# Core networking exceptions...
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
class NetworkError(TransportError):
|
| 179 |
+
"""
|
| 180 |
+
The base class for network-related errors.
|
| 181 |
+
|
| 182 |
+
An error occurred while interacting with the network.
|
| 183 |
+
"""
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
class ReadError(NetworkError):
|
| 187 |
+
"""
|
| 188 |
+
Failed to receive data from the network.
|
| 189 |
+
"""
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
class WriteError(NetworkError):
|
| 193 |
+
"""
|
| 194 |
+
Failed to send data through the network.
|
| 195 |
+
"""
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
class ConnectError(NetworkError):
|
| 199 |
+
"""
|
| 200 |
+
Failed to establish a connection.
|
| 201 |
+
"""
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
class CloseError(NetworkError):
|
| 205 |
+
"""
|
| 206 |
+
Failed to close a connection.
|
| 207 |
+
"""
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
# Other transport exceptions...
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
class ProxyError(TransportError):
|
| 214 |
+
"""
|
| 215 |
+
An error occurred while establishing a proxy connection.
|
| 216 |
+
"""
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
class UnsupportedProtocol(TransportError):
|
| 220 |
+
"""
|
| 221 |
+
Attempted to make a request to an unsupported protocol.
|
| 222 |
+
|
| 223 |
+
For example issuing a request to `ftp://www.example.com`.
|
| 224 |
+
"""
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
class ProtocolError(TransportError):
|
| 228 |
+
"""
|
| 229 |
+
The protocol was violated.
|
| 230 |
+
"""
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
class LocalProtocolError(ProtocolError):
|
| 234 |
+
"""
|
| 235 |
+
A protocol was violated by the client.
|
| 236 |
+
|
| 237 |
+
For example if the user instantiated a `Request` instance explicitly,
|
| 238 |
+
failed to include the mandatory `Host:` header, and then issued it directly
|
| 239 |
+
using `client.send()`.
|
| 240 |
+
"""
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
class RemoteProtocolError(ProtocolError):
|
| 244 |
+
"""
|
| 245 |
+
The protocol was violated by the server.
|
| 246 |
+
|
| 247 |
+
For example, returning malformed HTTP.
|
| 248 |
+
"""
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
# Other request exceptions...
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
class DecodingError(RequestError):
|
| 255 |
+
"""
|
| 256 |
+
Decoding of the response failed, due to a malformed encoding.
|
| 257 |
+
"""
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
class TooManyRedirects(RequestError):
|
| 261 |
+
"""
|
| 262 |
+
Too many redirects.
|
| 263 |
+
"""
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
# Client errors
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
class HTTPStatusError(HTTPError):
|
| 270 |
+
"""
|
| 271 |
+
The response had an error HTTP status of 4xx or 5xx.
|
| 272 |
+
|
| 273 |
+
May be raised when calling `response.raise_for_status()`
|
| 274 |
+
"""
|
| 275 |
+
|
| 276 |
+
def __init__(self, message: str, *, request: Request, response: Response) -> None:
|
| 277 |
+
super().__init__(message)
|
| 278 |
+
self.request = request
|
| 279 |
+
self.response = response
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
class InvalidURL(Exception):
|
| 283 |
+
"""
|
| 284 |
+
URL is improperly formed or cannot be parsed.
|
| 285 |
+
"""
|
| 286 |
+
|
| 287 |
+
def __init__(self, message: str) -> None:
|
| 288 |
+
super().__init__(message)
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
class CookieConflict(Exception):
|
| 292 |
+
"""
|
| 293 |
+
Attempted to lookup a cookie by name, but multiple cookies existed.
|
| 294 |
+
|
| 295 |
+
Can occur when calling `response.cookies.get(...)`.
|
| 296 |
+
"""
|
| 297 |
+
|
| 298 |
+
def __init__(self, message: str) -> None:
|
| 299 |
+
super().__init__(message)
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
# Stream exceptions...
|
| 303 |
+
|
| 304 |
+
# These may occur as the result of a programming error, by accessing
|
| 305 |
+
# the request/response stream in an invalid manner.
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
class StreamError(RuntimeError):
|
| 309 |
+
"""
|
| 310 |
+
The base class for stream exceptions.
|
| 311 |
+
|
| 312 |
+
The developer made an error in accessing the request stream in
|
| 313 |
+
an invalid way.
|
| 314 |
+
"""
|
| 315 |
+
|
| 316 |
+
def __init__(self, message: str) -> None:
|
| 317 |
+
super().__init__(message)
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
class StreamConsumed(StreamError):
|
| 321 |
+
"""
|
| 322 |
+
Attempted to read or stream content, but the content has already
|
| 323 |
+
been streamed.
|
| 324 |
+
"""
|
| 325 |
+
|
| 326 |
+
def __init__(self) -> None:
|
| 327 |
+
message = (
|
| 328 |
+
"Attempted to read or stream some content, but the content has "
|
| 329 |
+
"already been streamed. For requests, this could be due to passing "
|
| 330 |
+
"a generator as request content, and then receiving a redirect "
|
| 331 |
+
"response or a secondary request as part of an authentication flow."
|
| 332 |
+
"For responses, this could be due to attempting to stream the response "
|
| 333 |
+
"content more than once."
|
| 334 |
+
)
|
| 335 |
+
super().__init__(message)
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
class StreamClosed(StreamError):
|
| 339 |
+
"""
|
| 340 |
+
Attempted to read or stream response content, but the request has been
|
| 341 |
+
closed.
|
| 342 |
+
"""
|
| 343 |
+
|
| 344 |
+
def __init__(self) -> None:
|
| 345 |
+
message = "Attempted to read or stream content, but the stream has been closed."
|
| 346 |
+
super().__init__(message)
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
class ResponseNotRead(StreamError):
|
| 350 |
+
"""
|
| 351 |
+
Attempted to access streaming response content, without having called `read()`.
|
| 352 |
+
"""
|
| 353 |
+
|
| 354 |
+
def __init__(self) -> None:
|
| 355 |
+
message = "Attempted to access streaming response content, without having called `read()`."
|
| 356 |
+
super().__init__(message)
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
class RequestNotRead(StreamError):
|
| 360 |
+
"""
|
| 361 |
+
Attempted to access streaming request content, without having called `read()`.
|
| 362 |
+
"""
|
| 363 |
+
|
| 364 |
+
def __init__(self) -> None:
|
| 365 |
+
message = "Attempted to access streaming request content, without having called `read()`."
|
| 366 |
+
super().__init__(message)
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
@contextlib.contextmanager
|
| 370 |
+
def request_context(request: Request | None = None) -> Generator[None]:
|
| 371 |
+
"""
|
| 372 |
+
A context manager that can be used to attach the given request context
|
| 373 |
+
to any `RequestError` exceptions that are raised within the block.
|
| 374 |
+
"""
|
| 375 |
+
try:
|
| 376 |
+
yield
|
| 377 |
+
except RequestError as exc:
|
| 378 |
+
if request is not None:
|
| 379 |
+
exc.request = request
|
| 380 |
+
raise exc
|
.venv/lib/python3.12/site-packages/httpx2/_main.py
ADDED
|
@@ -0,0 +1,483 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import functools
|
| 4 |
+
import json
|
| 5 |
+
import sys
|
| 6 |
+
import typing
|
| 7 |
+
|
| 8 |
+
import click
|
| 9 |
+
import pygments.lexers
|
| 10 |
+
import pygments.util
|
| 11 |
+
import rich.console
|
| 12 |
+
import rich.markup
|
| 13 |
+
import rich.progress
|
| 14 |
+
import rich.syntax
|
| 15 |
+
import rich.table
|
| 16 |
+
|
| 17 |
+
from ._client import Client
|
| 18 |
+
from ._exceptions import RequestError
|
| 19 |
+
from ._models import Response
|
| 20 |
+
from ._status_codes import codes
|
| 21 |
+
|
| 22 |
+
if typing.TYPE_CHECKING:
|
| 23 |
+
import httpcore2 # pragma: no cover
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def print_help() -> None:
|
| 27 |
+
console = rich.console.Console()
|
| 28 |
+
|
| 29 |
+
console.print("[bold]HTTPX :butterfly:", justify="center")
|
| 30 |
+
console.print()
|
| 31 |
+
console.print("A next generation HTTP client.", justify="center")
|
| 32 |
+
console.print()
|
| 33 |
+
console.print("Usage: [bold]httpx2[/bold] [cyan]<URL> [OPTIONS][/cyan] ", justify="left")
|
| 34 |
+
console.print()
|
| 35 |
+
|
| 36 |
+
table = rich.table.Table.grid(padding=1, pad_edge=True)
|
| 37 |
+
table.add_column("Parameter", no_wrap=True, justify="left", style="bold")
|
| 38 |
+
table.add_column("Description")
|
| 39 |
+
table.add_row(
|
| 40 |
+
"-m, --method [cyan]METHOD",
|
| 41 |
+
"Request method, such as GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD, QUERY.\n"
|
| 42 |
+
"[Default: GET, or POST if a request body is included]",
|
| 43 |
+
)
|
| 44 |
+
table.add_row(
|
| 45 |
+
"-p, --params [cyan]<NAME VALUE> ...",
|
| 46 |
+
"Query parameters to include in the request URL.",
|
| 47 |
+
)
|
| 48 |
+
table.add_row("-c, --content [cyan]TEXT", "Byte content to include in the request body.")
|
| 49 |
+
table.add_row("-d, --data [cyan]<NAME VALUE> ...", "Form data to include in the request body.")
|
| 50 |
+
table.add_row(
|
| 51 |
+
"-f, --files [cyan]<NAME FILENAME> ...",
|
| 52 |
+
"Form files to include in the request body.",
|
| 53 |
+
)
|
| 54 |
+
table.add_row("-j, --json [cyan]TEXT", "JSON data to include in the request body.")
|
| 55 |
+
table.add_row(
|
| 56 |
+
"-h, --headers [cyan]<NAME VALUE> ...",
|
| 57 |
+
"Include additional HTTP headers in the request.",
|
| 58 |
+
)
|
| 59 |
+
table.add_row("--cookies [cyan]<NAME VALUE> ...", "Cookies to include in the request.")
|
| 60 |
+
table.add_row(
|
| 61 |
+
"--auth [cyan]<USER PASS>",
|
| 62 |
+
"Username and password to include in the request. Specify '-' for the password"
|
| 63 |
+
" to use a password prompt. Note that using --verbose/-v will expose"
|
| 64 |
+
" the Authorization header, including the password encoding"
|
| 65 |
+
" in a trivially reversible format.",
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
table.add_row(
|
| 69 |
+
"--proxy [cyan]URL",
|
| 70 |
+
"Send the request via a proxy. Should be the URL giving the proxy address.",
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
table.add_row(
|
| 74 |
+
"--timeout [cyan]FLOAT",
|
| 75 |
+
"Timeout value to use for network operations, such as establishing the"
|
| 76 |
+
" connection, reading some data, etc... [Default: 5.0]",
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
table.add_row("--follow-redirects", "Automatically follow redirects.")
|
| 80 |
+
table.add_row("--verify / --no-verify", "Enable SSL verification.")
|
| 81 |
+
table.add_row("--http2", "Send the request using HTTP/2, if the remote server supports it.")
|
| 82 |
+
|
| 83 |
+
table.add_row(
|
| 84 |
+
"--download [cyan]FILE",
|
| 85 |
+
"Save the response content as a file, rather than displaying it.",
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
table.add_row("-v, --verbose", "Verbose output. Show request as well as response.")
|
| 89 |
+
table.add_row("--help", "Show this message and exit.")
|
| 90 |
+
console.print(table)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def get_lexer_for_response(response: Response) -> str:
|
| 94 |
+
content_type = response.headers.get("Content-Type")
|
| 95 |
+
if content_type is not None:
|
| 96 |
+
mime_type, _, _ = content_type.partition(";")
|
| 97 |
+
try:
|
| 98 |
+
return typing.cast(str, pygments.lexers.get_lexer_for_mimetype(mime_type.strip()).name)
|
| 99 |
+
except pygments.util.ClassNotFound: # pragma: no cover
|
| 100 |
+
pass
|
| 101 |
+
return "" # pragma: no cover
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def format_request_headers(request: httpcore2.Request, http2: bool = False) -> str:
|
| 105 |
+
version = "HTTP/2" if http2 else "HTTP/1.1"
|
| 106 |
+
headers = [(name.lower() if http2 else name, value) for name, value in request.headers]
|
| 107 |
+
method = request.method.decode("ascii")
|
| 108 |
+
target = request.url.target.decode("ascii")
|
| 109 |
+
lines = [f"{method} {target} {version}"] + [
|
| 110 |
+
f"{name.decode('ascii')}: {value.decode('ascii')}" for name, value in headers
|
| 111 |
+
]
|
| 112 |
+
return "\n".join(lines)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def format_response_headers(
|
| 116 |
+
http_version: bytes,
|
| 117 |
+
status: int,
|
| 118 |
+
reason_phrase: bytes | None,
|
| 119 |
+
headers: list[tuple[bytes, bytes]],
|
| 120 |
+
) -> str:
|
| 121 |
+
version = http_version.decode("ascii")
|
| 122 |
+
reason = codes.get_reason_phrase(status) if reason_phrase is None else reason_phrase.decode("ascii")
|
| 123 |
+
lines = [f"{version} {status} {reason}"] + [
|
| 124 |
+
f"{name.decode('ascii')}: {value.decode('ascii')}" for name, value in headers
|
| 125 |
+
]
|
| 126 |
+
return "\n".join(lines)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def print_request_headers(request: httpcore2.Request, http2: bool = False) -> None:
|
| 130 |
+
console = rich.console.Console()
|
| 131 |
+
http_text = format_request_headers(request, http2=http2)
|
| 132 |
+
syntax = rich.syntax.Syntax(http_text, "http", theme="ansi_dark", word_wrap=True)
|
| 133 |
+
console.print(syntax)
|
| 134 |
+
syntax = rich.syntax.Syntax("", "http", theme="ansi_dark", word_wrap=True)
|
| 135 |
+
console.print(syntax)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def print_response_headers(
|
| 139 |
+
http_version: bytes,
|
| 140 |
+
status: int,
|
| 141 |
+
reason_phrase: bytes | None,
|
| 142 |
+
headers: list[tuple[bytes, bytes]],
|
| 143 |
+
) -> None:
|
| 144 |
+
console = rich.console.Console()
|
| 145 |
+
http_text = format_response_headers(http_version, status, reason_phrase, headers)
|
| 146 |
+
syntax = rich.syntax.Syntax(http_text, "http", theme="ansi_dark", word_wrap=True)
|
| 147 |
+
console.print(syntax)
|
| 148 |
+
syntax = rich.syntax.Syntax("", "http", theme="ansi_dark", word_wrap=True)
|
| 149 |
+
console.print(syntax)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def print_response(response: Response) -> None:
|
| 153 |
+
console = rich.console.Console()
|
| 154 |
+
lexer_name = get_lexer_for_response(response)
|
| 155 |
+
if lexer_name:
|
| 156 |
+
if lexer_name.lower() == "json":
|
| 157 |
+
try:
|
| 158 |
+
data = response.json()
|
| 159 |
+
text = json.dumps(data, indent=4)
|
| 160 |
+
except ValueError: # pragma: no cover
|
| 161 |
+
text = response.text
|
| 162 |
+
else:
|
| 163 |
+
text = response.text
|
| 164 |
+
|
| 165 |
+
syntax = rich.syntax.Syntax(text, lexer_name, theme="ansi_dark", word_wrap=True)
|
| 166 |
+
console.print(syntax)
|
| 167 |
+
else:
|
| 168 |
+
console.print(f"<{len(response.content)} bytes of binary data>")
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
_PCTRTT = tuple[tuple[str, str], ...]
|
| 172 |
+
_PCTRTTT = tuple[_PCTRTT, ...]
|
| 173 |
+
_PeerCertRetDictType = dict[str, str | _PCTRTTT | _PCTRTT]
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def format_certificate(cert: _PeerCertRetDictType) -> str: # pragma: no cover
|
| 177 |
+
lines: list[str] = []
|
| 178 |
+
for key, value in cert.items():
|
| 179 |
+
if isinstance(value, (list, tuple)):
|
| 180 |
+
lines.append(f"* {key}:")
|
| 181 |
+
for item in value:
|
| 182 |
+
if key in ("subject", "issuer"):
|
| 183 |
+
lines.extend(f"* {sub_item[0]}: {sub_item[1]!r}" for sub_item in item)
|
| 184 |
+
elif isinstance(item, tuple) and len(item) == 2:
|
| 185 |
+
lines.append(f"* {item[0]}: {item[1]!r}")
|
| 186 |
+
else:
|
| 187 |
+
lines.append(f"* {item!r}")
|
| 188 |
+
else:
|
| 189 |
+
lines.append(f"* {key}: {value!r}")
|
| 190 |
+
return "\n".join(lines)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def trace(name: str, info: typing.Mapping[str, typing.Any], verbose: bool = False) -> None:
|
| 194 |
+
console = rich.console.Console()
|
| 195 |
+
if name == "connection.connect_tcp.started" and verbose:
|
| 196 |
+
host = info["host"]
|
| 197 |
+
console.print(f"* Connecting to {host!r}")
|
| 198 |
+
elif name == "connection.connect_tcp.complete" and verbose:
|
| 199 |
+
stream = info["return_value"]
|
| 200 |
+
server_addr = stream.get_extra_info("server_addr")
|
| 201 |
+
console.print(f"* Connected to {server_addr[0]!r} on port {server_addr[1]}")
|
| 202 |
+
elif name == "connection.start_tls.complete" and verbose: # pragma: no cover
|
| 203 |
+
stream = info["return_value"]
|
| 204 |
+
ssl_object = stream.get_extra_info("ssl_object")
|
| 205 |
+
version = ssl_object.version()
|
| 206 |
+
cipher = ssl_object.cipher()
|
| 207 |
+
server_cert = ssl_object.getpeercert()
|
| 208 |
+
alpn = ssl_object.selected_alpn_protocol()
|
| 209 |
+
console.print(f"* SSL established using {version!r} / {cipher[0]!r}")
|
| 210 |
+
console.print(f"* Selected ALPN protocol: {alpn!r}")
|
| 211 |
+
if server_cert:
|
| 212 |
+
console.print("* Server certificate:")
|
| 213 |
+
console.print(format_certificate(server_cert))
|
| 214 |
+
elif name == "http11.send_request_headers.started" and verbose:
|
| 215 |
+
request = info["request"]
|
| 216 |
+
print_request_headers(request, http2=False)
|
| 217 |
+
elif name == "http2.send_request_headers.started" and verbose: # pragma: no cover
|
| 218 |
+
request = info["request"]
|
| 219 |
+
print_request_headers(request, http2=True)
|
| 220 |
+
elif name == "http11.receive_response_headers.complete":
|
| 221 |
+
http_version, status, reason_phrase, headers = info["return_value"]
|
| 222 |
+
print_response_headers(http_version, status, reason_phrase, headers)
|
| 223 |
+
elif name == "http2.receive_response_headers.complete": # pragma: no cover
|
| 224 |
+
status, headers = info["return_value"]
|
| 225 |
+
http_version = b"HTTP/2"
|
| 226 |
+
reason_phrase = None
|
| 227 |
+
print_response_headers(http_version, status, reason_phrase, headers)
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def download_response(response: Response, download: typing.BinaryIO) -> None:
|
| 231 |
+
console = rich.console.Console()
|
| 232 |
+
console.print()
|
| 233 |
+
content_length = response.headers.get("Content-Length")
|
| 234 |
+
with rich.progress.Progress(
|
| 235 |
+
"[progress.description]{task.description}",
|
| 236 |
+
"[progress.percentage]{task.percentage:>3.0f}%",
|
| 237 |
+
rich.progress.BarColumn(bar_width=None),
|
| 238 |
+
rich.progress.DownloadColumn(),
|
| 239 |
+
rich.progress.TransferSpeedColumn(),
|
| 240 |
+
) as progress:
|
| 241 |
+
description = f"Downloading [bold]{rich.markup.escape(download.name)}"
|
| 242 |
+
download_task = progress.add_task(
|
| 243 |
+
description,
|
| 244 |
+
total=int(content_length or 0),
|
| 245 |
+
start=content_length is not None,
|
| 246 |
+
)
|
| 247 |
+
for chunk in response.iter_bytes():
|
| 248 |
+
download.write(chunk)
|
| 249 |
+
progress.update(download_task, completed=response.num_bytes_downloaded)
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def validate_json(
|
| 253 |
+
ctx: click.Context,
|
| 254 |
+
param: click.Option | click.Parameter,
|
| 255 |
+
value: typing.Any,
|
| 256 |
+
) -> typing.Any:
|
| 257 |
+
if value is None:
|
| 258 |
+
return None
|
| 259 |
+
|
| 260 |
+
try:
|
| 261 |
+
return json.loads(value)
|
| 262 |
+
except json.JSONDecodeError: # pragma: no cover
|
| 263 |
+
raise click.BadParameter("Not valid JSON")
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
def validate_auth(
|
| 267 |
+
ctx: click.Context,
|
| 268 |
+
param: click.Option | click.Parameter,
|
| 269 |
+
value: typing.Any,
|
| 270 |
+
) -> typing.Any:
|
| 271 |
+
if value == (None, None):
|
| 272 |
+
return None
|
| 273 |
+
|
| 274 |
+
username, password = value
|
| 275 |
+
if password == "-": # pragma: no cover
|
| 276 |
+
password = click.prompt("Password", hide_input=True)
|
| 277 |
+
return (username, password)
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def handle_help(
|
| 281 |
+
ctx: click.Context,
|
| 282 |
+
param: click.Option | click.Parameter,
|
| 283 |
+
value: typing.Any,
|
| 284 |
+
) -> None:
|
| 285 |
+
if not value or ctx.resilient_parsing:
|
| 286 |
+
return
|
| 287 |
+
|
| 288 |
+
print_help()
|
| 289 |
+
ctx.exit()
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
@click.command(add_help_option=False)
|
| 293 |
+
@click.argument("url", type=str)
|
| 294 |
+
@click.option(
|
| 295 |
+
"--method",
|
| 296 |
+
"-m",
|
| 297 |
+
"method",
|
| 298 |
+
type=str,
|
| 299 |
+
help=(
|
| 300 |
+
"Request method, such as GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD, QUERY. "
|
| 301 |
+
"[Default: GET, or POST if a request body is included]"
|
| 302 |
+
),
|
| 303 |
+
)
|
| 304 |
+
@click.option(
|
| 305 |
+
"--params",
|
| 306 |
+
"-p",
|
| 307 |
+
"params",
|
| 308 |
+
type=(str, str),
|
| 309 |
+
multiple=True,
|
| 310 |
+
help="Query parameters to include in the request URL.",
|
| 311 |
+
)
|
| 312 |
+
@click.option(
|
| 313 |
+
"--content",
|
| 314 |
+
"-c",
|
| 315 |
+
"content",
|
| 316 |
+
type=str,
|
| 317 |
+
help="Byte content to include in the request body.",
|
| 318 |
+
)
|
| 319 |
+
@click.option(
|
| 320 |
+
"--data",
|
| 321 |
+
"-d",
|
| 322 |
+
"data",
|
| 323 |
+
type=(str, str),
|
| 324 |
+
multiple=True,
|
| 325 |
+
help="Form data to include in the request body.",
|
| 326 |
+
)
|
| 327 |
+
@click.option(
|
| 328 |
+
"--files",
|
| 329 |
+
"-f",
|
| 330 |
+
"files",
|
| 331 |
+
type=(str, click.File(mode="rb")),
|
| 332 |
+
multiple=True,
|
| 333 |
+
help="Form files to include in the request body.",
|
| 334 |
+
)
|
| 335 |
+
@click.option(
|
| 336 |
+
"--json",
|
| 337 |
+
"-j",
|
| 338 |
+
"json",
|
| 339 |
+
type=str,
|
| 340 |
+
callback=validate_json,
|
| 341 |
+
help="JSON data to include in the request body.",
|
| 342 |
+
)
|
| 343 |
+
@click.option(
|
| 344 |
+
"--headers",
|
| 345 |
+
"-h",
|
| 346 |
+
"headers",
|
| 347 |
+
type=(str, str),
|
| 348 |
+
multiple=True,
|
| 349 |
+
help="Include additional HTTP headers in the request.",
|
| 350 |
+
)
|
| 351 |
+
@click.option(
|
| 352 |
+
"--cookies",
|
| 353 |
+
"cookies",
|
| 354 |
+
type=(str, str),
|
| 355 |
+
multiple=True,
|
| 356 |
+
help="Cookies to include in the request.",
|
| 357 |
+
)
|
| 358 |
+
@click.option(
|
| 359 |
+
"--auth",
|
| 360 |
+
"auth",
|
| 361 |
+
type=(str, str),
|
| 362 |
+
default=(None, None),
|
| 363 |
+
callback=validate_auth,
|
| 364 |
+
help=(
|
| 365 |
+
"Username and password to include in the request. "
|
| 366 |
+
"Specify '-' for the password to use a password prompt. "
|
| 367 |
+
"Note that using --verbose/-v will expose the Authorization header, "
|
| 368 |
+
"including the password encoding in a trivially reversible format."
|
| 369 |
+
),
|
| 370 |
+
)
|
| 371 |
+
@click.option(
|
| 372 |
+
"--proxy",
|
| 373 |
+
"proxy",
|
| 374 |
+
type=str,
|
| 375 |
+
default=None,
|
| 376 |
+
help="Send the request via a proxy. Should be the URL giving the proxy address.",
|
| 377 |
+
)
|
| 378 |
+
@click.option(
|
| 379 |
+
"--timeout",
|
| 380 |
+
"timeout",
|
| 381 |
+
type=float,
|
| 382 |
+
default=5.0,
|
| 383 |
+
help=(
|
| 384 |
+
"Timeout value to use for network operations, such as establishing the "
|
| 385 |
+
"connection, reading some data, etc... [Default: 5.0]"
|
| 386 |
+
),
|
| 387 |
+
)
|
| 388 |
+
@click.option(
|
| 389 |
+
"--follow-redirects",
|
| 390 |
+
"follow_redirects",
|
| 391 |
+
is_flag=True,
|
| 392 |
+
default=False,
|
| 393 |
+
help="Automatically follow redirects.",
|
| 394 |
+
)
|
| 395 |
+
@click.option(
|
| 396 |
+
"--verify/--no-verify",
|
| 397 |
+
default=True,
|
| 398 |
+
help="Enable SSL verification.",
|
| 399 |
+
)
|
| 400 |
+
@click.option(
|
| 401 |
+
"--http2",
|
| 402 |
+
"http2",
|
| 403 |
+
type=bool,
|
| 404 |
+
is_flag=True,
|
| 405 |
+
default=False,
|
| 406 |
+
help="Send the request using HTTP/2, if the remote server supports it.",
|
| 407 |
+
)
|
| 408 |
+
@click.option(
|
| 409 |
+
"--download",
|
| 410 |
+
type=click.File("wb"),
|
| 411 |
+
help="Save the response content as a file, rather than displaying it.",
|
| 412 |
+
)
|
| 413 |
+
@click.option(
|
| 414 |
+
"--verbose",
|
| 415 |
+
"-v",
|
| 416 |
+
type=bool,
|
| 417 |
+
is_flag=True,
|
| 418 |
+
default=False,
|
| 419 |
+
help="Verbose. Show request as well as response.",
|
| 420 |
+
)
|
| 421 |
+
@click.option(
|
| 422 |
+
"--help",
|
| 423 |
+
is_flag=True,
|
| 424 |
+
is_eager=True,
|
| 425 |
+
expose_value=False,
|
| 426 |
+
callback=handle_help,
|
| 427 |
+
help="Show this message and exit.",
|
| 428 |
+
)
|
| 429 |
+
def main(
|
| 430 |
+
url: str,
|
| 431 |
+
method: str,
|
| 432 |
+
params: list[tuple[str, str]],
|
| 433 |
+
content: str,
|
| 434 |
+
data: list[tuple[str, str]],
|
| 435 |
+
files: list[tuple[str, click.File]],
|
| 436 |
+
json: str,
|
| 437 |
+
headers: list[tuple[str, str]],
|
| 438 |
+
cookies: list[tuple[str, str]],
|
| 439 |
+
auth: tuple[str, str] | None,
|
| 440 |
+
proxy: str,
|
| 441 |
+
timeout: float,
|
| 442 |
+
follow_redirects: bool,
|
| 443 |
+
verify: bool,
|
| 444 |
+
http2: bool,
|
| 445 |
+
download: typing.BinaryIO | None,
|
| 446 |
+
verbose: bool,
|
| 447 |
+
) -> None:
|
| 448 |
+
"""
|
| 449 |
+
An HTTP command line client.
|
| 450 |
+
Sends a request and displays the response.
|
| 451 |
+
"""
|
| 452 |
+
if not method:
|
| 453 |
+
method = "POST" if content or data or files or json else "GET"
|
| 454 |
+
|
| 455 |
+
try:
|
| 456 |
+
with Client(proxy=proxy, timeout=timeout, http2=http2, verify=verify) as client:
|
| 457 |
+
with client.stream(
|
| 458 |
+
method,
|
| 459 |
+
url,
|
| 460 |
+
params=list(params),
|
| 461 |
+
content=content,
|
| 462 |
+
data=dict(data),
|
| 463 |
+
files=files, # type: ignore[arg-type]
|
| 464 |
+
json=json,
|
| 465 |
+
headers=headers,
|
| 466 |
+
cookies=dict(cookies),
|
| 467 |
+
auth=auth,
|
| 468 |
+
follow_redirects=follow_redirects,
|
| 469 |
+
extensions={"trace": functools.partial(trace, verbose=verbose)},
|
| 470 |
+
) as response:
|
| 471 |
+
if download is not None:
|
| 472 |
+
download_response(response, download)
|
| 473 |
+
else:
|
| 474 |
+
response.read()
|
| 475 |
+
if response.content:
|
| 476 |
+
print_response(response)
|
| 477 |
+
|
| 478 |
+
except RequestError as exc:
|
| 479 |
+
console = rich.console.Console()
|
| 480 |
+
console.print(f"[red]{type(exc).__name__}[/red]: {exc}")
|
| 481 |
+
sys.exit(1)
|
| 482 |
+
|
| 483 |
+
sys.exit(0 if response.is_success else 1)
|
.venv/lib/python3.12/site-packages/httpx2/_models.py
ADDED
|
@@ -0,0 +1,1274 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import codecs
|
| 4 |
+
import contextlib
|
| 5 |
+
import datetime
|
| 6 |
+
import email.message
|
| 7 |
+
import json as jsonlib
|
| 8 |
+
import re
|
| 9 |
+
import typing
|
| 10 |
+
import urllib.request
|
| 11 |
+
from collections.abc import AsyncGenerator, Mapping
|
| 12 |
+
from http.cookiejar import Cookie, CookieJar
|
| 13 |
+
|
| 14 |
+
from ._content import ByteStream, UnattachedStream, encode_request, encode_response
|
| 15 |
+
from ._cookies import IndexedCookieJar
|
| 16 |
+
from ._decoders import (
|
| 17 |
+
ByteChunker,
|
| 18 |
+
ContentDecoder,
|
| 19 |
+
IdentityDecoder,
|
| 20 |
+
LineDecoder,
|
| 21 |
+
MultiDecoder,
|
| 22 |
+
TextChunker,
|
| 23 |
+
TextDecoder,
|
| 24 |
+
)
|
| 25 |
+
from ._exceptions import (
|
| 26 |
+
CookieConflict,
|
| 27 |
+
HTTPStatusError,
|
| 28 |
+
RequestNotRead,
|
| 29 |
+
ResponseNotRead,
|
| 30 |
+
StreamClosed,
|
| 31 |
+
StreamConsumed,
|
| 32 |
+
request_context,
|
| 33 |
+
)
|
| 34 |
+
from ._multipart import get_multipart_boundary_from_content_type
|
| 35 |
+
from ._status_codes import codes
|
| 36 |
+
from ._types import (
|
| 37 |
+
AsyncByteStream,
|
| 38 |
+
CookieTypes,
|
| 39 |
+
HeaderTypes,
|
| 40 |
+
QueryParamTypes,
|
| 41 |
+
RequestContent,
|
| 42 |
+
RequestData,
|
| 43 |
+
RequestExtensions,
|
| 44 |
+
RequestFiles,
|
| 45 |
+
ResponseContent,
|
| 46 |
+
ResponseExtensions,
|
| 47 |
+
SyncByteStream,
|
| 48 |
+
)
|
| 49 |
+
from ._urls import URL
|
| 50 |
+
from ._utils import to_bytes_or_str, to_str
|
| 51 |
+
|
| 52 |
+
__all__ = ["Cookies", "Headers", "Request", "Response"]
|
| 53 |
+
|
| 54 |
+
SENSITIVE_HEADERS = {"authorization", "proxy-authorization"}
|
| 55 |
+
|
| 56 |
+
_T = typing.TypeVar("_T")
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _is_known_encoding(encoding: str) -> bool:
|
| 60 |
+
"""
|
| 61 |
+
Return `True` if `encoding` is a known codec.
|
| 62 |
+
"""
|
| 63 |
+
try:
|
| 64 |
+
codecs.lookup(encoding)
|
| 65 |
+
except LookupError:
|
| 66 |
+
return False
|
| 67 |
+
return True
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _normalize_header_key(key: str | bytes, encoding: str | None = None) -> bytes:
|
| 71 |
+
"""
|
| 72 |
+
Coerce str/bytes into a strictly byte-wise HTTP header key.
|
| 73 |
+
"""
|
| 74 |
+
return key if isinstance(key, bytes) else key.encode(encoding or "ascii")
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _normalize_header_value(value: str | bytes, encoding: str | None = None) -> bytes:
|
| 78 |
+
"""
|
| 79 |
+
Coerce str/bytes into a strictly byte-wise HTTP header value.
|
| 80 |
+
"""
|
| 81 |
+
if isinstance(value, bytes):
|
| 82 |
+
return value
|
| 83 |
+
if not isinstance(value, str):
|
| 84 |
+
raise TypeError(f"Header value must be str or bytes, not {type(value)}")
|
| 85 |
+
return value.encode(encoding or "ascii")
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def _parse_content_type_charset(content_type: str) -> str | None:
|
| 89 |
+
# We used to use `cgi.parse_header()` here, but `cgi` became a dead battery.
|
| 90 |
+
# See: https://peps.python.org/pep-0594/#cgi
|
| 91 |
+
msg = email.message.Message()
|
| 92 |
+
msg["content-type"] = content_type
|
| 93 |
+
return msg.get_content_charset(failobj=None)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def _parse_header_links(value: str) -> list[dict[str, str]]:
|
| 97 |
+
"""
|
| 98 |
+
Returns a list of parsed link headers, for more info see:
|
| 99 |
+
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link
|
| 100 |
+
The generic syntax of those is:
|
| 101 |
+
Link: < uri-reference >; param1=value1; param2="value2"
|
| 102 |
+
So for instance:
|
| 103 |
+
Link; '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;'
|
| 104 |
+
would return
|
| 105 |
+
[
|
| 106 |
+
{"url": "http:/.../front.jpeg", "type": "image/jpeg"},
|
| 107 |
+
{"url": "http://.../back.jpeg"},
|
| 108 |
+
]
|
| 109 |
+
:param value: HTTP Link entity-header field
|
| 110 |
+
:return: list of parsed link headers
|
| 111 |
+
"""
|
| 112 |
+
links: list[dict[str, str]] = []
|
| 113 |
+
replace_chars = " '\""
|
| 114 |
+
value = value.strip(replace_chars)
|
| 115 |
+
if not value:
|
| 116 |
+
return links
|
| 117 |
+
for val in re.split(", *<", value):
|
| 118 |
+
try:
|
| 119 |
+
url, params = val.split(";", 1)
|
| 120 |
+
except ValueError:
|
| 121 |
+
url, params = val, ""
|
| 122 |
+
link = {"url": url.strip("<> '\"")}
|
| 123 |
+
for param in params.split(";"):
|
| 124 |
+
try:
|
| 125 |
+
key, value = param.split("=")
|
| 126 |
+
except ValueError:
|
| 127 |
+
break
|
| 128 |
+
link[key.strip(replace_chars)] = value.strip(replace_chars)
|
| 129 |
+
links.append(link)
|
| 130 |
+
return links
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def _obfuscate_sensitive_headers(
|
| 134 |
+
items: typing.Iterable[tuple[typing.AnyStr, typing.AnyStr]],
|
| 135 |
+
) -> typing.Iterator[tuple[typing.AnyStr, typing.AnyStr]]:
|
| 136 |
+
for k, v in items:
|
| 137 |
+
if to_str(k.lower()) in SENSITIVE_HEADERS:
|
| 138 |
+
v = to_bytes_or_str("[secure]", match_type_of=v)
|
| 139 |
+
yield k, v
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
class Headers(typing.MutableMapping[str, str]):
|
| 143 |
+
"""
|
| 144 |
+
HTTP headers, as a case-insensitive multi-dict.
|
| 145 |
+
"""
|
| 146 |
+
|
| 147 |
+
def __init__(
|
| 148 |
+
self,
|
| 149 |
+
headers: HeaderTypes | None = None,
|
| 150 |
+
encoding: str | None = None,
|
| 151 |
+
) -> None:
|
| 152 |
+
self._list: list[tuple[bytes, bytes, bytes]] = []
|
| 153 |
+
|
| 154 |
+
if isinstance(headers, Headers):
|
| 155 |
+
self._list = list(headers._list)
|
| 156 |
+
elif isinstance(headers, Mapping):
|
| 157 |
+
for k, v in headers.items():
|
| 158 |
+
bytes_key = _normalize_header_key(k, encoding)
|
| 159 |
+
bytes_value = _normalize_header_value(v, encoding)
|
| 160 |
+
self._list.append((bytes_key, bytes_key.lower(), bytes_value))
|
| 161 |
+
elif headers is not None:
|
| 162 |
+
for k, v in headers:
|
| 163 |
+
bytes_key = _normalize_header_key(k, encoding)
|
| 164 |
+
bytes_value = _normalize_header_value(v, encoding)
|
| 165 |
+
self._list.append((bytes_key, bytes_key.lower(), bytes_value))
|
| 166 |
+
|
| 167 |
+
self._encoding = encoding
|
| 168 |
+
|
| 169 |
+
@property
|
| 170 |
+
def encoding(self) -> str:
|
| 171 |
+
"""
|
| 172 |
+
Header encoding is mandated as ascii, but we allow fallbacks to utf-8
|
| 173 |
+
or iso-8859-1.
|
| 174 |
+
"""
|
| 175 |
+
if self._encoding is None:
|
| 176 |
+
for encoding in ["ascii", "utf-8"]:
|
| 177 |
+
for key, value in self.raw:
|
| 178 |
+
try:
|
| 179 |
+
key.decode(encoding)
|
| 180 |
+
value.decode(encoding)
|
| 181 |
+
except UnicodeDecodeError:
|
| 182 |
+
break
|
| 183 |
+
else:
|
| 184 |
+
# The else block runs if 'break' did not occur, meaning
|
| 185 |
+
# all values fitted the encoding.
|
| 186 |
+
self._encoding = encoding
|
| 187 |
+
break
|
| 188 |
+
else:
|
| 189 |
+
# The ISO-8859-1 encoding covers all 256 code points in a byte,
|
| 190 |
+
# so will never raise decode errors.
|
| 191 |
+
self._encoding = "iso-8859-1"
|
| 192 |
+
return self._encoding
|
| 193 |
+
|
| 194 |
+
@encoding.setter
|
| 195 |
+
def encoding(self, value: str) -> None:
|
| 196 |
+
self._encoding = value
|
| 197 |
+
|
| 198 |
+
@property
|
| 199 |
+
def raw(self) -> list[tuple[bytes, bytes]]:
|
| 200 |
+
"""
|
| 201 |
+
Returns a list of the raw header items, as byte pairs.
|
| 202 |
+
"""
|
| 203 |
+
return [(raw_key, value) for raw_key, _, value in self._list]
|
| 204 |
+
|
| 205 |
+
def keys(self) -> typing.KeysView[str]:
|
| 206 |
+
return {key.decode(self.encoding): None for _, key, _value in self._list}.keys()
|
| 207 |
+
|
| 208 |
+
def values(self) -> typing.ValuesView[str]:
|
| 209 |
+
values_dict: dict[str, str] = {}
|
| 210 |
+
for _, key, value in self._list:
|
| 211 |
+
str_key = key.decode(self.encoding)
|
| 212 |
+
str_value = value.decode(self.encoding)
|
| 213 |
+
if str_key in values_dict:
|
| 214 |
+
values_dict[str_key] += f", {str_value}"
|
| 215 |
+
else:
|
| 216 |
+
values_dict[str_key] = str_value
|
| 217 |
+
return values_dict.values()
|
| 218 |
+
|
| 219 |
+
def items(self) -> typing.ItemsView[str, str]:
|
| 220 |
+
"""
|
| 221 |
+
Return `(key, value)` items of headers. Concatenate headers
|
| 222 |
+
into a single comma separated value when a key occurs multiple times.
|
| 223 |
+
"""
|
| 224 |
+
values_dict: dict[str, str] = {}
|
| 225 |
+
for _, key, value in self._list:
|
| 226 |
+
str_key = key.decode(self.encoding)
|
| 227 |
+
str_value = value.decode(self.encoding)
|
| 228 |
+
if str_key in values_dict:
|
| 229 |
+
values_dict[str_key] += f", {str_value}"
|
| 230 |
+
else:
|
| 231 |
+
values_dict[str_key] = str_value
|
| 232 |
+
return values_dict.items()
|
| 233 |
+
|
| 234 |
+
def multi_items(self) -> list[tuple[str, str]]:
|
| 235 |
+
"""
|
| 236 |
+
Return a list of `(key, value)` pairs of headers. Allow multiple
|
| 237 |
+
occurrences of the same key without concatenating into a single
|
| 238 |
+
comma separated value.
|
| 239 |
+
"""
|
| 240 |
+
return [(key.decode(self.encoding), value.decode(self.encoding)) for _, key, value in self._list]
|
| 241 |
+
|
| 242 |
+
@typing.overload
|
| 243 |
+
def get(self, key: str, /) -> str | None: ...
|
| 244 |
+
|
| 245 |
+
@typing.overload
|
| 246 |
+
def get(self, key: str, default: _T) -> str | _T: ...
|
| 247 |
+
|
| 248 |
+
def get(self, key: str, default: _T | None = None) -> str | _T | None:
|
| 249 |
+
"""
|
| 250 |
+
Return a header value. If multiple occurrences of the header occur
|
| 251 |
+
then concatenate them together with commas.
|
| 252 |
+
"""
|
| 253 |
+
try:
|
| 254 |
+
return self[key]
|
| 255 |
+
except KeyError:
|
| 256 |
+
return default
|
| 257 |
+
|
| 258 |
+
def get_list(self, key: str, split_commas: bool = False) -> list[str]:
|
| 259 |
+
"""
|
| 260 |
+
Return a list of all header values for a given key.
|
| 261 |
+
If `split_commas=True` is passed, then any comma separated header
|
| 262 |
+
values are split into multiple return strings.
|
| 263 |
+
"""
|
| 264 |
+
get_header_key = key.lower().encode(self.encoding)
|
| 265 |
+
|
| 266 |
+
values = [
|
| 267 |
+
item_value.decode(self.encoding)
|
| 268 |
+
for _, item_key, item_value in self._list
|
| 269 |
+
if item_key.lower() == get_header_key
|
| 270 |
+
]
|
| 271 |
+
|
| 272 |
+
if not split_commas:
|
| 273 |
+
return values
|
| 274 |
+
|
| 275 |
+
split_values: list[str] = []
|
| 276 |
+
for value in values:
|
| 277 |
+
split_values.extend([item.strip() for item in value.split(",")])
|
| 278 |
+
return split_values
|
| 279 |
+
|
| 280 |
+
def update(self, headers: HeaderTypes | None = None) -> None: # type: ignore
|
| 281 |
+
headers = Headers(headers)
|
| 282 |
+
for key in headers.keys():
|
| 283 |
+
if key in self:
|
| 284 |
+
self.pop(key)
|
| 285 |
+
self._list.extend(headers._list)
|
| 286 |
+
|
| 287 |
+
def copy(self) -> Headers:
|
| 288 |
+
return Headers(self, encoding=self.encoding)
|
| 289 |
+
|
| 290 |
+
def __or__(self, other: Mapping[str, str]) -> Headers:
|
| 291 |
+
if not isinstance(other, Mapping):
|
| 292 |
+
return NotImplemented
|
| 293 |
+
merged = self.copy()
|
| 294 |
+
merged.update(other)
|
| 295 |
+
return merged
|
| 296 |
+
|
| 297 |
+
def __ror__(self, other: Mapping[str, str]) -> Headers:
|
| 298 |
+
if not isinstance(other, Mapping):
|
| 299 |
+
return NotImplemented
|
| 300 |
+
merged = Headers(other)
|
| 301 |
+
merged.update(self)
|
| 302 |
+
return merged
|
| 303 |
+
|
| 304 |
+
def __ior__(self, other: HeaderTypes) -> Headers:
|
| 305 |
+
self.update(other)
|
| 306 |
+
return self
|
| 307 |
+
|
| 308 |
+
def __getitem__(self, key: str) -> str:
|
| 309 |
+
"""
|
| 310 |
+
Return a single header value.
|
| 311 |
+
|
| 312 |
+
If there are multiple headers with the same key, then we concatenate
|
| 313 |
+
them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2
|
| 314 |
+
"""
|
| 315 |
+
normalized_key = key.lower().encode(self.encoding)
|
| 316 |
+
|
| 317 |
+
items = [
|
| 318 |
+
header_value.decode(self.encoding)
|
| 319 |
+
for _, header_key, header_value in self._list
|
| 320 |
+
if header_key == normalized_key
|
| 321 |
+
]
|
| 322 |
+
|
| 323 |
+
if items:
|
| 324 |
+
return ", ".join(items)
|
| 325 |
+
|
| 326 |
+
raise KeyError(key)
|
| 327 |
+
|
| 328 |
+
def __setitem__(self, key: str, value: str) -> None:
|
| 329 |
+
"""
|
| 330 |
+
Set the header `key` to `value`, removing any duplicate entries.
|
| 331 |
+
Retains insertion order.
|
| 332 |
+
"""
|
| 333 |
+
set_key = key.encode(self._encoding or "utf-8")
|
| 334 |
+
set_value = value.encode(self._encoding or "utf-8")
|
| 335 |
+
lookup_key = set_key.lower()
|
| 336 |
+
|
| 337 |
+
found_indexes = [idx for idx, (_, item_key, _) in enumerate(self._list) if item_key == lookup_key]
|
| 338 |
+
|
| 339 |
+
for idx in reversed(found_indexes[1:]):
|
| 340 |
+
del self._list[idx]
|
| 341 |
+
|
| 342 |
+
if found_indexes:
|
| 343 |
+
idx = found_indexes[0]
|
| 344 |
+
self._list[idx] = (set_key, lookup_key, set_value)
|
| 345 |
+
else:
|
| 346 |
+
self._list.append((set_key, lookup_key, set_value))
|
| 347 |
+
|
| 348 |
+
def __delitem__(self, key: str) -> None:
|
| 349 |
+
"""
|
| 350 |
+
Remove the header `key`.
|
| 351 |
+
"""
|
| 352 |
+
del_key = key.lower().encode(self.encoding)
|
| 353 |
+
|
| 354 |
+
pop_indexes = [idx for idx, (_, item_key, _) in enumerate(self._list) if item_key.lower() == del_key]
|
| 355 |
+
|
| 356 |
+
if not pop_indexes:
|
| 357 |
+
raise KeyError(key)
|
| 358 |
+
|
| 359 |
+
for idx in reversed(pop_indexes):
|
| 360 |
+
del self._list[idx]
|
| 361 |
+
|
| 362 |
+
def __contains__(self, key: typing.Any) -> bool:
|
| 363 |
+
header_key = key.lower().encode(self.encoding)
|
| 364 |
+
return header_key in [key for _, key, _ in self._list]
|
| 365 |
+
|
| 366 |
+
def __iter__(self) -> typing.Iterator[typing.Any]:
|
| 367 |
+
return iter(self.keys())
|
| 368 |
+
|
| 369 |
+
def __len__(self) -> int:
|
| 370 |
+
return len(self._list)
|
| 371 |
+
|
| 372 |
+
def __eq__(self, other: typing.Any) -> bool:
|
| 373 |
+
try:
|
| 374 |
+
other_headers = Headers(other)
|
| 375 |
+
except ValueError:
|
| 376 |
+
return False
|
| 377 |
+
|
| 378 |
+
self_list = [(key, value) for _, key, value in self._list]
|
| 379 |
+
other_list = [(key, value) for _, key, value in other_headers._list]
|
| 380 |
+
return sorted(self_list) == sorted(other_list)
|
| 381 |
+
|
| 382 |
+
def __repr__(self) -> str:
|
| 383 |
+
class_name = self.__class__.__name__
|
| 384 |
+
|
| 385 |
+
encoding_str = ""
|
| 386 |
+
if self.encoding != "ascii":
|
| 387 |
+
encoding_str = f", encoding={self.encoding!r}"
|
| 388 |
+
|
| 389 |
+
as_list = list(_obfuscate_sensitive_headers(self.multi_items()))
|
| 390 |
+
as_dict = dict(as_list)
|
| 391 |
+
|
| 392 |
+
no_duplicate_keys = len(as_dict) == len(as_list)
|
| 393 |
+
if no_duplicate_keys:
|
| 394 |
+
return f"{class_name}({as_dict!r}{encoding_str})"
|
| 395 |
+
return f"{class_name}({as_list!r}{encoding_str})"
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
class Request:
|
| 399 |
+
def __init__(
|
| 400 |
+
self,
|
| 401 |
+
method: str,
|
| 402 |
+
url: URL | str,
|
| 403 |
+
*,
|
| 404 |
+
params: QueryParamTypes | None = None,
|
| 405 |
+
headers: HeaderTypes | None = None,
|
| 406 |
+
cookies: CookieTypes | None = None,
|
| 407 |
+
content: RequestContent | None = None,
|
| 408 |
+
data: RequestData | None = None,
|
| 409 |
+
files: RequestFiles | None = None,
|
| 410 |
+
json: typing.Any | None = None,
|
| 411 |
+
stream: SyncByteStream | AsyncByteStream | None = None,
|
| 412 |
+
extensions: RequestExtensions | None = None,
|
| 413 |
+
) -> None:
|
| 414 |
+
self.method = method.upper()
|
| 415 |
+
self.url = URL(url) if params is None else URL(url, params=params)
|
| 416 |
+
self.headers = Headers(headers)
|
| 417 |
+
self.extensions = {} if extensions is None else dict(extensions)
|
| 418 |
+
|
| 419 |
+
if cookies:
|
| 420 |
+
(cookies if isinstance(cookies, Cookies) else Cookies(cookies)).set_cookie_header(self)
|
| 421 |
+
|
| 422 |
+
if stream is None:
|
| 423 |
+
content_type: str | None = self.headers.get("content-type")
|
| 424 |
+
headers, stream = encode_request(
|
| 425 |
+
content=content,
|
| 426 |
+
data=data,
|
| 427 |
+
files=files,
|
| 428 |
+
json=json,
|
| 429 |
+
boundary=get_multipart_boundary_from_content_type(
|
| 430 |
+
content_type=content_type.encode(self.headers.encoding) if content_type else None
|
| 431 |
+
),
|
| 432 |
+
)
|
| 433 |
+
self._prepare(headers)
|
| 434 |
+
self.stream = stream
|
| 435 |
+
# Load the request body, except for streaming content.
|
| 436 |
+
if isinstance(stream, ByteStream):
|
| 437 |
+
self.read()
|
| 438 |
+
else:
|
| 439 |
+
# There's an important distinction between `Request(content=...)`,
|
| 440 |
+
# and `Request(stream=...)`.
|
| 441 |
+
#
|
| 442 |
+
# Using `content=...` implies automatically populated `Host` and content
|
| 443 |
+
# headers, of either `Content-Length: ...` or `Transfer-Encoding: chunked`.
|
| 444 |
+
#
|
| 445 |
+
# Using `stream=...` will not automatically include *any*
|
| 446 |
+
# auto-populated headers.
|
| 447 |
+
#
|
| 448 |
+
# As an end-user you don't really need `stream=...`. It's only
|
| 449 |
+
# useful when:
|
| 450 |
+
#
|
| 451 |
+
# * Preserving the request stream when copying requests, eg for redirects.
|
| 452 |
+
# * Creating request instances on the *server-side* of the transport API.
|
| 453 |
+
self.stream = stream
|
| 454 |
+
|
| 455 |
+
def _prepare(self, default_headers: dict[str, str]) -> None:
|
| 456 |
+
for key, value in default_headers.items():
|
| 457 |
+
# Ignore Content-Length if Transfer-Encoding has been set explicitly.
|
| 458 |
+
if key.lower() == "content-length" and "Transfer-Encoding" in self.headers:
|
| 459 |
+
continue
|
| 460 |
+
# Ignore Transfer-Encoding if Content-Length has been set explicitly.
|
| 461 |
+
if key.lower() == "transfer-encoding" and "Content-Length" in self.headers:
|
| 462 |
+
continue
|
| 463 |
+
self.headers.setdefault(key, value)
|
| 464 |
+
|
| 465 |
+
auto_headers: list[tuple[bytes, bytes]] = []
|
| 466 |
+
|
| 467 |
+
has_host = "Host" in self.headers
|
| 468 |
+
has_content_length = "Content-Length" in self.headers or "Transfer-Encoding" in self.headers
|
| 469 |
+
|
| 470 |
+
if not has_host and self.url.host:
|
| 471 |
+
auto_headers.append((b"Host", self.url.netloc))
|
| 472 |
+
if not has_content_length and self.method in ("POST", "PUT", "PATCH", "QUERY"):
|
| 473 |
+
auto_headers.append((b"Content-Length", b"0"))
|
| 474 |
+
|
| 475 |
+
self.headers = Headers(auto_headers + self.headers.raw)
|
| 476 |
+
|
| 477 |
+
@property
|
| 478 |
+
def content(self) -> bytes:
|
| 479 |
+
if not hasattr(self, "_content"):
|
| 480 |
+
raise RequestNotRead()
|
| 481 |
+
return self._content
|
| 482 |
+
|
| 483 |
+
def read(self) -> bytes:
|
| 484 |
+
"""
|
| 485 |
+
Read and return the request content.
|
| 486 |
+
"""
|
| 487 |
+
if not hasattr(self, "_content"):
|
| 488 |
+
assert isinstance(self.stream, typing.Iterable)
|
| 489 |
+
self._content = b"".join(self.stream)
|
| 490 |
+
if not isinstance(self.stream, ByteStream):
|
| 491 |
+
# If a streaming request has been read entirely into memory, then
|
| 492 |
+
# we can replace the stream with a raw bytes implementation,
|
| 493 |
+
# to ensure that any non-replayable streams can still be used.
|
| 494 |
+
self.stream = ByteStream(self._content)
|
| 495 |
+
return self._content
|
| 496 |
+
|
| 497 |
+
async def aread(self) -> bytes:
|
| 498 |
+
"""
|
| 499 |
+
Read and return the request content.
|
| 500 |
+
"""
|
| 501 |
+
if not hasattr(self, "_content"):
|
| 502 |
+
assert isinstance(self.stream, typing.AsyncIterable)
|
| 503 |
+
self._content = b"".join([part async for part in self.stream])
|
| 504 |
+
if not isinstance(self.stream, ByteStream):
|
| 505 |
+
# If a streaming request has been read entirely into memory, then
|
| 506 |
+
# we can replace the stream with a raw bytes implementation,
|
| 507 |
+
# to ensure that any non-replayable streams can still be used.
|
| 508 |
+
self.stream = ByteStream(self._content)
|
| 509 |
+
return self._content
|
| 510 |
+
|
| 511 |
+
def __repr__(self) -> str:
|
| 512 |
+
class_name = self.__class__.__name__
|
| 513 |
+
url = str(self.url)
|
| 514 |
+
return f"<{class_name}({self.method!r}, {url!r})>"
|
| 515 |
+
|
| 516 |
+
def __getstate__(self) -> dict[str, typing.Any]:
|
| 517 |
+
return {name: value for name, value in self.__dict__.items() if name not in ["extensions", "stream"]}
|
| 518 |
+
|
| 519 |
+
def __setstate__(self, state: dict[str, typing.Any]) -> None:
|
| 520 |
+
for name, value in state.items():
|
| 521 |
+
setattr(self, name, value)
|
| 522 |
+
self.extensions = {}
|
| 523 |
+
self.stream = UnattachedStream()
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
class Response:
|
| 527 |
+
def __init__(
|
| 528 |
+
self,
|
| 529 |
+
status_code: int,
|
| 530 |
+
*,
|
| 531 |
+
headers: HeaderTypes | None = None,
|
| 532 |
+
content: ResponseContent | None = None,
|
| 533 |
+
text: str | None = None,
|
| 534 |
+
html: str | None = None,
|
| 535 |
+
json: typing.Any = None,
|
| 536 |
+
stream: SyncByteStream | AsyncByteStream | None = None,
|
| 537 |
+
request: Request | None = None,
|
| 538 |
+
extensions: ResponseExtensions | None = None,
|
| 539 |
+
history: list[Response] | None = None,
|
| 540 |
+
default_encoding: str | typing.Callable[[bytes], str | None] = "utf-8",
|
| 541 |
+
) -> None:
|
| 542 |
+
self.status_code = status_code
|
| 543 |
+
self.headers = Headers(headers)
|
| 544 |
+
|
| 545 |
+
self._request: Request | None = request
|
| 546 |
+
|
| 547 |
+
# When follow_redirects=False and a redirect is received,
|
| 548 |
+
# the client will set `response.next_request`.
|
| 549 |
+
self.next_request: Request | None = None
|
| 550 |
+
|
| 551 |
+
self.extensions = {} if extensions is None else dict(extensions)
|
| 552 |
+
self.history = [] if history is None else list(history)
|
| 553 |
+
|
| 554 |
+
self.is_closed = False
|
| 555 |
+
self.is_stream_consumed = False
|
| 556 |
+
|
| 557 |
+
self.default_encoding = default_encoding
|
| 558 |
+
|
| 559 |
+
if stream is None:
|
| 560 |
+
headers, stream = encode_response(content, text, html, json)
|
| 561 |
+
self._prepare(headers)
|
| 562 |
+
self.stream = stream
|
| 563 |
+
if isinstance(stream, ByteStream):
|
| 564 |
+
# Load the response body, except for streaming content.
|
| 565 |
+
self.read()
|
| 566 |
+
else:
|
| 567 |
+
# There's an important distinction between `Response(content=...)`,
|
| 568 |
+
# and `Response(stream=...)`.
|
| 569 |
+
#
|
| 570 |
+
# Using `content=...` implies automatically populated content headers,
|
| 571 |
+
# of either `Content-Length: ...` or `Transfer-Encoding: chunked`.
|
| 572 |
+
#
|
| 573 |
+
# Using `stream=...` will not automatically include any content headers.
|
| 574 |
+
#
|
| 575 |
+
# As an end-user you don't really need `stream=...`. It's only
|
| 576 |
+
# useful when creating response instances having received a stream
|
| 577 |
+
# from the transport API.
|
| 578 |
+
self.stream = stream
|
| 579 |
+
|
| 580 |
+
self._num_bytes_downloaded = 0
|
| 581 |
+
|
| 582 |
+
def _prepare(self, default_headers: dict[str, str]) -> None:
|
| 583 |
+
for key, value in default_headers.items():
|
| 584 |
+
# Ignore Transfer-Encoding if the Content-Length has been set explicitly.
|
| 585 |
+
if key.lower() == "transfer-encoding" and "content-length" in self.headers:
|
| 586 |
+
continue
|
| 587 |
+
self.headers.setdefault(key, value)
|
| 588 |
+
|
| 589 |
+
@property
|
| 590 |
+
def elapsed(self) -> datetime.timedelta:
|
| 591 |
+
"""
|
| 592 |
+
Returns the time taken for the complete request/response
|
| 593 |
+
cycle to complete.
|
| 594 |
+
"""
|
| 595 |
+
if not hasattr(self, "_elapsed"):
|
| 596 |
+
stream_elapsed: datetime.timedelta | None = getattr(self.stream, "elapsed", None)
|
| 597 |
+
if stream_elapsed is not None:
|
| 598 |
+
return stream_elapsed
|
| 599 |
+
raise RuntimeError("'.elapsed' may only be accessed after the response has been read or closed.")
|
| 600 |
+
return self._elapsed
|
| 601 |
+
|
| 602 |
+
@elapsed.setter
|
| 603 |
+
def elapsed(self, elapsed: datetime.timedelta) -> None:
|
| 604 |
+
self._elapsed = elapsed
|
| 605 |
+
|
| 606 |
+
@property
|
| 607 |
+
def request(self) -> Request:
|
| 608 |
+
"""
|
| 609 |
+
Returns the request instance associated to the current response.
|
| 610 |
+
"""
|
| 611 |
+
if self._request is None:
|
| 612 |
+
raise RuntimeError("The request instance has not been set on this response.")
|
| 613 |
+
return self._request
|
| 614 |
+
|
| 615 |
+
@request.setter
|
| 616 |
+
def request(self, value: Request) -> None:
|
| 617 |
+
self._request = value
|
| 618 |
+
|
| 619 |
+
@property
|
| 620 |
+
def http_version(self) -> str:
|
| 621 |
+
try:
|
| 622 |
+
http_version: bytes = self.extensions["http_version"]
|
| 623 |
+
except KeyError:
|
| 624 |
+
return "HTTP/1.1"
|
| 625 |
+
else:
|
| 626 |
+
return http_version.decode("ascii", errors="ignore")
|
| 627 |
+
|
| 628 |
+
@property
|
| 629 |
+
def reason_phrase(self) -> str:
|
| 630 |
+
try:
|
| 631 |
+
reason_phrase: bytes = self.extensions["reason_phrase"]
|
| 632 |
+
except KeyError:
|
| 633 |
+
return codes.get_reason_phrase(self.status_code)
|
| 634 |
+
else:
|
| 635 |
+
return reason_phrase.decode("ascii", errors="ignore")
|
| 636 |
+
|
| 637 |
+
@property
|
| 638 |
+
def url(self) -> URL:
|
| 639 |
+
"""
|
| 640 |
+
Returns the URL for which the request was made.
|
| 641 |
+
"""
|
| 642 |
+
return self.request.url
|
| 643 |
+
|
| 644 |
+
@property
|
| 645 |
+
def content(self) -> bytes:
|
| 646 |
+
if not hasattr(self, "_content"):
|
| 647 |
+
raise ResponseNotRead()
|
| 648 |
+
return self._content
|
| 649 |
+
|
| 650 |
+
@property
|
| 651 |
+
def text(self) -> str:
|
| 652 |
+
if not hasattr(self, "_text"):
|
| 653 |
+
content = self.content
|
| 654 |
+
if not content:
|
| 655 |
+
self._text = ""
|
| 656 |
+
else:
|
| 657 |
+
decoder = TextDecoder(encoding=self.encoding or "utf-8")
|
| 658 |
+
self._text = "".join([decoder.decode(self.content), decoder.flush()])
|
| 659 |
+
return self._text
|
| 660 |
+
|
| 661 |
+
@property
|
| 662 |
+
def encoding(self) -> str | None:
|
| 663 |
+
"""
|
| 664 |
+
Return an encoding to use for decoding the byte content into text.
|
| 665 |
+
The priority for determining this is given by...
|
| 666 |
+
|
| 667 |
+
* `.encoding = <>` has been set explicitly.
|
| 668 |
+
* The encoding as specified by the charset parameter in the Content-Type header.
|
| 669 |
+
* The encoding as determined by `default_encoding`, which may either be
|
| 670 |
+
a string like "utf-8" indicating the encoding to use, or may be a callable
|
| 671 |
+
which enables charset autodetection.
|
| 672 |
+
"""
|
| 673 |
+
if not hasattr(self, "_encoding"):
|
| 674 |
+
encoding = self.charset_encoding
|
| 675 |
+
if encoding is None or not _is_known_encoding(encoding):
|
| 676 |
+
if isinstance(self.default_encoding, str):
|
| 677 |
+
encoding = self.default_encoding
|
| 678 |
+
elif hasattr(self, "_content"):
|
| 679 |
+
encoding = self.default_encoding(self._content)
|
| 680 |
+
self._encoding = encoding or "utf-8"
|
| 681 |
+
return self._encoding
|
| 682 |
+
|
| 683 |
+
@encoding.setter
|
| 684 |
+
def encoding(self, value: str) -> None:
|
| 685 |
+
"""
|
| 686 |
+
Set the encoding to use for decoding the byte content into text.
|
| 687 |
+
|
| 688 |
+
If the `text` attribute has been accessed, attempting to set the
|
| 689 |
+
encoding will throw a ValueError.
|
| 690 |
+
"""
|
| 691 |
+
if hasattr(self, "_text"):
|
| 692 |
+
raise ValueError("Setting encoding after `text` has been accessed is not allowed.")
|
| 693 |
+
self._encoding = value
|
| 694 |
+
|
| 695 |
+
@property
|
| 696 |
+
def charset_encoding(self) -> str | None:
|
| 697 |
+
"""
|
| 698 |
+
Return the encoding, as specified by the Content-Type header.
|
| 699 |
+
"""
|
| 700 |
+
content_type = self.headers.get("Content-Type")
|
| 701 |
+
if content_type is None:
|
| 702 |
+
return None
|
| 703 |
+
|
| 704 |
+
return _parse_content_type_charset(content_type)
|
| 705 |
+
|
| 706 |
+
def _get_content_decoder(self) -> ContentDecoder:
|
| 707 |
+
"""
|
| 708 |
+
Returns a decoder instance which can be used to decode the raw byte
|
| 709 |
+
content, depending on the Content-Encoding used in the response.
|
| 710 |
+
"""
|
| 711 |
+
if not hasattr(self, "_decoder"):
|
| 712 |
+
values = self.headers.get_list("content-encoding", split_commas=True)
|
| 713 |
+
encodings = [value.strip().lower() for value in values]
|
| 714 |
+
decoder = MultiDecoder([encoding for encoding in encodings if encoding != "identity"])
|
| 715 |
+
if len(decoder.children) == 1:
|
| 716 |
+
self._decoder = decoder.children[0]
|
| 717 |
+
elif decoder.children:
|
| 718 |
+
self._decoder = decoder
|
| 719 |
+
else:
|
| 720 |
+
self._decoder = IdentityDecoder()
|
| 721 |
+
|
| 722 |
+
return self._decoder
|
| 723 |
+
|
| 724 |
+
@property
|
| 725 |
+
def is_informational(self) -> bool:
|
| 726 |
+
"""
|
| 727 |
+
A property which is `True` for 1xx status codes, `False` otherwise.
|
| 728 |
+
"""
|
| 729 |
+
return codes.is_informational(self.status_code)
|
| 730 |
+
|
| 731 |
+
@property
|
| 732 |
+
def is_success(self) -> bool:
|
| 733 |
+
"""
|
| 734 |
+
A property which is `True` for 2xx status codes, `False` otherwise.
|
| 735 |
+
"""
|
| 736 |
+
return codes.is_success(self.status_code)
|
| 737 |
+
|
| 738 |
+
@property
|
| 739 |
+
def is_redirect(self) -> bool:
|
| 740 |
+
"""
|
| 741 |
+
A property which is `True` for 3xx status codes, `False` otherwise.
|
| 742 |
+
|
| 743 |
+
Note that not all responses with a 3xx status code indicate a URL redirect.
|
| 744 |
+
|
| 745 |
+
Use `response.has_redirect_location` to determine responses with a properly
|
| 746 |
+
formed URL redirection.
|
| 747 |
+
"""
|
| 748 |
+
return codes.is_redirect(self.status_code)
|
| 749 |
+
|
| 750 |
+
@property
|
| 751 |
+
def is_client_error(self) -> bool:
|
| 752 |
+
"""
|
| 753 |
+
A property which is `True` for 4xx status codes, `False` otherwise.
|
| 754 |
+
"""
|
| 755 |
+
return codes.is_client_error(self.status_code)
|
| 756 |
+
|
| 757 |
+
@property
|
| 758 |
+
def is_server_error(self) -> bool:
|
| 759 |
+
"""
|
| 760 |
+
A property which is `True` for 5xx status codes, `False` otherwise.
|
| 761 |
+
"""
|
| 762 |
+
return codes.is_server_error(self.status_code)
|
| 763 |
+
|
| 764 |
+
@property
|
| 765 |
+
def is_error(self) -> bool:
|
| 766 |
+
"""
|
| 767 |
+
A property which is `True` for 4xx and 5xx status codes, `False` otherwise.
|
| 768 |
+
"""
|
| 769 |
+
return codes.is_error(self.status_code)
|
| 770 |
+
|
| 771 |
+
@property
|
| 772 |
+
def has_redirect_location(self) -> bool:
|
| 773 |
+
"""
|
| 774 |
+
Returns True for 3xx responses with a properly formed URL redirection,
|
| 775 |
+
`False` otherwise.
|
| 776 |
+
"""
|
| 777 |
+
return (
|
| 778 |
+
self.status_code
|
| 779 |
+
in (
|
| 780 |
+
# 301 (Cacheable redirect. Method may change to GET.)
|
| 781 |
+
codes.MOVED_PERMANENTLY,
|
| 782 |
+
# 302 (Uncacheable redirect. Method may change to GET.)
|
| 783 |
+
codes.FOUND,
|
| 784 |
+
# 303 (Client should make a GET or HEAD request.)
|
| 785 |
+
codes.SEE_OTHER,
|
| 786 |
+
# 307 (Equiv. 302, but retain method)
|
| 787 |
+
codes.TEMPORARY_REDIRECT,
|
| 788 |
+
# 308 (Equiv. 301, but retain method)
|
| 789 |
+
codes.PERMANENT_REDIRECT,
|
| 790 |
+
)
|
| 791 |
+
and "Location" in self.headers
|
| 792 |
+
)
|
| 793 |
+
|
| 794 |
+
def raise_for_status(self) -> Response:
|
| 795 |
+
"""
|
| 796 |
+
Raise the `HTTPStatusError` if one occurred.
|
| 797 |
+
"""
|
| 798 |
+
request = self._request
|
| 799 |
+
if request is None:
|
| 800 |
+
raise RuntimeError(
|
| 801 |
+
"Cannot call `raise_for_status` as the request instance has not been set on this response."
|
| 802 |
+
)
|
| 803 |
+
|
| 804 |
+
if self.is_success:
|
| 805 |
+
return self
|
| 806 |
+
|
| 807 |
+
if self.has_redirect_location:
|
| 808 |
+
message = (
|
| 809 |
+
"{error_type} '{0.status_code} {0.reason_phrase}' for url '{0.url}'\n"
|
| 810 |
+
"Redirect location: '{0.headers[location]}'\n"
|
| 811 |
+
"For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/{0.status_code}"
|
| 812 |
+
)
|
| 813 |
+
else:
|
| 814 |
+
message = (
|
| 815 |
+
"{error_type} '{0.status_code} {0.reason_phrase}' for url '{0.url}'\n"
|
| 816 |
+
"For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/{0.status_code}"
|
| 817 |
+
)
|
| 818 |
+
|
| 819 |
+
status_class = self.status_code // 100
|
| 820 |
+
error_types = {
|
| 821 |
+
1: "Informational response",
|
| 822 |
+
3: "Redirect response",
|
| 823 |
+
4: "Client error",
|
| 824 |
+
5: "Server error",
|
| 825 |
+
}
|
| 826 |
+
error_type = error_types.get(status_class, "Invalid status code")
|
| 827 |
+
message = message.format(self, error_type=error_type)
|
| 828 |
+
raise HTTPStatusError(message, request=request, response=self)
|
| 829 |
+
|
| 830 |
+
def json(self, **kwargs: typing.Any) -> typing.Any:
|
| 831 |
+
return jsonlib.loads(self.content, **kwargs)
|
| 832 |
+
|
| 833 |
+
@property
|
| 834 |
+
def cookies(self) -> Cookies:
|
| 835 |
+
if not hasattr(self, "_cookies"):
|
| 836 |
+
self._cookies = Cookies()
|
| 837 |
+
self._cookies.extract_cookies(self)
|
| 838 |
+
return self._cookies
|
| 839 |
+
|
| 840 |
+
@property
|
| 841 |
+
def links(self) -> dict[str | None, dict[str, str]]:
|
| 842 |
+
"""
|
| 843 |
+
Returns the parsed header links of the response, if any
|
| 844 |
+
"""
|
| 845 |
+
header = self.headers.get("link")
|
| 846 |
+
if header is None:
|
| 847 |
+
return {}
|
| 848 |
+
|
| 849 |
+
return {(link.get("rel") or link.get("url")): link for link in _parse_header_links(header)}
|
| 850 |
+
|
| 851 |
+
@property
|
| 852 |
+
def num_bytes_downloaded(self) -> int:
|
| 853 |
+
return self._num_bytes_downloaded
|
| 854 |
+
|
| 855 |
+
def __repr__(self) -> str:
|
| 856 |
+
return f"<Response [{self.status_code} {self.reason_phrase}]>"
|
| 857 |
+
|
| 858 |
+
def __getstate__(self) -> dict[str, typing.Any]:
|
| 859 |
+
return {
|
| 860 |
+
name: value
|
| 861 |
+
for name, value in self.__dict__.items()
|
| 862 |
+
if name not in ["extensions", "stream", "is_closed", "_decoder"]
|
| 863 |
+
}
|
| 864 |
+
|
| 865 |
+
def __setstate__(self, state: dict[str, typing.Any]) -> None:
|
| 866 |
+
for name, value in state.items():
|
| 867 |
+
setattr(self, name, value)
|
| 868 |
+
self.is_closed = True
|
| 869 |
+
self.extensions = {}
|
| 870 |
+
self.stream = UnattachedStream()
|
| 871 |
+
|
| 872 |
+
def read(self) -> bytes:
|
| 873 |
+
"""
|
| 874 |
+
Read and return the response content.
|
| 875 |
+
"""
|
| 876 |
+
if not hasattr(self, "_content"):
|
| 877 |
+
self._content = b"".join(self.iter_bytes())
|
| 878 |
+
return self._content
|
| 879 |
+
|
| 880 |
+
def iter_bytes(self, chunk_size: int | None = None) -> typing.Iterator[bytes]:
|
| 881 |
+
"""
|
| 882 |
+
A byte-iterator over the decoded response content.
|
| 883 |
+
This allows us to handle gzip, deflate, brotli, and zstd encoded responses.
|
| 884 |
+
"""
|
| 885 |
+
if hasattr(self, "_content"):
|
| 886 |
+
chunk_size = len(self._content) if chunk_size is None else chunk_size
|
| 887 |
+
for i in range(0, len(self._content), max(chunk_size, 1)):
|
| 888 |
+
yield self._content[i : i + chunk_size]
|
| 889 |
+
else:
|
| 890 |
+
decoder = self._get_content_decoder()
|
| 891 |
+
chunker = ByteChunker(chunk_size=chunk_size)
|
| 892 |
+
with request_context(request=self._request):
|
| 893 |
+
for raw_bytes in self.iter_raw():
|
| 894 |
+
for decoded in decoder.decode(raw_bytes):
|
| 895 |
+
for chunk in chunker.decode(decoded):
|
| 896 |
+
yield chunk
|
| 897 |
+
for decoded in decoder.flush():
|
| 898 |
+
for chunk in chunker.decode(decoded):
|
| 899 |
+
yield chunk # pragma: no cover
|
| 900 |
+
for chunk in chunker.flush():
|
| 901 |
+
yield chunk
|
| 902 |
+
|
| 903 |
+
def iter_text(self, chunk_size: int | None = None) -> typing.Iterator[str]:
|
| 904 |
+
"""
|
| 905 |
+
A str-iterator over the decoded response content
|
| 906 |
+
that handles both gzip, deflate, etc but also detects the content's
|
| 907 |
+
string encoding.
|
| 908 |
+
"""
|
| 909 |
+
decoder = TextDecoder(encoding=self.encoding or "utf-8")
|
| 910 |
+
chunker = TextChunker(chunk_size=chunk_size)
|
| 911 |
+
with request_context(request=self._request):
|
| 912 |
+
for byte_content in self.iter_bytes():
|
| 913 |
+
text_content = decoder.decode(byte_content)
|
| 914 |
+
for chunk in chunker.decode(text_content):
|
| 915 |
+
yield chunk
|
| 916 |
+
text_content = decoder.flush()
|
| 917 |
+
for chunk in chunker.decode(text_content):
|
| 918 |
+
yield chunk # pragma: no cover
|
| 919 |
+
for chunk in chunker.flush():
|
| 920 |
+
yield chunk
|
| 921 |
+
|
| 922 |
+
def iter_lines(self) -> typing.Iterator[str]:
|
| 923 |
+
decoder = LineDecoder()
|
| 924 |
+
with request_context(request=self._request):
|
| 925 |
+
for text in self.iter_text():
|
| 926 |
+
for line in decoder.decode(text):
|
| 927 |
+
yield line
|
| 928 |
+
for line in decoder.flush():
|
| 929 |
+
yield line
|
| 930 |
+
|
| 931 |
+
def iter_raw(self, chunk_size: int | None = None) -> typing.Iterator[bytes]:
|
| 932 |
+
"""
|
| 933 |
+
A byte-iterator over the raw response content.
|
| 934 |
+
"""
|
| 935 |
+
if self.is_stream_consumed:
|
| 936 |
+
raise StreamConsumed()
|
| 937 |
+
if self.is_closed:
|
| 938 |
+
raise StreamClosed()
|
| 939 |
+
if not isinstance(self.stream, SyncByteStream):
|
| 940 |
+
raise RuntimeError("Attempted to call a sync iterator on an async stream.")
|
| 941 |
+
|
| 942 |
+
self.is_stream_consumed = True
|
| 943 |
+
self._num_bytes_downloaded = 0
|
| 944 |
+
chunker = ByteChunker(chunk_size=chunk_size)
|
| 945 |
+
|
| 946 |
+
try:
|
| 947 |
+
with request_context(request=self._request):
|
| 948 |
+
for raw_stream_bytes in self.stream:
|
| 949 |
+
self._num_bytes_downloaded += len(raw_stream_bytes)
|
| 950 |
+
for chunk in chunker.decode(raw_stream_bytes):
|
| 951 |
+
yield chunk
|
| 952 |
+
|
| 953 |
+
for chunk in chunker.flush():
|
| 954 |
+
yield chunk
|
| 955 |
+
finally:
|
| 956 |
+
self.close()
|
| 957 |
+
|
| 958 |
+
def close(self) -> None:
|
| 959 |
+
"""
|
| 960 |
+
Close the response and release the connection.
|
| 961 |
+
Automatically called if the response body is read to completion.
|
| 962 |
+
"""
|
| 963 |
+
if not isinstance(self.stream, SyncByteStream):
|
| 964 |
+
raise RuntimeError("Attempted to call a sync close on an async stream.")
|
| 965 |
+
|
| 966 |
+
if not self.is_closed:
|
| 967 |
+
self.is_closed = True
|
| 968 |
+
with request_context(request=self._request):
|
| 969 |
+
self.stream.close()
|
| 970 |
+
|
| 971 |
+
async def aread(self) -> bytes:
|
| 972 |
+
"""
|
| 973 |
+
Read and return the response content.
|
| 974 |
+
"""
|
| 975 |
+
if not hasattr(self, "_content"):
|
| 976 |
+
async with contextlib.aclosing(self.aiter_bytes()) as parts:
|
| 977 |
+
self._content = b"".join([part async for part in parts])
|
| 978 |
+
return self._content
|
| 979 |
+
|
| 980 |
+
async def aiter_bytes(self, chunk_size: int | None = None) -> typing.AsyncGenerator[bytes, None]:
|
| 981 |
+
"""
|
| 982 |
+
A byte-iterator over the decoded response content.
|
| 983 |
+
This allows us to handle gzip, deflate, brotli, and zstd encoded responses.
|
| 984 |
+
"""
|
| 985 |
+
if hasattr(self, "_content"):
|
| 986 |
+
chunk_size = len(self._content) if chunk_size is None else chunk_size
|
| 987 |
+
for i in range(0, len(self._content), max(chunk_size, 1)):
|
| 988 |
+
yield self._content[i : i + chunk_size]
|
| 989 |
+
else:
|
| 990 |
+
decoder = self._get_content_decoder()
|
| 991 |
+
chunker = ByteChunker(chunk_size=chunk_size)
|
| 992 |
+
with request_context(request=self._request):
|
| 993 |
+
async with contextlib.aclosing(self.aiter_raw()) as raw_stream:
|
| 994 |
+
async for raw_bytes in raw_stream:
|
| 995 |
+
for decoded in decoder.decode(raw_bytes):
|
| 996 |
+
for chunk in chunker.decode(decoded):
|
| 997 |
+
yield chunk
|
| 998 |
+
for decoded in decoder.flush():
|
| 999 |
+
for chunk in chunker.decode(decoded):
|
| 1000 |
+
yield chunk # pragma: no cover
|
| 1001 |
+
for chunk in chunker.flush():
|
| 1002 |
+
yield chunk
|
| 1003 |
+
|
| 1004 |
+
async def aiter_text(self, chunk_size: int | None = None) -> typing.AsyncIterator[str]:
|
| 1005 |
+
"""
|
| 1006 |
+
A str-iterator over the decoded response content
|
| 1007 |
+
that handles both gzip, deflate, etc but also detects the content's
|
| 1008 |
+
string encoding.
|
| 1009 |
+
"""
|
| 1010 |
+
decoder = TextDecoder(encoding=self.encoding or "utf-8")
|
| 1011 |
+
chunker = TextChunker(chunk_size=chunk_size)
|
| 1012 |
+
with request_context(request=self._request):
|
| 1013 |
+
async for byte_content in self.aiter_bytes():
|
| 1014 |
+
text_content = decoder.decode(byte_content)
|
| 1015 |
+
for chunk in chunker.decode(text_content):
|
| 1016 |
+
yield chunk
|
| 1017 |
+
text_content = decoder.flush()
|
| 1018 |
+
for chunk in chunker.decode(text_content):
|
| 1019 |
+
yield chunk # pragma: no cover
|
| 1020 |
+
for chunk in chunker.flush():
|
| 1021 |
+
yield chunk
|
| 1022 |
+
|
| 1023 |
+
async def aiter_lines(self) -> typing.AsyncIterator[str]:
|
| 1024 |
+
decoder = LineDecoder()
|
| 1025 |
+
with request_context(request=self._request):
|
| 1026 |
+
async for text in self.aiter_text():
|
| 1027 |
+
for line in decoder.decode(text):
|
| 1028 |
+
yield line
|
| 1029 |
+
for line in decoder.flush():
|
| 1030 |
+
yield line
|
| 1031 |
+
|
| 1032 |
+
async def aiter_raw(self, chunk_size: int | None = None) -> typing.AsyncGenerator[bytes, None]:
|
| 1033 |
+
"""
|
| 1034 |
+
A byte-iterator over the raw response content.
|
| 1035 |
+
"""
|
| 1036 |
+
if self.is_stream_consumed:
|
| 1037 |
+
raise StreamConsumed()
|
| 1038 |
+
if self.is_closed:
|
| 1039 |
+
raise StreamClosed()
|
| 1040 |
+
if not isinstance(self.stream, AsyncByteStream):
|
| 1041 |
+
raise RuntimeError("Attempted to call an async iterator on a sync stream.")
|
| 1042 |
+
|
| 1043 |
+
self.is_stream_consumed = True
|
| 1044 |
+
self._num_bytes_downloaded = 0
|
| 1045 |
+
chunker = ByteChunker(chunk_size=chunk_size)
|
| 1046 |
+
|
| 1047 |
+
stream = self.stream.__aiter__()
|
| 1048 |
+
try:
|
| 1049 |
+
with request_context(request=self._request):
|
| 1050 |
+
async for raw_stream_bytes in stream:
|
| 1051 |
+
self._num_bytes_downloaded += len(raw_stream_bytes)
|
| 1052 |
+
for chunk in chunker.decode(raw_stream_bytes):
|
| 1053 |
+
yield chunk
|
| 1054 |
+
|
| 1055 |
+
for chunk in chunker.flush():
|
| 1056 |
+
yield chunk
|
| 1057 |
+
finally:
|
| 1058 |
+
if isinstance(stream, AsyncGenerator):
|
| 1059 |
+
await stream.aclose()
|
| 1060 |
+
await self.aclose()
|
| 1061 |
+
|
| 1062 |
+
async def aclose(self) -> None:
|
| 1063 |
+
"""
|
| 1064 |
+
Close the response and release the connection.
|
| 1065 |
+
Automatically called if the response body is read to completion.
|
| 1066 |
+
"""
|
| 1067 |
+
if not isinstance(self.stream, AsyncByteStream):
|
| 1068 |
+
raise RuntimeError("Attempted to call an async close on a sync stream.")
|
| 1069 |
+
|
| 1070 |
+
if not self.is_closed:
|
| 1071 |
+
self.is_closed = True
|
| 1072 |
+
with request_context(request=self._request):
|
| 1073 |
+
await self.stream.aclose()
|
| 1074 |
+
|
| 1075 |
+
|
| 1076 |
+
class Cookies(typing.MutableMapping[str, str]):
|
| 1077 |
+
"""
|
| 1078 |
+
HTTP Cookies, as a mutable mapping.
|
| 1079 |
+
"""
|
| 1080 |
+
|
| 1081 |
+
def __init__(self, cookies: CookieTypes | None = None) -> None:
|
| 1082 |
+
if cookies is None or isinstance(cookies, dict):
|
| 1083 |
+
self.jar: CookieJar = IndexedCookieJar()
|
| 1084 |
+
if isinstance(cookies, dict):
|
| 1085 |
+
for key, value in cookies.items():
|
| 1086 |
+
self.set(key, value)
|
| 1087 |
+
elif isinstance(cookies, list):
|
| 1088 |
+
self.jar = IndexedCookieJar()
|
| 1089 |
+
for key, value in cookies:
|
| 1090 |
+
self.set(key, value)
|
| 1091 |
+
elif isinstance(cookies, Cookies):
|
| 1092 |
+
self.jar = IndexedCookieJar()
|
| 1093 |
+
for cookie in cookies.jar:
|
| 1094 |
+
self.jar.set_cookie(cookie)
|
| 1095 |
+
else:
|
| 1096 |
+
self.jar = cookies
|
| 1097 |
+
|
| 1098 |
+
def extract_cookies(self, response: Response) -> None:
|
| 1099 |
+
"""
|
| 1100 |
+
Loads any cookies based on the response `Set-Cookie` headers.
|
| 1101 |
+
"""
|
| 1102 |
+
if "set-cookie" not in response.headers and "set-cookie2" not in response.headers:
|
| 1103 |
+
return
|
| 1104 |
+
|
| 1105 |
+
urllib_response = self._CookieCompatResponse(response)
|
| 1106 |
+
urllib_request = self._CookieCompatRequest(response.request)
|
| 1107 |
+
|
| 1108 |
+
self.jar.extract_cookies(urllib_response, urllib_request) # type: ignore
|
| 1109 |
+
|
| 1110 |
+
def set_cookie_header(self, request: Request) -> None:
|
| 1111 |
+
"""
|
| 1112 |
+
Sets an appropriate 'Cookie:' HTTP header on the `Request`.
|
| 1113 |
+
"""
|
| 1114 |
+
urllib_request = self._CookieCompatRequest(request)
|
| 1115 |
+
self.jar.add_cookie_header(urllib_request)
|
| 1116 |
+
|
| 1117 |
+
def set(self, name: str, value: str, domain: str = "", path: str = "/") -> None:
|
| 1118 |
+
"""
|
| 1119 |
+
Set a cookie value by name. May optionally include domain and path.
|
| 1120 |
+
"""
|
| 1121 |
+
kwargs = {
|
| 1122 |
+
"version": 0,
|
| 1123 |
+
"name": name,
|
| 1124 |
+
"value": value,
|
| 1125 |
+
"port": None,
|
| 1126 |
+
"port_specified": False,
|
| 1127 |
+
"domain": domain,
|
| 1128 |
+
"domain_specified": bool(domain),
|
| 1129 |
+
"domain_initial_dot": domain.startswith("."),
|
| 1130 |
+
"path": path,
|
| 1131 |
+
"path_specified": bool(path),
|
| 1132 |
+
"secure": False,
|
| 1133 |
+
"expires": None,
|
| 1134 |
+
"discard": True,
|
| 1135 |
+
"comment": None,
|
| 1136 |
+
"comment_url": None,
|
| 1137 |
+
"rest": {"HttpOnly": None},
|
| 1138 |
+
"rfc2109": False,
|
| 1139 |
+
}
|
| 1140 |
+
cookie = Cookie(**kwargs) # type: ignore
|
| 1141 |
+
self.jar.set_cookie(cookie)
|
| 1142 |
+
|
| 1143 |
+
def get( # type: ignore
|
| 1144 |
+
self,
|
| 1145 |
+
name: str,
|
| 1146 |
+
default: str | None = None,
|
| 1147 |
+
domain: str | None = None,
|
| 1148 |
+
path: str | None = None,
|
| 1149 |
+
) -> str | None:
|
| 1150 |
+
"""
|
| 1151 |
+
Get a cookie by name. May optionally include domain and path
|
| 1152 |
+
in order to specify exactly which cookie to retrieve.
|
| 1153 |
+
"""
|
| 1154 |
+
value = None
|
| 1155 |
+
for cookie in self.jar:
|
| 1156 |
+
if cookie.name == name:
|
| 1157 |
+
if domain is None or cookie.domain == domain:
|
| 1158 |
+
if path is None or cookie.path == path:
|
| 1159 |
+
if value is not None:
|
| 1160 |
+
message = f"Multiple cookies exist with name={name}"
|
| 1161 |
+
raise CookieConflict(message)
|
| 1162 |
+
value = cookie.value
|
| 1163 |
+
|
| 1164 |
+
if value is None:
|
| 1165 |
+
return default
|
| 1166 |
+
return value
|
| 1167 |
+
|
| 1168 |
+
def delete(
|
| 1169 |
+
self,
|
| 1170 |
+
name: str,
|
| 1171 |
+
domain: str | None = None,
|
| 1172 |
+
path: str | None = None,
|
| 1173 |
+
) -> None:
|
| 1174 |
+
"""
|
| 1175 |
+
Delete a cookie by name. May optionally include domain and path
|
| 1176 |
+
in order to specify exactly which cookie to delete.
|
| 1177 |
+
"""
|
| 1178 |
+
if domain is not None and path is not None:
|
| 1179 |
+
return self.jar.clear(domain, path, name)
|
| 1180 |
+
|
| 1181 |
+
remove = [
|
| 1182 |
+
cookie
|
| 1183 |
+
for cookie in self.jar
|
| 1184 |
+
if cookie.name == name
|
| 1185 |
+
and (domain is None or cookie.domain == domain)
|
| 1186 |
+
and (path is None or cookie.path == path)
|
| 1187 |
+
]
|
| 1188 |
+
|
| 1189 |
+
for cookie in remove:
|
| 1190 |
+
self.jar.clear(cookie.domain, cookie.path, cookie.name)
|
| 1191 |
+
|
| 1192 |
+
def clear(self, domain: str | None = None, path: str | None = None) -> None:
|
| 1193 |
+
"""
|
| 1194 |
+
Delete all cookies. Optionally include a domain and path in
|
| 1195 |
+
order to only delete a subset of all the cookies.
|
| 1196 |
+
"""
|
| 1197 |
+
args: list[str] = []
|
| 1198 |
+
if domain is not None:
|
| 1199 |
+
args.append(domain)
|
| 1200 |
+
if path is not None:
|
| 1201 |
+
assert domain is not None
|
| 1202 |
+
args.append(path)
|
| 1203 |
+
self.jar.clear(*args)
|
| 1204 |
+
|
| 1205 |
+
def update(self, cookies: CookieTypes | None = None) -> None: # type: ignore
|
| 1206 |
+
cookies = Cookies(cookies)
|
| 1207 |
+
for cookie in cookies.jar:
|
| 1208 |
+
self.jar.set_cookie(cookie)
|
| 1209 |
+
|
| 1210 |
+
def __setitem__(self, name: str, value: str) -> None:
|
| 1211 |
+
return self.set(name, value)
|
| 1212 |
+
|
| 1213 |
+
def __getitem__(self, name: str) -> str:
|
| 1214 |
+
value = self.get(name)
|
| 1215 |
+
if value is None:
|
| 1216 |
+
raise KeyError(name)
|
| 1217 |
+
return value
|
| 1218 |
+
|
| 1219 |
+
def __delitem__(self, name: str) -> None:
|
| 1220 |
+
return self.delete(name)
|
| 1221 |
+
|
| 1222 |
+
def __len__(self) -> int:
|
| 1223 |
+
return len(self.jar)
|
| 1224 |
+
|
| 1225 |
+
def __iter__(self) -> typing.Iterator[str]:
|
| 1226 |
+
return (cookie.name for cookie in self.jar)
|
| 1227 |
+
|
| 1228 |
+
def __bool__(self) -> bool:
|
| 1229 |
+
for _ in self.jar:
|
| 1230 |
+
return True
|
| 1231 |
+
return False
|
| 1232 |
+
|
| 1233 |
+
def __repr__(self) -> str:
|
| 1234 |
+
cookies_repr = ", ".join(
|
| 1235 |
+
[f"<Cookie {cookie.name}={cookie.value} for {cookie.domain} />" for cookie in self.jar]
|
| 1236 |
+
)
|
| 1237 |
+
|
| 1238 |
+
return f"<Cookies[{cookies_repr}]>"
|
| 1239 |
+
|
| 1240 |
+
class _CookieCompatRequest(urllib.request.Request):
|
| 1241 |
+
"""
|
| 1242 |
+
Wraps a `Request` instance up in a compatibility interface suitable
|
| 1243 |
+
for use with `CookieJar` operations.
|
| 1244 |
+
"""
|
| 1245 |
+
|
| 1246 |
+
def __init__(self, request: Request) -> None:
|
| 1247 |
+
super().__init__(
|
| 1248 |
+
url=str(request.url),
|
| 1249 |
+
headers=dict(request.headers),
|
| 1250 |
+
method=request.method,
|
| 1251 |
+
)
|
| 1252 |
+
self.request = request
|
| 1253 |
+
|
| 1254 |
+
def add_unredirected_header(self, key: str, val: str) -> None:
|
| 1255 |
+
super().add_unredirected_header(key, val)
|
| 1256 |
+
self.request.headers[key] = val
|
| 1257 |
+
|
| 1258 |
+
class _CookieCompatResponse:
|
| 1259 |
+
"""
|
| 1260 |
+
Wraps a `Request` instance up in a compatibility interface suitable
|
| 1261 |
+
for use with `CookieJar` operations.
|
| 1262 |
+
"""
|
| 1263 |
+
|
| 1264 |
+
def __init__(self, response: Response) -> None:
|
| 1265 |
+
self.response = response
|
| 1266 |
+
|
| 1267 |
+
def info(self) -> email.message.Message:
|
| 1268 |
+
info = email.message.Message()
|
| 1269 |
+
for key, value in self.response.headers.multi_items():
|
| 1270 |
+
# Note that setting `info[key]` here is an "append" operation,
|
| 1271 |
+
# not a "replace" operation.
|
| 1272 |
+
# https://docs.python.org/3/library/email.compat32-message.html#email.message.Message.__setitem__
|
| 1273 |
+
info[key] = value
|
| 1274 |
+
return info
|
.venv/lib/python3.12/site-packages/httpx2/_multipart.py
ADDED
|
@@ -0,0 +1,284 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import io
|
| 4 |
+
import mimetypes
|
| 5 |
+
import os
|
| 6 |
+
import re
|
| 7 |
+
import typing
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
from ._types import (
|
| 11 |
+
AsyncByteStream,
|
| 12 |
+
FileContent,
|
| 13 |
+
FileTypes,
|
| 14 |
+
RequestData,
|
| 15 |
+
RequestFiles,
|
| 16 |
+
SyncByteStream,
|
| 17 |
+
)
|
| 18 |
+
from ._utils import (
|
| 19 |
+
peek_filelike_length,
|
| 20 |
+
primitive_value_to_str,
|
| 21 |
+
to_bytes,
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
_HTML5_FORM_ENCODING_REPLACEMENTS = {'"': "%22", "\\": "\\\\"}
|
| 25 |
+
_HTML5_FORM_ENCODING_REPLACEMENTS.update({chr(c): f"%{c:02X}" for c in range(0x1F + 1) if c != 0x1B})
|
| 26 |
+
_HTML5_FORM_ENCODING_RE = re.compile(r"|".join([re.escape(c) for c in _HTML5_FORM_ENCODING_REPLACEMENTS.keys()]))
|
| 27 |
+
_HEADER_NAME_RE = re.compile(r"[!#$%&'*+\-.^_`|~0-9A-Za-z]+")
|
| 28 |
+
_FORBIDDEN_HEADER_VALUE_CHARS_RE = re.compile(r"[\x00-\x08\x0a-\x1f\x7f]")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _format_form_param(name: str, value: str) -> bytes:
|
| 32 |
+
"""
|
| 33 |
+
Encode a name/value pair within a multipart form.
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
def replacer(match: typing.Match[str]) -> str:
|
| 37 |
+
return _HTML5_FORM_ENCODING_REPLACEMENTS[match.group(0)]
|
| 38 |
+
|
| 39 |
+
value = _HTML5_FORM_ENCODING_RE.sub(replacer, value)
|
| 40 |
+
return f'{name}="{value}"'.encode()
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _guess_content_type(filename: str | None) -> str | None:
|
| 44 |
+
"""
|
| 45 |
+
Guesses the mimetype based on a filename. Defaults to `application/octet-stream`.
|
| 46 |
+
|
| 47 |
+
Returns `None` if `filename` is `None` or empty.
|
| 48 |
+
"""
|
| 49 |
+
if filename:
|
| 50 |
+
return mimetypes.guess_type(filename)[0] or "application/octet-stream"
|
| 51 |
+
return None
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def get_multipart_boundary_from_content_type(
|
| 55 |
+
content_type: bytes | None,
|
| 56 |
+
) -> bytes | None:
|
| 57 |
+
if not content_type or not content_type.startswith(b"multipart/form-data"):
|
| 58 |
+
return None
|
| 59 |
+
# parse boundary according to
|
| 60 |
+
# https://www.rfc-editor.org/rfc/rfc2046#section-5.1.1
|
| 61 |
+
if b";" in content_type:
|
| 62 |
+
for section in content_type.split(b";"):
|
| 63 |
+
if section.strip().lower().startswith(b"boundary="):
|
| 64 |
+
return section.strip()[len(b"boundary=") :].strip(b'"')
|
| 65 |
+
return None
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class DataField:
|
| 69 |
+
"""
|
| 70 |
+
A single form field item, within a multipart form field.
|
| 71 |
+
"""
|
| 72 |
+
|
| 73 |
+
def __init__(self, name: str, value: str | bytes | int | float | None) -> None:
|
| 74 |
+
if not isinstance(name, str):
|
| 75 |
+
raise TypeError(f"Invalid type for name. Expected str, got {type(name)}: {name!r}")
|
| 76 |
+
if value is not None and not isinstance(value, (str, bytes, int, float)):
|
| 77 |
+
raise TypeError(f"Invalid type for value. Expected primitive type, got {type(value)}: {value!r}")
|
| 78 |
+
self.name = name
|
| 79 |
+
self.value: str | bytes = value if isinstance(value, bytes) else primitive_value_to_str(value)
|
| 80 |
+
|
| 81 |
+
def render_headers(self) -> bytes:
|
| 82 |
+
if not hasattr(self, "_headers"):
|
| 83 |
+
name = _format_form_param("name", self.name)
|
| 84 |
+
self._headers = b"".join([b"Content-Disposition: form-data; ", name, b"\r\n\r\n"])
|
| 85 |
+
|
| 86 |
+
return self._headers
|
| 87 |
+
|
| 88 |
+
def render_data(self) -> bytes:
|
| 89 |
+
if not hasattr(self, "_data"):
|
| 90 |
+
self._data = to_bytes(self.value)
|
| 91 |
+
|
| 92 |
+
return self._data
|
| 93 |
+
|
| 94 |
+
def get_length(self) -> int:
|
| 95 |
+
headers = self.render_headers()
|
| 96 |
+
data = self.render_data()
|
| 97 |
+
return len(headers) + len(data)
|
| 98 |
+
|
| 99 |
+
def render(self) -> typing.Iterator[bytes]:
|
| 100 |
+
yield self.render_headers()
|
| 101 |
+
yield self.render_data()
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class FileField:
|
| 105 |
+
"""
|
| 106 |
+
A single file field item, within a multipart form field.
|
| 107 |
+
"""
|
| 108 |
+
|
| 109 |
+
CHUNK_SIZE = 64 * 1024
|
| 110 |
+
|
| 111 |
+
def __init__(self, name: str, value: FileTypes) -> None:
|
| 112 |
+
self.name = name
|
| 113 |
+
|
| 114 |
+
fileobj: FileContent
|
| 115 |
+
|
| 116 |
+
headers: dict[str, str] = {}
|
| 117 |
+
content_type: str | None = None
|
| 118 |
+
|
| 119 |
+
# This large tuple based API largely mirror's requests' API
|
| 120 |
+
# It would be good to think of better APIs for this that we could
|
| 121 |
+
# include in httpx 2.0 since variable length tuples(especially of 4 elements)
|
| 122 |
+
# are quite unwieldy
|
| 123 |
+
if isinstance(value, tuple):
|
| 124 |
+
if len(value) == 2:
|
| 125 |
+
# neither the 3rd parameter (content_type) nor the 4th (headers)
|
| 126 |
+
# was included
|
| 127 |
+
filename, fileobj = value
|
| 128 |
+
elif len(value) == 3:
|
| 129 |
+
filename, fileobj, content_type = value
|
| 130 |
+
else:
|
| 131 |
+
# all 4 parameters included
|
| 132 |
+
filename, fileobj, content_type, headers = value # type: ignore
|
| 133 |
+
else:
|
| 134 |
+
filename = Path(str(getattr(value, "name", "upload"))).name
|
| 135 |
+
fileobj = value
|
| 136 |
+
|
| 137 |
+
if content_type is None:
|
| 138 |
+
content_type = _guess_content_type(filename)
|
| 139 |
+
|
| 140 |
+
has_content_type_header = any("content-type" in key.lower() for key in headers)
|
| 141 |
+
if content_type is not None and not has_content_type_header:
|
| 142 |
+
# note that unlike requests, we ignore the content_type provided in the 3rd
|
| 143 |
+
# tuple element if it is also included in the headers requests does
|
| 144 |
+
# the opposite (it overwrites the headerwith the 3rd tuple element)
|
| 145 |
+
headers["Content-Type"] = content_type
|
| 146 |
+
|
| 147 |
+
if isinstance(fileobj, io.StringIO):
|
| 148 |
+
raise TypeError("Multipart file uploads require 'io.BytesIO', not 'io.StringIO'.")
|
| 149 |
+
if isinstance(fileobj, io.TextIOBase):
|
| 150 |
+
raise TypeError("Multipart file uploads must be opened in binary mode, not text mode.")
|
| 151 |
+
|
| 152 |
+
self.filename = filename
|
| 153 |
+
self.file = fileobj
|
| 154 |
+
self.headers = headers
|
| 155 |
+
|
| 156 |
+
def get_length(self) -> int | None:
|
| 157 |
+
headers = self.render_headers()
|
| 158 |
+
|
| 159 |
+
if isinstance(self.file, (str, bytes)):
|
| 160 |
+
return len(headers) + len(to_bytes(self.file))
|
| 161 |
+
|
| 162 |
+
file_length = peek_filelike_length(self.file)
|
| 163 |
+
|
| 164 |
+
# If we can't determine the filesize without reading it into memory,
|
| 165 |
+
# then return `None` here, to indicate an unknown file length.
|
| 166 |
+
if file_length is None:
|
| 167 |
+
return None
|
| 168 |
+
|
| 169 |
+
return len(headers) + file_length
|
| 170 |
+
|
| 171 |
+
def render_headers(self) -> bytes:
|
| 172 |
+
if not hasattr(self, "_headers"):
|
| 173 |
+
parts = [
|
| 174 |
+
b"Content-Disposition: form-data; ",
|
| 175 |
+
_format_form_param("name", self.name),
|
| 176 |
+
]
|
| 177 |
+
if self.filename:
|
| 178 |
+
filename = _format_form_param("filename", self.filename)
|
| 179 |
+
parts.extend([b"; ", filename])
|
| 180 |
+
for header_name, header_value in self.headers.items():
|
| 181 |
+
if _HEADER_NAME_RE.fullmatch(header_name) is None:
|
| 182 |
+
raise ValueError("Invalid multipart header name.")
|
| 183 |
+
if _FORBIDDEN_HEADER_VALUE_CHARS_RE.search(header_value) is not None:
|
| 184 |
+
raise ValueError("Invalid control character in multipart header value.")
|
| 185 |
+
key, val = f"\r\n{header_name}: ".encode(), header_value.encode()
|
| 186 |
+
parts.extend([key, val])
|
| 187 |
+
parts.append(b"\r\n\r\n")
|
| 188 |
+
self._headers = b"".join(parts)
|
| 189 |
+
|
| 190 |
+
return self._headers
|
| 191 |
+
|
| 192 |
+
def render_data(self) -> typing.Iterator[bytes]:
|
| 193 |
+
if isinstance(self.file, (str, bytes)):
|
| 194 |
+
yield to_bytes(self.file)
|
| 195 |
+
return
|
| 196 |
+
|
| 197 |
+
if hasattr(self.file, "seek"):
|
| 198 |
+
try:
|
| 199 |
+
self.file.seek(0)
|
| 200 |
+
except io.UnsupportedOperation:
|
| 201 |
+
pass
|
| 202 |
+
|
| 203 |
+
chunk = self.file.read(self.CHUNK_SIZE)
|
| 204 |
+
while chunk:
|
| 205 |
+
yield to_bytes(chunk)
|
| 206 |
+
chunk = self.file.read(self.CHUNK_SIZE)
|
| 207 |
+
|
| 208 |
+
def render(self) -> typing.Iterator[bytes]:
|
| 209 |
+
yield self.render_headers()
|
| 210 |
+
yield from self.render_data()
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
class MultipartStream(SyncByteStream, AsyncByteStream):
|
| 214 |
+
"""
|
| 215 |
+
Request content as streaming multipart encoded form data.
|
| 216 |
+
"""
|
| 217 |
+
|
| 218 |
+
def __init__(
|
| 219 |
+
self,
|
| 220 |
+
data: RequestData,
|
| 221 |
+
files: RequestFiles,
|
| 222 |
+
boundary: bytes | None = None,
|
| 223 |
+
) -> None:
|
| 224 |
+
if boundary is None:
|
| 225 |
+
boundary = os.urandom(16).hex().encode("ascii")
|
| 226 |
+
|
| 227 |
+
self.boundary = boundary
|
| 228 |
+
self.content_type = f"multipart/form-data; boundary={boundary.decode('ascii')}"
|
| 229 |
+
self.fields = list(self._iter_fields(data, files))
|
| 230 |
+
|
| 231 |
+
def _iter_fields(self, data: RequestData, files: RequestFiles) -> typing.Iterator[FileField | DataField]:
|
| 232 |
+
for name, value in data.items():
|
| 233 |
+
if isinstance(value, (tuple, list)):
|
| 234 |
+
for item in value:
|
| 235 |
+
yield DataField(name=name, value=item)
|
| 236 |
+
else:
|
| 237 |
+
yield DataField(name=name, value=value)
|
| 238 |
+
|
| 239 |
+
file_items = files.items() if isinstance(files, typing.Mapping) else files
|
| 240 |
+
for name, value in file_items:
|
| 241 |
+
yield FileField(name=name, value=value)
|
| 242 |
+
|
| 243 |
+
def iter_chunks(self) -> typing.Iterator[bytes]:
|
| 244 |
+
for field in self.fields:
|
| 245 |
+
yield b"--%s\r\n" % self.boundary
|
| 246 |
+
yield from field.render()
|
| 247 |
+
yield b"\r\n"
|
| 248 |
+
yield b"--%s--\r\n" % self.boundary
|
| 249 |
+
|
| 250 |
+
def get_content_length(self) -> int | None:
|
| 251 |
+
"""
|
| 252 |
+
Return the length of the multipart encoded content, or `None` if
|
| 253 |
+
any of the files have a length that cannot be determined upfront.
|
| 254 |
+
"""
|
| 255 |
+
boundary_length = len(self.boundary)
|
| 256 |
+
length = 0
|
| 257 |
+
|
| 258 |
+
for field in self.fields:
|
| 259 |
+
field_length = field.get_length()
|
| 260 |
+
if field_length is None:
|
| 261 |
+
return None
|
| 262 |
+
|
| 263 |
+
length += 2 + boundary_length + 2 # b"--{boundary}\r\n"
|
| 264 |
+
length += field_length
|
| 265 |
+
length += 2 # b"\r\n"
|
| 266 |
+
|
| 267 |
+
length += 2 + boundary_length + 4 # b"--{boundary}--\r\n"
|
| 268 |
+
return length
|
| 269 |
+
|
| 270 |
+
# Content stream interface.
|
| 271 |
+
|
| 272 |
+
def get_headers(self) -> dict[str, str]:
|
| 273 |
+
content_length = self.get_content_length()
|
| 274 |
+
content_type = self.content_type
|
| 275 |
+
if content_length is None:
|
| 276 |
+
return {"Transfer-Encoding": "chunked", "Content-Type": content_type}
|
| 277 |
+
return {"Content-Length": str(content_length), "Content-Type": content_type}
|
| 278 |
+
|
| 279 |
+
def __iter__(self) -> typing.Iterator[bytes]:
|
| 280 |
+
yield from self.iter_chunks()
|
| 281 |
+
|
| 282 |
+
async def __aiter__(self) -> typing.AsyncIterator[bytes]:
|
| 283 |
+
for chunk in self.iter_chunks():
|
| 284 |
+
yield chunk
|
.venv/lib/python3.12/site-packages/httpx2/_sse.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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
|
.venv/lib/python3.12/site-packages/httpx2/_status_codes.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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ant 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 __getattribute__(cls, name: str) -> object:
|
| 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 super().__getattribute__(name)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class codes(IntEnum, metaclass=_CodesMeta):
|
| 31 |
+
"""HTTP status codes and reason phrases
|
| 32 |
+
|
| 33 |
+
Status codes from the following RFCs are all observed:
|
| 34 |
+
|
| 35 |
+
* RFC 9110: HTTP Semantics, obsoletes 7231 & 7238
|
| 36 |
+
* RFC 6585: Additional HTTP Status Codes
|
| 37 |
+
* RFC 3229: Delta encoding in HTTP
|
| 38 |
+
* RFC 4918: HTTP Extensions for WebDAV, obsoletes 2518
|
| 39 |
+
* RFC 5842: Binding Extensions to WebDAV
|
| 40 |
+
* RFC 2295: Transparent Content Negotiation in HTTP
|
| 41 |
+
* RFC 2774: An HTTP Extension Framework
|
| 42 |
+
* RFC 7540: Hypertext Transfer Protocol Version 2 (HTTP/2)
|
| 43 |
+
* RFC 2324: Hyper Text Coffee Pot Control Protocol (HTCPCP/1.0)
|
| 44 |
+
* RFC 7725: An HTTP Status Code to Report Legal Obstacles
|
| 45 |
+
* RFC 8297: An HTTP Status Code for Indicating Hints
|
| 46 |
+
* RFC 8470: Using Early Data in HTTP
|
| 47 |
+
"""
|
| 48 |
+
|
| 49 |
+
def __new__(cls, value: int, phrase: str = "") -> codes:
|
| 50 |
+
obj = int.__new__(cls, value)
|
| 51 |
+
obj._value_ = value
|
| 52 |
+
|
| 53 |
+
obj.phrase = phrase # type: ignore[attr-defined]
|
| 54 |
+
return obj
|
| 55 |
+
|
| 56 |
+
def __str__(self) -> str:
|
| 57 |
+
return str(self.value)
|
| 58 |
+
|
| 59 |
+
@classmethod
|
| 60 |
+
def get_reason_phrase(cls, value: int) -> str:
|
| 61 |
+
try:
|
| 62 |
+
return codes(value).phrase # type: ignore
|
| 63 |
+
except ValueError:
|
| 64 |
+
return ""
|
| 65 |
+
|
| 66 |
+
@classmethod
|
| 67 |
+
def is_informational(cls, value: int) -> bool:
|
| 68 |
+
"""
|
| 69 |
+
Returns `True` for 1xx status codes, `False` otherwise.
|
| 70 |
+
"""
|
| 71 |
+
return 100 <= value <= 199
|
| 72 |
+
|
| 73 |
+
@classmethod
|
| 74 |
+
def is_success(cls, value: int) -> bool:
|
| 75 |
+
"""
|
| 76 |
+
Returns `True` for 2xx status codes, `False` otherwise.
|
| 77 |
+
"""
|
| 78 |
+
return 200 <= value <= 299
|
| 79 |
+
|
| 80 |
+
@classmethod
|
| 81 |
+
def is_redirect(cls, value: int) -> bool:
|
| 82 |
+
"""
|
| 83 |
+
Returns `True` for 3xx status codes, `False` otherwise.
|
| 84 |
+
"""
|
| 85 |
+
return 300 <= value <= 399
|
| 86 |
+
|
| 87 |
+
@classmethod
|
| 88 |
+
def is_client_error(cls, value: int) -> bool:
|
| 89 |
+
"""
|
| 90 |
+
Returns `True` for 4xx status codes, `False` otherwise.
|
| 91 |
+
"""
|
| 92 |
+
return 400 <= value <= 499
|
| 93 |
+
|
| 94 |
+
@classmethod
|
| 95 |
+
def is_server_error(cls, value: int) -> bool:
|
| 96 |
+
"""
|
| 97 |
+
Returns `True` for 5xx status codes, `False` otherwise.
|
| 98 |
+
"""
|
| 99 |
+
return 500 <= value <= 599
|
| 100 |
+
|
| 101 |
+
@classmethod
|
| 102 |
+
def is_error(cls, value: int) -> bool:
|
| 103 |
+
"""
|
| 104 |
+
Returns `True` for 4xx or 5xx status codes, `False` otherwise.
|
| 105 |
+
"""
|
| 106 |
+
return 400 <= value <= 599
|
| 107 |
+
|
| 108 |
+
# informational
|
| 109 |
+
CONTINUE = 100, "Continue"
|
| 110 |
+
SWITCHING_PROTOCOLS = 101, "Switching Protocols"
|
| 111 |
+
PROCESSING = 102, "Processing"
|
| 112 |
+
EARLY_HINTS = 103, "Early Hints"
|
| 113 |
+
|
| 114 |
+
# success
|
| 115 |
+
OK = 200, "OK"
|
| 116 |
+
CREATED = 201, "Created"
|
| 117 |
+
ACCEPTED = 202, "Accepted"
|
| 118 |
+
NON_AUTHORITATIVE_INFORMATION = 203, "Non-Authoritative Information"
|
| 119 |
+
NO_CONTENT = 204, "No Content"
|
| 120 |
+
RESET_CONTENT = 205, "Reset Content"
|
| 121 |
+
PARTIAL_CONTENT = 206, "Partial Content"
|
| 122 |
+
MULTI_STATUS = 207, "Multi-Status"
|
| 123 |
+
ALREADY_REPORTED = 208, "Already Reported"
|
| 124 |
+
IM_USED = 226, "IM Used"
|
| 125 |
+
|
| 126 |
+
# redirection
|
| 127 |
+
MULTIPLE_CHOICES = 300, "Multiple Choices"
|
| 128 |
+
MOVED_PERMANENTLY = 301, "Moved Permanently"
|
| 129 |
+
FOUND = 302, "Found"
|
| 130 |
+
SEE_OTHER = 303, "See Other"
|
| 131 |
+
NOT_MODIFIED = 304, "Not Modified"
|
| 132 |
+
USE_PROXY = 305, "Use Proxy"
|
| 133 |
+
TEMPORARY_REDIRECT = 307, "Temporary Redirect"
|
| 134 |
+
PERMANENT_REDIRECT = 308, "Permanent Redirect"
|
| 135 |
+
|
| 136 |
+
# client error
|
| 137 |
+
BAD_REQUEST = 400, "Bad Request"
|
| 138 |
+
UNAUTHORIZED = 401, "Unauthorized"
|
| 139 |
+
PAYMENT_REQUIRED = 402, "Payment Required"
|
| 140 |
+
FORBIDDEN = 403, "Forbidden"
|
| 141 |
+
NOT_FOUND = 404, "Not Found"
|
| 142 |
+
METHOD_NOT_ALLOWED = 405, "Method Not Allowed"
|
| 143 |
+
NOT_ACCEPTABLE = 406, "Not Acceptable"
|
| 144 |
+
PROXY_AUTHENTICATION_REQUIRED = 407, "Proxy Authentication Required"
|
| 145 |
+
REQUEST_TIMEOUT = 408, "Request Timeout"
|
| 146 |
+
CONFLICT = 409, "Conflict"
|
| 147 |
+
GONE = 410, "Gone"
|
| 148 |
+
LENGTH_REQUIRED = 411, "Length Required"
|
| 149 |
+
PRECONDITION_FAILED = 412, "Precondition Failed"
|
| 150 |
+
CONTENT_TOO_LARGE = 413, "Content Too Large"
|
| 151 |
+
URI_TOO_LONG = 414, "URI Too Long"
|
| 152 |
+
UNSUPPORTED_MEDIA_TYPE = 415, "Unsupported Media Type"
|
| 153 |
+
RANGE_NOT_SATISFIABLE = 416, "Range Not Satisfiable"
|
| 154 |
+
EXPECTATION_FAILED = 417, "Expectation Failed"
|
| 155 |
+
IM_A_TEAPOT = 418, "I'm a teapot"
|
| 156 |
+
MISDIRECTED_REQUEST = 421, "Misdirected Request"
|
| 157 |
+
UNPROCESSABLE_CONTENT = 422, "Unprocessable Content"
|
| 158 |
+
LOCKED = 423, "Locked"
|
| 159 |
+
FAILED_DEPENDENCY = 424, "Failed Dependency"
|
| 160 |
+
TOO_EARLY = 425, "Too Early"
|
| 161 |
+
UPGRADE_REQUIRED = 426, "Upgrade Required"
|
| 162 |
+
PRECONDITION_REQUIRED = 428, "Precondition Required"
|
| 163 |
+
TOO_MANY_REQUESTS = 429, "Too Many Requests"
|
| 164 |
+
REQUEST_HEADER_FIELDS_TOO_LARGE = 431, "Request Header Fields Too Large"
|
| 165 |
+
UNAVAILABLE_FOR_LEGAL_REASONS = 451, "Unavailable For Legal Reasons"
|
| 166 |
+
|
| 167 |
+
# server errors
|
| 168 |
+
INTERNAL_SERVER_ERROR = 500, "Internal Server Error"
|
| 169 |
+
NOT_IMPLEMENTED = 501, "Not Implemented"
|
| 170 |
+
BAD_GATEWAY = 502, "Bad Gateway"
|
| 171 |
+
SERVICE_UNAVAILABLE = 503, "Service Unavailable"
|
| 172 |
+
GATEWAY_TIMEOUT = 504, "Gateway Timeout"
|
| 173 |
+
HTTP_VERSION_NOT_SUPPORTED = 505, "HTTP Version Not Supported"
|
| 174 |
+
VARIANT_ALSO_NEGOTIATES = 506, "Variant Also Negotiates"
|
| 175 |
+
INSUFFICIENT_STORAGE = 507, "Insufficient Storage"
|
| 176 |
+
LOOP_DETECTED = 508, "Loop Detected"
|
| 177 |
+
NOT_EXTENDED = 510, "Not Extended"
|
| 178 |
+
NETWORK_AUTHENTICATION_REQUIRED = 511, "Network Authentication Required"
|
| 179 |
+
|
| 180 |
+
# Deprecated aliases for names replaced by RFC 9110.
|
| 181 |
+
REQUEST_ENTITY_TOO_LARGE = CONTENT_TOO_LARGE
|
| 182 |
+
REQUEST_URI_TOO_LONG = URI_TOO_LONG
|
| 183 |
+
REQUESTED_RANGE_NOT_SATISFIABLE = RANGE_NOT_SATISFIABLE
|
| 184 |
+
UNPROCESSABLE_ENTITY = UNPROCESSABLE_CONTENT
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
# Include lower-case styles for `requests` compatibility.
|
| 188 |
+
for name, code in codes.__members__.items():
|
| 189 |
+
setattr(codes, name.lower(), int(code))
|
.venv/lib/python3.12/site-packages/httpx2/_transports/__init__.py
ADDED
|
@@ -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 |
+
]
|
.venv/lib/python3.12/site-packages/httpx2/_transports/asgi.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import typing
|
| 4 |
+
|
| 5 |
+
from .._models import Request, Response
|
| 6 |
+
from .._types import AsyncByteStream
|
| 7 |
+
from .base import AsyncBaseTransport
|
| 8 |
+
|
| 9 |
+
if typing.TYPE_CHECKING:
|
| 10 |
+
import asyncio
|
| 11 |
+
|
| 12 |
+
import trio
|
| 13 |
+
|
| 14 |
+
Event = asyncio.Event | trio.Event
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
_Message = typing.MutableMapping[str, typing.Any]
|
| 18 |
+
_Receive = typing.Callable[[], typing.Awaitable[_Message]]
|
| 19 |
+
_Send = typing.Callable[[typing.MutableMapping[str, typing.Any]], typing.Awaitable[None]]
|
| 20 |
+
_ASGIApp = typing.Callable[[typing.MutableMapping[str, typing.Any], _Receive, _Send], typing.Awaitable[None]]
|
| 21 |
+
|
| 22 |
+
__all__ = ["ASGITransport"]
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def is_running_trio() -> bool:
|
| 26 |
+
try:
|
| 27 |
+
# sniffio is a dependency of trio.
|
| 28 |
+
|
| 29 |
+
# See https://github.com/python-trio/trio/issues/2802
|
| 30 |
+
import sniffio
|
| 31 |
+
|
| 32 |
+
if sniffio.current_async_library() == "trio":
|
| 33 |
+
return True
|
| 34 |
+
except ImportError: # pragma: no cover
|
| 35 |
+
pass
|
| 36 |
+
|
| 37 |
+
return False
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def create_event() -> Event:
|
| 41 |
+
if is_running_trio():
|
| 42 |
+
import trio
|
| 43 |
+
|
| 44 |
+
return trio.Event()
|
| 45 |
+
|
| 46 |
+
import asyncio
|
| 47 |
+
|
| 48 |
+
return asyncio.Event()
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class ASGIResponseStream(AsyncByteStream):
|
| 52 |
+
def __init__(self, body: list[bytes]) -> None:
|
| 53 |
+
self._body = body
|
| 54 |
+
|
| 55 |
+
async def __aiter__(self) -> typing.AsyncIterator[bytes]:
|
| 56 |
+
yield b"".join(self._body)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class ASGITransport(AsyncBaseTransport):
|
| 60 |
+
"""
|
| 61 |
+
A custom AsyncTransport that handles sending requests directly to an ASGI app.
|
| 62 |
+
|
| 63 |
+
```python
|
| 64 |
+
transport = httpx2.ASGITransport(
|
| 65 |
+
app=app,
|
| 66 |
+
root_path="/submount",
|
| 67 |
+
client=("1.2.3.4", 123)
|
| 68 |
+
)
|
| 69 |
+
client = httpx2.AsyncClient(transport=transport)
|
| 70 |
+
```
|
| 71 |
+
|
| 72 |
+
Arguments:
|
| 73 |
+
app: The ASGI application.
|
| 74 |
+
raise_app_exceptions: Boolean indicating if exceptions in the application
|
| 75 |
+
should be raised. Default to `True`. Can be set to `False` for use cases
|
| 76 |
+
such as testing the content of a client 500 response.
|
| 77 |
+
root_path: The root path on which the ASGI application should be mounted.
|
| 78 |
+
client: A two-tuple indicating the client IP and port of incoming requests.
|
| 79 |
+
"""
|
| 80 |
+
|
| 81 |
+
def __init__(
|
| 82 |
+
self,
|
| 83 |
+
app: _ASGIApp,
|
| 84 |
+
raise_app_exceptions: bool = True,
|
| 85 |
+
root_path: str = "",
|
| 86 |
+
client: tuple[str, int] = ("127.0.0.1", 123),
|
| 87 |
+
) -> None:
|
| 88 |
+
self.app = app
|
| 89 |
+
self.raise_app_exceptions = raise_app_exceptions
|
| 90 |
+
self.root_path = root_path
|
| 91 |
+
self.client = client
|
| 92 |
+
|
| 93 |
+
async def handle_async_request(self, request: Request) -> Response:
|
| 94 |
+
assert isinstance(request.stream, AsyncByteStream)
|
| 95 |
+
|
| 96 |
+
# ASGI scope.
|
| 97 |
+
scope = {
|
| 98 |
+
"type": "http",
|
| 99 |
+
"asgi": {"version": "3.0"},
|
| 100 |
+
"http_version": "1.1",
|
| 101 |
+
"method": request.method,
|
| 102 |
+
"headers": [(k.lower(), v) for (k, v) in request.headers.raw],
|
| 103 |
+
"scheme": request.url.scheme,
|
| 104 |
+
"path": request.url.path,
|
| 105 |
+
"raw_path": request.url.raw_path.split(b"?")[0],
|
| 106 |
+
"query_string": request.url.query,
|
| 107 |
+
"server": (request.url.host, request.url.port),
|
| 108 |
+
"client": self.client,
|
| 109 |
+
"root_path": self.root_path,
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
# Request.
|
| 113 |
+
request_body_chunks = request.stream.__aiter__()
|
| 114 |
+
request_complete = False
|
| 115 |
+
|
| 116 |
+
# Response.
|
| 117 |
+
status_code = None
|
| 118 |
+
response_headers = None
|
| 119 |
+
body_parts: list[bytes] = []
|
| 120 |
+
response_started = False
|
| 121 |
+
response_complete = create_event()
|
| 122 |
+
|
| 123 |
+
# ASGI callables.
|
| 124 |
+
|
| 125 |
+
async def receive() -> dict[str, typing.Any]:
|
| 126 |
+
nonlocal request_complete
|
| 127 |
+
|
| 128 |
+
if request_complete:
|
| 129 |
+
await response_complete.wait()
|
| 130 |
+
return {"type": "http.disconnect"}
|
| 131 |
+
|
| 132 |
+
try:
|
| 133 |
+
body = await request_body_chunks.__anext__()
|
| 134 |
+
except StopAsyncIteration:
|
| 135 |
+
request_complete = True
|
| 136 |
+
return {"type": "http.request", "body": b"", "more_body": False}
|
| 137 |
+
return {"type": "http.request", "body": body, "more_body": True}
|
| 138 |
+
|
| 139 |
+
async def send(message: typing.MutableMapping[str, typing.Any]) -> None:
|
| 140 |
+
nonlocal status_code, response_headers, response_started
|
| 141 |
+
|
| 142 |
+
if message["type"] == "http.response.start":
|
| 143 |
+
assert not response_started
|
| 144 |
+
|
| 145 |
+
status_code = message["status"]
|
| 146 |
+
response_headers = message.get("headers", [])
|
| 147 |
+
response_started = True
|
| 148 |
+
|
| 149 |
+
elif message["type"] == "http.response.body":
|
| 150 |
+
assert not response_complete.is_set()
|
| 151 |
+
body = message.get("body", b"")
|
| 152 |
+
more_body = message.get("more_body", False)
|
| 153 |
+
|
| 154 |
+
if body and request.method != "HEAD":
|
| 155 |
+
body_parts.append(body)
|
| 156 |
+
|
| 157 |
+
if not more_body:
|
| 158 |
+
response_complete.set()
|
| 159 |
+
|
| 160 |
+
try:
|
| 161 |
+
await self.app(scope, receive, send)
|
| 162 |
+
except Exception:
|
| 163 |
+
if self.raise_app_exceptions:
|
| 164 |
+
raise
|
| 165 |
+
|
| 166 |
+
response_complete.set()
|
| 167 |
+
if status_code is None:
|
| 168 |
+
status_code = 500
|
| 169 |
+
if response_headers is None:
|
| 170 |
+
response_headers = {}
|
| 171 |
+
|
| 172 |
+
assert response_complete.is_set()
|
| 173 |
+
assert status_code is not None
|
| 174 |
+
assert response_headers is not None
|
| 175 |
+
|
| 176 |
+
stream = ASGIResponseStream(body_parts)
|
| 177 |
+
|
| 178 |
+
return Response(status_code, headers=response_headers, stream=stream)
|
.venv/lib/python3.12/site-packages/httpx2/_transports/base.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import typing
|
| 4 |
+
from types import TracebackType
|
| 5 |
+
|
| 6 |
+
from .._models import Request, Response
|
| 7 |
+
|
| 8 |
+
# TODO(Marcelo): When Python 3.10 reaches EOF, we can use `typing.Self` instead of defining those two.
|
| 9 |
+
T = typing.TypeVar("T", bound="BaseTransport")
|
| 10 |
+
A = typing.TypeVar("A", bound="AsyncBaseTransport")
|
| 11 |
+
|
| 12 |
+
__all__ = ["AsyncBaseTransport", "BaseTransport"]
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class BaseTransport:
|
| 16 |
+
def __enter__(self: T) -> T:
|
| 17 |
+
return self
|
| 18 |
+
|
| 19 |
+
def __exit__(
|
| 20 |
+
self,
|
| 21 |
+
exc_type: type[BaseException] | None = None,
|
| 22 |
+
exc_value: BaseException | None = None,
|
| 23 |
+
traceback: TracebackType | None = None,
|
| 24 |
+
) -> None:
|
| 25 |
+
self.close()
|
| 26 |
+
|
| 27 |
+
def handle_request(self, request: Request) -> Response:
|
| 28 |
+
"""
|
| 29 |
+
Send a single HTTP request and return a response.
|
| 30 |
+
|
| 31 |
+
Developers shouldn't typically ever need to call into this API directly,
|
| 32 |
+
since the Client class provides all the higher level user-facing API
|
| 33 |
+
niceties.
|
| 34 |
+
|
| 35 |
+
In order to properly release any network resources, the response
|
| 36 |
+
stream should *either* be consumed immediately, with a call to
|
| 37 |
+
`response.stream.read()`, or else the `handle_request` call should
|
| 38 |
+
be followed with a try/finally block to ensuring the stream is
|
| 39 |
+
always closed.
|
| 40 |
+
|
| 41 |
+
Example usage:
|
| 42 |
+
|
| 43 |
+
with httpx2.HTTPTransport() as transport:
|
| 44 |
+
req = httpx2.Request(
|
| 45 |
+
method=b"GET",
|
| 46 |
+
url=(b"https", b"www.example.com", 443, b"/"),
|
| 47 |
+
headers=[(b"Host", b"www.example.com")],
|
| 48 |
+
)
|
| 49 |
+
resp = transport.handle_request(req)
|
| 50 |
+
body = resp.stream.read()
|
| 51 |
+
print(resp.status_code, resp.headers, body)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
Takes a `Request` instance as the only argument.
|
| 55 |
+
|
| 56 |
+
Returns a `Response` instance.
|
| 57 |
+
"""
|
| 58 |
+
raise NotImplementedError("The 'handle_request' method must be implemented.") # pragma: no cover
|
| 59 |
+
|
| 60 |
+
def close(self) -> None:
|
| 61 |
+
pass
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class AsyncBaseTransport:
|
| 65 |
+
async def __aenter__(self: A) -> A:
|
| 66 |
+
return self
|
| 67 |
+
|
| 68 |
+
async def __aexit__(
|
| 69 |
+
self,
|
| 70 |
+
exc_type: type[BaseException] | None = None,
|
| 71 |
+
exc_value: BaseException | None = None,
|
| 72 |
+
traceback: TracebackType | None = None,
|
| 73 |
+
) -> None:
|
| 74 |
+
await self.aclose()
|
| 75 |
+
|
| 76 |
+
async def handle_async_request(
|
| 77 |
+
self,
|
| 78 |
+
request: Request,
|
| 79 |
+
) -> Response:
|
| 80 |
+
raise NotImplementedError("The 'handle_async_request' method must be implemented.") # pragma: no cover
|
| 81 |
+
|
| 82 |
+
async def aclose(self) -> None:
|
| 83 |
+
pass
|
.venv/lib/python3.12/site-packages/httpx2/_transports/default.py
ADDED
|
@@ -0,0 +1,400 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Custom transports, with nicely configured defaults.
|
| 3 |
+
|
| 4 |
+
The following additional keyword arguments are currently supported by httpcore...
|
| 5 |
+
|
| 6 |
+
* uds: str
|
| 7 |
+
* local_address: str
|
| 8 |
+
* retries: int
|
| 9 |
+
|
| 10 |
+
Example usages...
|
| 11 |
+
|
| 12 |
+
# Disable HTTP/2 on a single specific domain.
|
| 13 |
+
mounts = {
|
| 14 |
+
"all://": httpx2.HTTPTransport(http2=True),
|
| 15 |
+
"all://*example.org": httpx2.HTTPTransport()
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
# Using advanced httpcore configuration, with connection retries.
|
| 19 |
+
transport = httpx2.HTTPTransport(retries=1)
|
| 20 |
+
client = httpx2.Client(transport=transport)
|
| 21 |
+
|
| 22 |
+
# Using advanced httpcore configuration, with unix domain sockets.
|
| 23 |
+
transport = httpx2.HTTPTransport(uds="socket.uds")
|
| 24 |
+
client = httpx2.Client(transport=transport)
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
from __future__ import annotations
|
| 28 |
+
|
| 29 |
+
import contextlib
|
| 30 |
+
import typing
|
| 31 |
+
from collections.abc import Generator
|
| 32 |
+
from types import TracebackType
|
| 33 |
+
|
| 34 |
+
if typing.TYPE_CHECKING: # pragma: no cover
|
| 35 |
+
import ssl
|
| 36 |
+
|
| 37 |
+
import httpx2
|
| 38 |
+
|
| 39 |
+
from .._config import DEFAULT_LIMITS, Limits, Proxy, create_ssl_context
|
| 40 |
+
from .._exceptions import (
|
| 41 |
+
ConnectError,
|
| 42 |
+
ConnectTimeout,
|
| 43 |
+
LocalProtocolError,
|
| 44 |
+
NetworkError,
|
| 45 |
+
PoolTimeout,
|
| 46 |
+
ProtocolError,
|
| 47 |
+
ProxyError,
|
| 48 |
+
ReadError,
|
| 49 |
+
ReadTimeout,
|
| 50 |
+
RemoteProtocolError,
|
| 51 |
+
TimeoutException,
|
| 52 |
+
UnsupportedProtocol,
|
| 53 |
+
WriteError,
|
| 54 |
+
WriteTimeout,
|
| 55 |
+
)
|
| 56 |
+
from .._models import Request, Response
|
| 57 |
+
from .._types import AsyncByteStream, CertTypes, ProxyTypes, SyncByteStream
|
| 58 |
+
from .._urls import URL
|
| 59 |
+
from .base import AsyncBaseTransport, BaseTransport
|
| 60 |
+
|
| 61 |
+
T = typing.TypeVar("T", bound="HTTPTransport")
|
| 62 |
+
A = typing.TypeVar("A", bound="AsyncHTTPTransport")
|
| 63 |
+
|
| 64 |
+
SOCKET_OPTION = tuple[int, int, int] | tuple[int, int, bytes | bytearray] | tuple[int, int, None, int]
|
| 65 |
+
|
| 66 |
+
__all__ = ["AsyncHTTPTransport", "HTTPTransport"]
|
| 67 |
+
|
| 68 |
+
HTTPCORE_EXC_MAP: dict[type[Exception], type[httpx2.HTTPError]] = {}
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _load_httpcore_exceptions() -> dict[type[Exception], type[httpx2.HTTPError]]:
|
| 72 |
+
import httpcore2
|
| 73 |
+
|
| 74 |
+
return {
|
| 75 |
+
httpcore2.TimeoutException: TimeoutException,
|
| 76 |
+
httpcore2.ConnectTimeout: ConnectTimeout,
|
| 77 |
+
httpcore2.ReadTimeout: ReadTimeout,
|
| 78 |
+
httpcore2.WriteTimeout: WriteTimeout,
|
| 79 |
+
httpcore2.PoolTimeout: PoolTimeout,
|
| 80 |
+
httpcore2.NetworkError: NetworkError,
|
| 81 |
+
httpcore2.ConnectError: ConnectError,
|
| 82 |
+
httpcore2.ReadError: ReadError,
|
| 83 |
+
httpcore2.WriteError: WriteError,
|
| 84 |
+
httpcore2.ProxyError: ProxyError,
|
| 85 |
+
httpcore2.UnsupportedProtocol: UnsupportedProtocol,
|
| 86 |
+
httpcore2.ProtocolError: ProtocolError,
|
| 87 |
+
httpcore2.LocalProtocolError: LocalProtocolError,
|
| 88 |
+
httpcore2.RemoteProtocolError: RemoteProtocolError,
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
@contextlib.contextmanager
|
| 93 |
+
def map_httpcore_exceptions() -> Generator[None]:
|
| 94 |
+
global HTTPCORE_EXC_MAP
|
| 95 |
+
if len(HTTPCORE_EXC_MAP) == 0:
|
| 96 |
+
HTTPCORE_EXC_MAP = _load_httpcore_exceptions()
|
| 97 |
+
try:
|
| 98 |
+
yield
|
| 99 |
+
except Exception as exc:
|
| 100 |
+
mapped_exc = None
|
| 101 |
+
|
| 102 |
+
for from_exc, to_exc in HTTPCORE_EXC_MAP.items():
|
| 103 |
+
if not isinstance(exc, from_exc):
|
| 104 |
+
continue
|
| 105 |
+
# We want to map to the most specific exception we can find.
|
| 106 |
+
# Eg if `exc` is an `httpcore2.ReadTimeout`, we want to map to
|
| 107 |
+
# `httpx2.ReadTimeout`, not just `httpx2.TimeoutException`.
|
| 108 |
+
if mapped_exc is None or issubclass(to_exc, mapped_exc):
|
| 109 |
+
mapped_exc = to_exc
|
| 110 |
+
|
| 111 |
+
if mapped_exc is None: # pragma: no cover
|
| 112 |
+
raise
|
| 113 |
+
|
| 114 |
+
message = str(exc)
|
| 115 |
+
raise mapped_exc(message) from exc
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
class ResponseStream(SyncByteStream):
|
| 119 |
+
def __init__(self, httpcore_stream: typing.Iterable[bytes]) -> None:
|
| 120 |
+
self._httpcore_stream = httpcore_stream
|
| 121 |
+
|
| 122 |
+
def __iter__(self) -> typing.Iterator[bytes]:
|
| 123 |
+
with map_httpcore_exceptions():
|
| 124 |
+
yield from self._httpcore_stream
|
| 125 |
+
|
| 126 |
+
def close(self) -> None:
|
| 127 |
+
if hasattr(self._httpcore_stream, "close"):
|
| 128 |
+
self._httpcore_stream.close()
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
class HTTPTransport(BaseTransport):
|
| 132 |
+
def __init__(
|
| 133 |
+
self,
|
| 134 |
+
verify: ssl.SSLContext | str | bool = True,
|
| 135 |
+
cert: CertTypes | None = None,
|
| 136 |
+
trust_env: bool = True,
|
| 137 |
+
http1: bool = True,
|
| 138 |
+
http2: bool = False,
|
| 139 |
+
limits: Limits = DEFAULT_LIMITS,
|
| 140 |
+
proxy: ProxyTypes | None = None,
|
| 141 |
+
uds: str | None = None,
|
| 142 |
+
local_address: str | None = None,
|
| 143 |
+
retries: int = 0,
|
| 144 |
+
socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
|
| 145 |
+
) -> None:
|
| 146 |
+
import httpcore2
|
| 147 |
+
|
| 148 |
+
proxy = Proxy(url=proxy) if isinstance(proxy, (str, URL)) else proxy
|
| 149 |
+
ssl_context = create_ssl_context(verify=verify, cert=cert, trust_env=trust_env)
|
| 150 |
+
|
| 151 |
+
if proxy is None:
|
| 152 |
+
self._pool = httpcore2.ConnectionPool(
|
| 153 |
+
ssl_context=ssl_context,
|
| 154 |
+
max_connections=limits.max_connections,
|
| 155 |
+
max_keepalive_connections=limits.max_keepalive_connections,
|
| 156 |
+
keepalive_expiry=limits.keepalive_expiry,
|
| 157 |
+
http1=http1,
|
| 158 |
+
http2=http2,
|
| 159 |
+
uds=uds,
|
| 160 |
+
local_address=local_address,
|
| 161 |
+
retries=retries,
|
| 162 |
+
socket_options=socket_options,
|
| 163 |
+
)
|
| 164 |
+
elif proxy.url.scheme in ("http", "https"):
|
| 165 |
+
self._pool = httpcore2.HTTPProxy(
|
| 166 |
+
proxy_url=httpcore2.URL(
|
| 167 |
+
scheme=proxy.url.raw_scheme,
|
| 168 |
+
host=proxy.url.raw_host,
|
| 169 |
+
port=proxy.url.port,
|
| 170 |
+
target=proxy.url.raw_path,
|
| 171 |
+
),
|
| 172 |
+
proxy_auth=proxy.raw_auth,
|
| 173 |
+
proxy_headers=proxy.headers.raw,
|
| 174 |
+
ssl_context=ssl_context,
|
| 175 |
+
proxy_ssl_context=proxy.ssl_context,
|
| 176 |
+
max_connections=limits.max_connections,
|
| 177 |
+
max_keepalive_connections=limits.max_keepalive_connections,
|
| 178 |
+
keepalive_expiry=limits.keepalive_expiry,
|
| 179 |
+
http1=http1,
|
| 180 |
+
http2=http2,
|
| 181 |
+
socket_options=socket_options,
|
| 182 |
+
)
|
| 183 |
+
elif proxy.url.scheme in ("socks5", "socks5h"):
|
| 184 |
+
try:
|
| 185 |
+
import socksio # noqa
|
| 186 |
+
except ImportError: # pragma: no cover
|
| 187 |
+
raise ImportError(
|
| 188 |
+
"Using SOCKS proxy, but the 'socksio' package is not installed. "
|
| 189 |
+
"Make sure to install httpx using `pip install httpx[socks]`."
|
| 190 |
+
) from None
|
| 191 |
+
|
| 192 |
+
self._pool = httpcore2.SOCKSProxy(
|
| 193 |
+
proxy_url=httpcore2.URL(
|
| 194 |
+
scheme=proxy.url.raw_scheme,
|
| 195 |
+
host=proxy.url.raw_host,
|
| 196 |
+
port=proxy.url.port,
|
| 197 |
+
target=proxy.url.raw_path,
|
| 198 |
+
),
|
| 199 |
+
proxy_auth=proxy.raw_auth,
|
| 200 |
+
ssl_context=ssl_context,
|
| 201 |
+
max_connections=limits.max_connections,
|
| 202 |
+
max_keepalive_connections=limits.max_keepalive_connections,
|
| 203 |
+
keepalive_expiry=limits.keepalive_expiry,
|
| 204 |
+
http1=http1,
|
| 205 |
+
http2=http2,
|
| 206 |
+
)
|
| 207 |
+
else: # pragma: no cover
|
| 208 |
+
raise ValueError(
|
| 209 |
+
f"Proxy protocol must be either 'http', 'https', 'socks5', or 'socks5h', but got {proxy.url.scheme!r}."
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
def __enter__(self: T) -> T: # Use generics for subclass support.
|
| 213 |
+
self._pool.__enter__()
|
| 214 |
+
return self
|
| 215 |
+
|
| 216 |
+
def __exit__(
|
| 217 |
+
self,
|
| 218 |
+
exc_type: type[BaseException] | None = None,
|
| 219 |
+
exc_value: BaseException | None = None,
|
| 220 |
+
traceback: TracebackType | None = None,
|
| 221 |
+
) -> None:
|
| 222 |
+
with map_httpcore_exceptions():
|
| 223 |
+
self._pool.__exit__(exc_type, exc_value, traceback)
|
| 224 |
+
|
| 225 |
+
def handle_request(
|
| 226 |
+
self,
|
| 227 |
+
request: Request,
|
| 228 |
+
) -> Response:
|
| 229 |
+
assert isinstance(request.stream, SyncByteStream)
|
| 230 |
+
import httpcore2
|
| 231 |
+
|
| 232 |
+
req = httpcore2.Request(
|
| 233 |
+
method=request.method,
|
| 234 |
+
url=httpcore2.URL(
|
| 235 |
+
scheme=request.url.raw_scheme,
|
| 236 |
+
host=request.url.raw_host,
|
| 237 |
+
port=request.url.port,
|
| 238 |
+
target=request.url.raw_path,
|
| 239 |
+
),
|
| 240 |
+
headers=request.headers.raw,
|
| 241 |
+
content=request.stream,
|
| 242 |
+
extensions=request.extensions,
|
| 243 |
+
)
|
| 244 |
+
with map_httpcore_exceptions():
|
| 245 |
+
resp = self._pool.handle_request(req)
|
| 246 |
+
|
| 247 |
+
assert isinstance(resp.stream, typing.Iterable)
|
| 248 |
+
|
| 249 |
+
return Response(
|
| 250 |
+
status_code=resp.status,
|
| 251 |
+
headers=resp.headers,
|
| 252 |
+
stream=ResponseStream(resp.stream),
|
| 253 |
+
extensions=resp.extensions,
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
def close(self) -> None:
|
| 257 |
+
self._pool.close()
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
class AsyncResponseStream(AsyncByteStream):
|
| 261 |
+
def __init__(self, httpcore_stream: typing.AsyncIterable[bytes]) -> None:
|
| 262 |
+
self._httpcore_stream = httpcore_stream
|
| 263 |
+
|
| 264 |
+
async def __aiter__(self) -> typing.AsyncIterator[bytes]:
|
| 265 |
+
with map_httpcore_exceptions():
|
| 266 |
+
async for part in self._httpcore_stream:
|
| 267 |
+
yield part
|
| 268 |
+
|
| 269 |
+
async def aclose(self) -> None:
|
| 270 |
+
if hasattr(self._httpcore_stream, "aclose"):
|
| 271 |
+
await self._httpcore_stream.aclose()
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
class AsyncHTTPTransport(AsyncBaseTransport):
|
| 275 |
+
def __init__(
|
| 276 |
+
self,
|
| 277 |
+
verify: ssl.SSLContext | str | bool = True,
|
| 278 |
+
cert: CertTypes | None = None,
|
| 279 |
+
trust_env: bool = True,
|
| 280 |
+
http1: bool = True,
|
| 281 |
+
http2: bool = False,
|
| 282 |
+
limits: Limits = DEFAULT_LIMITS,
|
| 283 |
+
proxy: ProxyTypes | None = None,
|
| 284 |
+
uds: str | None = None,
|
| 285 |
+
local_address: str | None = None,
|
| 286 |
+
retries: int = 0,
|
| 287 |
+
socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
|
| 288 |
+
) -> None:
|
| 289 |
+
import httpcore2
|
| 290 |
+
|
| 291 |
+
proxy = Proxy(url=proxy) if isinstance(proxy, (str, URL)) else proxy
|
| 292 |
+
ssl_context = create_ssl_context(verify=verify, cert=cert, trust_env=trust_env)
|
| 293 |
+
|
| 294 |
+
if proxy is None:
|
| 295 |
+
self._pool = httpcore2.AsyncConnectionPool(
|
| 296 |
+
ssl_context=ssl_context,
|
| 297 |
+
max_connections=limits.max_connections,
|
| 298 |
+
max_keepalive_connections=limits.max_keepalive_connections,
|
| 299 |
+
keepalive_expiry=limits.keepalive_expiry,
|
| 300 |
+
http1=http1,
|
| 301 |
+
http2=http2,
|
| 302 |
+
uds=uds,
|
| 303 |
+
local_address=local_address,
|
| 304 |
+
retries=retries,
|
| 305 |
+
socket_options=socket_options,
|
| 306 |
+
)
|
| 307 |
+
elif proxy.url.scheme in ("http", "https"):
|
| 308 |
+
self._pool = httpcore2.AsyncHTTPProxy(
|
| 309 |
+
proxy_url=httpcore2.URL(
|
| 310 |
+
scheme=proxy.url.raw_scheme,
|
| 311 |
+
host=proxy.url.raw_host,
|
| 312 |
+
port=proxy.url.port,
|
| 313 |
+
target=proxy.url.raw_path,
|
| 314 |
+
),
|
| 315 |
+
proxy_auth=proxy.raw_auth,
|
| 316 |
+
proxy_headers=proxy.headers.raw,
|
| 317 |
+
proxy_ssl_context=proxy.ssl_context,
|
| 318 |
+
ssl_context=ssl_context,
|
| 319 |
+
max_connections=limits.max_connections,
|
| 320 |
+
max_keepalive_connections=limits.max_keepalive_connections,
|
| 321 |
+
keepalive_expiry=limits.keepalive_expiry,
|
| 322 |
+
http1=http1,
|
| 323 |
+
http2=http2,
|
| 324 |
+
socket_options=socket_options,
|
| 325 |
+
)
|
| 326 |
+
elif proxy.url.scheme in ("socks5", "socks5h"):
|
| 327 |
+
try:
|
| 328 |
+
import socksio # noqa
|
| 329 |
+
except ImportError: # pragma: no cover
|
| 330 |
+
raise ImportError(
|
| 331 |
+
"Using SOCKS proxy, but the 'socksio' package is not installed. "
|
| 332 |
+
"Make sure to install httpx using `pip install httpx[socks]`."
|
| 333 |
+
) from None
|
| 334 |
+
|
| 335 |
+
self._pool = httpcore2.AsyncSOCKSProxy(
|
| 336 |
+
proxy_url=httpcore2.URL(
|
| 337 |
+
scheme=proxy.url.raw_scheme,
|
| 338 |
+
host=proxy.url.raw_host,
|
| 339 |
+
port=proxy.url.port,
|
| 340 |
+
target=proxy.url.raw_path,
|
| 341 |
+
),
|
| 342 |
+
proxy_auth=proxy.raw_auth,
|
| 343 |
+
ssl_context=ssl_context,
|
| 344 |
+
max_connections=limits.max_connections,
|
| 345 |
+
max_keepalive_connections=limits.max_keepalive_connections,
|
| 346 |
+
keepalive_expiry=limits.keepalive_expiry,
|
| 347 |
+
http1=http1,
|
| 348 |
+
http2=http2,
|
| 349 |
+
)
|
| 350 |
+
else: # pragma: no cover
|
| 351 |
+
raise ValueError(
|
| 352 |
+
f"Proxy protocol must be either 'http', 'https', 'socks5', or 'socks5h', but got {proxy.url.scheme!r}."
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
async def __aenter__(self: A) -> A: # Use generics for subclass support.
|
| 356 |
+
await self._pool.__aenter__()
|
| 357 |
+
return self
|
| 358 |
+
|
| 359 |
+
async def __aexit__(
|
| 360 |
+
self,
|
| 361 |
+
exc_type: type[BaseException] | None = None,
|
| 362 |
+
exc_value: BaseException | None = None,
|
| 363 |
+
traceback: TracebackType | None = None,
|
| 364 |
+
) -> None:
|
| 365 |
+
with map_httpcore_exceptions():
|
| 366 |
+
await self._pool.__aexit__(exc_type, exc_value, traceback)
|
| 367 |
+
|
| 368 |
+
async def handle_async_request(
|
| 369 |
+
self,
|
| 370 |
+
request: Request,
|
| 371 |
+
) -> Response:
|
| 372 |
+
assert isinstance(request.stream, AsyncByteStream)
|
| 373 |
+
import httpcore2
|
| 374 |
+
|
| 375 |
+
req = httpcore2.Request(
|
| 376 |
+
method=request.method,
|
| 377 |
+
url=httpcore2.URL(
|
| 378 |
+
scheme=request.url.raw_scheme,
|
| 379 |
+
host=request.url.raw_host,
|
| 380 |
+
port=request.url.port,
|
| 381 |
+
target=request.url.raw_path,
|
| 382 |
+
),
|
| 383 |
+
headers=request.headers.raw,
|
| 384 |
+
content=request.stream,
|
| 385 |
+
extensions=request.extensions,
|
| 386 |
+
)
|
| 387 |
+
with map_httpcore_exceptions():
|
| 388 |
+
resp = await self._pool.handle_async_request(req)
|
| 389 |
+
|
| 390 |
+
assert isinstance(resp.stream, typing.AsyncIterable)
|
| 391 |
+
|
| 392 |
+
return Response(
|
| 393 |
+
status_code=resp.status,
|
| 394 |
+
headers=resp.headers,
|
| 395 |
+
stream=AsyncResponseStream(resp.stream),
|
| 396 |
+
extensions=resp.extensions,
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
async def aclose(self) -> None:
|
| 400 |
+
await self._pool.aclose()
|
.venv/lib/python3.12/site-packages/httpx2/_transports/mock.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import typing
|
| 4 |
+
|
| 5 |
+
from .._models import Request, Response
|
| 6 |
+
from .base import AsyncBaseTransport, BaseTransport
|
| 7 |
+
|
| 8 |
+
SyncHandler = typing.Callable[[Request], Response]
|
| 9 |
+
AsyncHandler = typing.Callable[[Request], typing.Coroutine[None, None, Response]]
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
__all__ = ["MockTransport"]
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class MockTransport(AsyncBaseTransport, BaseTransport):
|
| 16 |
+
def __init__(self, handler: SyncHandler | AsyncHandler) -> None:
|
| 17 |
+
self.handler = handler
|
| 18 |
+
|
| 19 |
+
def handle_request(
|
| 20 |
+
self,
|
| 21 |
+
request: Request,
|
| 22 |
+
) -> Response:
|
| 23 |
+
request.read()
|
| 24 |
+
response = self.handler(request)
|
| 25 |
+
if not isinstance(response, Response): # pragma: no cover
|
| 26 |
+
raise TypeError("Cannot use an async handler in a sync Client")
|
| 27 |
+
return response
|
| 28 |
+
|
| 29 |
+
async def handle_async_request(self, request: Request) -> Response:
|
| 30 |
+
await request.aread()
|
| 31 |
+
response = self.handler(request)
|
| 32 |
+
|
| 33 |
+
# Allow handler to *optionally* be an `async` function.
|
| 34 |
+
# If it is, then the `response` variable need to be awaited to actually
|
| 35 |
+
# return the result.
|
| 36 |
+
|
| 37 |
+
if not isinstance(response, Response):
|
| 38 |
+
response = await response
|
| 39 |
+
|
| 40 |
+
return response
|
.venv/lib/python3.12/site-packages/httpx2/_transports/wsgi.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import io
|
| 4 |
+
import itertools
|
| 5 |
+
import sys
|
| 6 |
+
import typing
|
| 7 |
+
|
| 8 |
+
from .._models import Request, Response
|
| 9 |
+
from .._types import SyncByteStream
|
| 10 |
+
from .base import BaseTransport
|
| 11 |
+
|
| 12 |
+
if typing.TYPE_CHECKING:
|
| 13 |
+
from _typeshed import OptExcInfo # pragma: no cover
|
| 14 |
+
from _typeshed.wsgi import WSGIApplication # pragma: no cover
|
| 15 |
+
|
| 16 |
+
_T = typing.TypeVar("_T")
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
__all__ = ["WSGITransport"]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _skip_leading_empty_chunks(body: typing.Iterable[_T]) -> typing.Iterable[_T]:
|
| 23 |
+
body = iter(body)
|
| 24 |
+
for chunk in body:
|
| 25 |
+
if chunk:
|
| 26 |
+
return itertools.chain([chunk], body)
|
| 27 |
+
return []
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class WSGIByteStream(SyncByteStream):
|
| 31 |
+
def __init__(self, result: typing.Iterable[bytes]) -> None:
|
| 32 |
+
self._close = getattr(result, "close", None)
|
| 33 |
+
self._result = _skip_leading_empty_chunks(result)
|
| 34 |
+
|
| 35 |
+
def __iter__(self) -> typing.Iterator[bytes]:
|
| 36 |
+
yield from self._result
|
| 37 |
+
|
| 38 |
+
def close(self) -> None:
|
| 39 |
+
if self._close is not None:
|
| 40 |
+
self._close()
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class WSGITransport(BaseTransport):
|
| 44 |
+
"""
|
| 45 |
+
A custom transport that handles sending requests directly to an WSGI app.
|
| 46 |
+
The simplest way to use this functionality is to use the `app` argument.
|
| 47 |
+
|
| 48 |
+
```
|
| 49 |
+
client = httpx2.Client(app=app)
|
| 50 |
+
```
|
| 51 |
+
|
| 52 |
+
Alternatively, you can setup the transport instance explicitly.
|
| 53 |
+
This allows you to include any additional configuration arguments specific
|
| 54 |
+
to the WSGITransport class:
|
| 55 |
+
|
| 56 |
+
```
|
| 57 |
+
transport = httpx2.WSGITransport(
|
| 58 |
+
app=app,
|
| 59 |
+
script_name="/submount",
|
| 60 |
+
remote_addr="1.2.3.4"
|
| 61 |
+
)
|
| 62 |
+
client = httpx2.Client(transport=transport)
|
| 63 |
+
```
|
| 64 |
+
|
| 65 |
+
Arguments:
|
| 66 |
+
app: The WSGI application.
|
| 67 |
+
raise_app_exceptions: Boolean indicating if exceptions in the application
|
| 68 |
+
should be raised. Default to `True`. Can be set to `False` for use cases
|
| 69 |
+
such as testing the content of a client 500 response.
|
| 70 |
+
script_name: The root path on which the WSGI application should be mounted.
|
| 71 |
+
remote_addr: A string indicating the client IP of incoming requests.
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
def __init__(
|
| 75 |
+
self,
|
| 76 |
+
app: WSGIApplication,
|
| 77 |
+
raise_app_exceptions: bool = True,
|
| 78 |
+
script_name: str = "",
|
| 79 |
+
remote_addr: str = "127.0.0.1",
|
| 80 |
+
wsgi_errors: typing.TextIO | None = None,
|
| 81 |
+
) -> None:
|
| 82 |
+
self.app = app
|
| 83 |
+
self.raise_app_exceptions = raise_app_exceptions
|
| 84 |
+
self.script_name = script_name
|
| 85 |
+
self.remote_addr = remote_addr
|
| 86 |
+
self.wsgi_errors = wsgi_errors
|
| 87 |
+
|
| 88 |
+
def handle_request(self, request: Request) -> Response:
|
| 89 |
+
request.read()
|
| 90 |
+
wsgi_input = io.BytesIO(request.content)
|
| 91 |
+
|
| 92 |
+
port = request.url.port or {"http": 80, "https": 443}[request.url.scheme]
|
| 93 |
+
environ = {
|
| 94 |
+
"wsgi.version": (1, 0),
|
| 95 |
+
"wsgi.url_scheme": request.url.scheme,
|
| 96 |
+
"wsgi.input": wsgi_input,
|
| 97 |
+
"wsgi.errors": self.wsgi_errors or sys.stderr,
|
| 98 |
+
"wsgi.multithread": True,
|
| 99 |
+
"wsgi.multiprocess": False,
|
| 100 |
+
"wsgi.run_once": False,
|
| 101 |
+
"REQUEST_METHOD": request.method,
|
| 102 |
+
"SCRIPT_NAME": self.script_name,
|
| 103 |
+
"PATH_INFO": request.url.path,
|
| 104 |
+
"QUERY_STRING": request.url.query.decode("ascii"),
|
| 105 |
+
"SERVER_NAME": request.url.host,
|
| 106 |
+
"SERVER_PORT": str(port),
|
| 107 |
+
"SERVER_PROTOCOL": "HTTP/1.1",
|
| 108 |
+
"REMOTE_ADDR": self.remote_addr,
|
| 109 |
+
}
|
| 110 |
+
if request.content and "Content-Length" not in request.headers:
|
| 111 |
+
environ["CONTENT_LENGTH"] = str(len(request.content))
|
| 112 |
+
for header_key, header_value in request.headers.raw:
|
| 113 |
+
key = header_key.decode("ascii").upper().replace("-", "_")
|
| 114 |
+
if key not in ("CONTENT_TYPE", "CONTENT_LENGTH"):
|
| 115 |
+
key = "HTTP_" + key
|
| 116 |
+
environ[key] = header_value.decode("ascii")
|
| 117 |
+
|
| 118 |
+
seen_status = None
|
| 119 |
+
seen_response_headers = None
|
| 120 |
+
seen_exc_info = None
|
| 121 |
+
|
| 122 |
+
def start_response(
|
| 123 |
+
status: str,
|
| 124 |
+
response_headers: list[tuple[str, str]],
|
| 125 |
+
exc_info: OptExcInfo | None = None,
|
| 126 |
+
) -> typing.Callable[[bytes], typing.Any]:
|
| 127 |
+
nonlocal seen_status, seen_response_headers, seen_exc_info
|
| 128 |
+
seen_status = status
|
| 129 |
+
seen_response_headers = response_headers
|
| 130 |
+
seen_exc_info = exc_info
|
| 131 |
+
return lambda _: None
|
| 132 |
+
|
| 133 |
+
result = self.app(environ, start_response)
|
| 134 |
+
|
| 135 |
+
stream = WSGIByteStream(result)
|
| 136 |
+
|
| 137 |
+
assert seen_status is not None
|
| 138 |
+
assert seen_response_headers is not None
|
| 139 |
+
if seen_exc_info and seen_exc_info[0] and self.raise_app_exceptions:
|
| 140 |
+
raise seen_exc_info[1]
|
| 141 |
+
|
| 142 |
+
status_code = int(seen_status.split()[0])
|
| 143 |
+
headers = [(key.encode("ascii"), value.encode("ascii")) for key, value in seen_response_headers]
|
| 144 |
+
|
| 145 |
+
return Response(status_code, headers=headers, stream=stream)
|
.venv/lib/python3.12/site-packages/httpx2/_types.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Type definitions for type checking purposes.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from collections.abc import AsyncIterable, AsyncIterator, Callable, Iterable, Iterator, Mapping, Sequence
|
| 6 |
+
from http.cookiejar import CookieJar
|
| 7 |
+
from typing import IO, TYPE_CHECKING, Any, Union
|
| 8 |
+
|
| 9 |
+
if TYPE_CHECKING:
|
| 10 |
+
from ._auth import Auth # noqa: F401
|
| 11 |
+
from ._config import Proxy, Timeout # noqa: F401
|
| 12 |
+
from ._models import Cookies, Headers, Request # noqa: F401
|
| 13 |
+
from ._urls import URL, QueryParams # noqa: F401
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
PrimitiveData = str | int | float | bool | None
|
| 17 |
+
|
| 18 |
+
URLTypes = Union["URL", str]
|
| 19 |
+
|
| 20 |
+
QueryParamTypes = Union[
|
| 21 |
+
"QueryParams",
|
| 22 |
+
Mapping[str, PrimitiveData | Sequence[PrimitiveData]],
|
| 23 |
+
list[tuple[str, PrimitiveData]],
|
| 24 |
+
tuple[tuple[str, PrimitiveData], ...],
|
| 25 |
+
str,
|
| 26 |
+
bytes,
|
| 27 |
+
]
|
| 28 |
+
|
| 29 |
+
HeaderTypes = Union[
|
| 30 |
+
"Headers",
|
| 31 |
+
Mapping[str, str],
|
| 32 |
+
Mapping[bytes, bytes],
|
| 33 |
+
Sequence[tuple[str, str]],
|
| 34 |
+
Sequence[tuple[bytes, bytes]],
|
| 35 |
+
]
|
| 36 |
+
|
| 37 |
+
CookieTypes = Union["Cookies", CookieJar, dict[str, str], list[tuple[str, str]]]
|
| 38 |
+
|
| 39 |
+
TimeoutTypes = Union[float | None, tuple[float | None, float | None, float | None, float | None], "Timeout"]
|
| 40 |
+
ProxyTypes = Union["URL", str, "Proxy"]
|
| 41 |
+
CertTypes = str | tuple[str, str] | tuple[str, str, str]
|
| 42 |
+
|
| 43 |
+
AuthTypes = Union[tuple[str | bytes, str | bytes], Callable[["Request"], "Request"], "Auth"]
|
| 44 |
+
|
| 45 |
+
RequestContent = str | bytes | Iterable[bytes] | AsyncIterable[bytes]
|
| 46 |
+
ResponseContent = str | bytes | Iterable[bytes] | AsyncIterable[bytes]
|
| 47 |
+
ResponseExtensions = Mapping[str, Any]
|
| 48 |
+
|
| 49 |
+
RequestData = Mapping[str, Any]
|
| 50 |
+
|
| 51 |
+
FileContent = IO[bytes] | bytes | str
|
| 52 |
+
FileTypes = (
|
| 53 |
+
# # file (or bytes)
|
| 54 |
+
FileContent
|
| 55 |
+
# # (filename, file (or bytes))
|
| 56 |
+
| tuple[str | None, FileContent]
|
| 57 |
+
# # (filename, file (or bytes), content_type)
|
| 58 |
+
| tuple[str | None, FileContent, str | None]
|
| 59 |
+
| tuple[str | None, FileContent, str | None, Mapping[str, str]]
|
| 60 |
+
)
|
| 61 |
+
RequestFiles = Mapping[str, FileTypes] | Sequence[tuple[str, FileTypes]]
|
| 62 |
+
|
| 63 |
+
RequestExtensions = Mapping[str, Any]
|
| 64 |
+
|
| 65 |
+
__all__ = ["AsyncByteStream", "SyncByteStream"]
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class SyncByteStream:
|
| 69 |
+
def __iter__(self) -> Iterator[bytes]:
|
| 70 |
+
raise NotImplementedError("The '__iter__' method must be implemented.") # pragma: no cover
|
| 71 |
+
yield b"" # pragma: no cover
|
| 72 |
+
|
| 73 |
+
def close(self) -> None:
|
| 74 |
+
"""
|
| 75 |
+
Subclasses can override this method to release any network resources
|
| 76 |
+
after a request/response cycle is complete.
|
| 77 |
+
"""
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class AsyncByteStream:
|
| 81 |
+
async def __aiter__(self) -> AsyncIterator[bytes]:
|
| 82 |
+
raise NotImplementedError("The '__aiter__' method must be implemented.") # pragma: no cover
|
| 83 |
+
yield b"" # pragma: no cover
|
| 84 |
+
|
| 85 |
+
async def aclose(self) -> None:
|
| 86 |
+
pass
|
.venv/lib/python3.12/site-packages/httpx2/_urlparse.py
ADDED
|
@@ -0,0 +1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| 3 |
+
as described by RFC3986.
|
| 4 |
+
|
| 5 |
+
We rely on this implementation rather than the one in Python's stdlib, because:
|
| 6 |
+
|
| 7 |
+
* It provides more complete URL validation.
|
| 8 |
+
* It properly differentiates between an empty querystring and an absent querystring,
|
| 9 |
+
to distinguish URLs with a trailing '?'.
|
| 10 |
+
* It handles scheme, hostname, port, and path normalization.
|
| 11 |
+
* It supports IDNA hostnames, normalizing them to their encoded form.
|
| 12 |
+
* The API supports passing individual components, as well as the complete URL string.
|
| 13 |
+
|
| 14 |
+
Previously we relied on the excellent `rfc3986` package to handle URL parsing and
|
| 15 |
+
validation, but this module provides a simpler alternative, with less indirection
|
| 16 |
+
required.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
import ipaddress
|
| 22 |
+
import re
|
| 23 |
+
import typing
|
| 24 |
+
|
| 25 |
+
import idna
|
| 26 |
+
|
| 27 |
+
from ._exceptions import InvalidURL
|
| 28 |
+
|
| 29 |
+
MAX_URL_LENGTH = 65536
|
| 30 |
+
|
| 31 |
+
# https://datatracker.ietf.org/doc/html/rfc3986.html#section-2.3
|
| 32 |
+
UNRESERVED_CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"
|
| 33 |
+
SUB_DELIMS = "!$&'()*+,;="
|
| 34 |
+
|
| 35 |
+
PERCENT_ENCODED_REGEX = re.compile("%[A-Fa-f0-9]{2}")
|
| 36 |
+
|
| 37 |
+
# https://url.spec.whatwg.org/#percent-encoded-bytes
|
| 38 |
+
|
| 39 |
+
# The fragment percent-encode set is the C0 control percent-encode set
|
| 40 |
+
# and U+0020 SPACE, U+0022 ("), U+003C (<), U+003E (>), and U+0060 (`).
|
| 41 |
+
FRAG_SAFE = "".join([chr(i) for i in range(0x20, 0x7F) if i not in (0x20, 0x22, 0x3C, 0x3E, 0x60)])
|
| 42 |
+
|
| 43 |
+
# The query percent-encode set is the C0 control percent-encode set
|
| 44 |
+
# and U+0020 SPACE, U+0022 ("), U+0023 (#), U+003C (<), and U+003E (>).
|
| 45 |
+
QUERY_SAFE = "".join([chr(i) for i in range(0x20, 0x7F) if i not in (0x20, 0x22, 0x23, 0x3C, 0x3E)])
|
| 46 |
+
|
| 47 |
+
# The path percent-encode set is the query percent-encode set
|
| 48 |
+
# and U+003F (?), U+0060 (`), U+007B ({), and U+007D (}).
|
| 49 |
+
PATH_SAFE = "".join(
|
| 50 |
+
[chr(i) for i in range(0x20, 0x7F) if i not in (0x20, 0x22, 0x23, 0x3C, 0x3E) + (0x3F, 0x60, 0x7B, 0x7D)]
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
# The userinfo percent-encode set is the path percent-encode set
|
| 54 |
+
# and U+002F (/), U+003A (:), U+003B (;), U+003D (=), U+0040 (@),
|
| 55 |
+
# U+005B ([) to U+005E (^), inclusive, and U+007C (|).
|
| 56 |
+
USERNAME_SAFE = "".join(
|
| 57 |
+
[
|
| 58 |
+
chr(i)
|
| 59 |
+
for i in range(0x20, 0x7F)
|
| 60 |
+
if i
|
| 61 |
+
not in (0x20, 0x22, 0x23, 0x3C, 0x3E)
|
| 62 |
+
+ (0x3F, 0x60, 0x7B, 0x7D)
|
| 63 |
+
+ (0x2F, 0x3A, 0x3B, 0x3D, 0x40, 0x5B, 0x5C, 0x5D, 0x5E, 0x7C)
|
| 64 |
+
]
|
| 65 |
+
)
|
| 66 |
+
PASSWORD_SAFE = "".join(
|
| 67 |
+
[
|
| 68 |
+
chr(i)
|
| 69 |
+
for i in range(0x20, 0x7F)
|
| 70 |
+
if i
|
| 71 |
+
not in (0x20, 0x22, 0x23, 0x3C, 0x3E)
|
| 72 |
+
+ (0x3F, 0x60, 0x7B, 0x7D)
|
| 73 |
+
+ (0x2F, 0x3A, 0x3B, 0x3D, 0x40, 0x5B, 0x5C, 0x5D, 0x5E, 0x7C)
|
| 74 |
+
]
|
| 75 |
+
)
|
| 76 |
+
# Note... The terminology 'userinfo' percent-encode set in the WHATWG document
|
| 77 |
+
# is used for the username and password quoting. For the joint userinfo component
|
| 78 |
+
# we remove U+003A (:) from the safe set.
|
| 79 |
+
USERINFO_SAFE = "".join(
|
| 80 |
+
[
|
| 81 |
+
chr(i)
|
| 82 |
+
for i in range(0x20, 0x7F)
|
| 83 |
+
if i
|
| 84 |
+
not in (0x20, 0x22, 0x23, 0x3C, 0x3E)
|
| 85 |
+
+ (0x3F, 0x60, 0x7B, 0x7D)
|
| 86 |
+
+ (0x2F, 0x3B, 0x3D, 0x40, 0x5B, 0x5C, 0x5D, 0x5E, 0x7C)
|
| 87 |
+
]
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
# {scheme}: (optional)
|
| 92 |
+
# //{authority} (optional)
|
| 93 |
+
# {path}
|
| 94 |
+
# ?{query} (optional)
|
| 95 |
+
# #{fragment} (optional)
|
| 96 |
+
URL_REGEX = re.compile(
|
| 97 |
+
(
|
| 98 |
+
r"(?:(?P<scheme>{scheme}):)?"
|
| 99 |
+
r"(?://(?P<authority>{authority}))?"
|
| 100 |
+
r"(?P<path>{path})"
|
| 101 |
+
r"(?:\?(?P<query>{query}))?"
|
| 102 |
+
r"(?:#(?P<fragment>{fragment}))?"
|
| 103 |
+
).format(
|
| 104 |
+
scheme="([a-zA-Z][a-zA-Z0-9+.-]*)?",
|
| 105 |
+
authority="[^/?#]*",
|
| 106 |
+
path="[^?#]*",
|
| 107 |
+
query="[^#]*",
|
| 108 |
+
fragment=".*",
|
| 109 |
+
)
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
# {userinfo}@ (optional)
|
| 113 |
+
# {host}
|
| 114 |
+
# :{port} (optional)
|
| 115 |
+
AUTHORITY_REGEX = re.compile(
|
| 116 |
+
(r"(?:(?P<userinfo>{userinfo})@)?" r"(?P<host>{host})" r":?(?P<port>{port})?").format(
|
| 117 |
+
userinfo=".*", # Any character sequence.
|
| 118 |
+
host="(\\[.*\\]|[^:@]*)", # Either any character sequence excluding ':' or '@',
|
| 119 |
+
# or an IPv6 address enclosed within square brackets.
|
| 120 |
+
port=".*", # Any character sequence.
|
| 121 |
+
)
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
# If we call urlparse with an individual component, then we need to regex
|
| 126 |
+
# validate that component individually.
|
| 127 |
+
# Note that we're duplicating the same strings as above. Shock! Horror!!
|
| 128 |
+
COMPONENT_REGEX = {
|
| 129 |
+
"scheme": re.compile("([a-zA-Z][a-zA-Z0-9+.-]*)?"),
|
| 130 |
+
"authority": re.compile("[^/?#]*"),
|
| 131 |
+
"path": re.compile("[^?#]*"),
|
| 132 |
+
"query": re.compile("[^#]*"),
|
| 133 |
+
"fragment": re.compile(".*"),
|
| 134 |
+
"userinfo": re.compile("[^@]*"),
|
| 135 |
+
"host": re.compile("(\\[.*\\]|[^:]*)"),
|
| 136 |
+
"port": re.compile(".*"),
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
# We use these simple regexs as a first pass before handing off to
|
| 141 |
+
# the stdlib 'ipaddress' module for IP address validation.
|
| 142 |
+
IPv4_STYLE_HOSTNAME = re.compile(r"^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$")
|
| 143 |
+
IPv6_STYLE_HOSTNAME = re.compile(r"^\[.*\]$")
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
class ParseResult(typing.NamedTuple):
|
| 147 |
+
scheme: str
|
| 148 |
+
userinfo: str
|
| 149 |
+
host: str
|
| 150 |
+
port: int | None
|
| 151 |
+
path: str
|
| 152 |
+
query: str | None
|
| 153 |
+
fragment: str | None
|
| 154 |
+
|
| 155 |
+
@property
|
| 156 |
+
def authority(self) -> str:
|
| 157 |
+
return "".join(
|
| 158 |
+
[
|
| 159 |
+
f"{self.userinfo}@" if self.userinfo else "",
|
| 160 |
+
f"[{self.host}]" if ":" in self.host else self.host,
|
| 161 |
+
f":{self.port}" if self.port is not None else "",
|
| 162 |
+
]
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
@property
|
| 166 |
+
def netloc(self) -> str:
|
| 167 |
+
return "".join(
|
| 168 |
+
[
|
| 169 |
+
f"[{self.host}]" if ":" in self.host else self.host,
|
| 170 |
+
f":{self.port}" if self.port is not None else "",
|
| 171 |
+
]
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
def copy_with(self, **kwargs: str | None) -> ParseResult:
|
| 175 |
+
if not kwargs:
|
| 176 |
+
return self
|
| 177 |
+
|
| 178 |
+
defaults = {
|
| 179 |
+
"scheme": self.scheme,
|
| 180 |
+
"authority": self.authority,
|
| 181 |
+
"path": self.path,
|
| 182 |
+
"query": self.query,
|
| 183 |
+
"fragment": self.fragment,
|
| 184 |
+
}
|
| 185 |
+
defaults.update(kwargs)
|
| 186 |
+
return urlparse("", **defaults)
|
| 187 |
+
|
| 188 |
+
def __str__(self) -> str:
|
| 189 |
+
authority = self.authority
|
| 190 |
+
return "".join(
|
| 191 |
+
[
|
| 192 |
+
f"{self.scheme}:" if self.scheme else "",
|
| 193 |
+
f"//{authority}" if authority else "",
|
| 194 |
+
self.path,
|
| 195 |
+
f"?{self.query}" if self.query is not None else "",
|
| 196 |
+
f"#{self.fragment}" if self.fragment is not None else "",
|
| 197 |
+
]
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def urlparse(url: str = "", **kwargs: str | None) -> ParseResult:
|
| 202 |
+
# Initial basic checks on allowable URLs.
|
| 203 |
+
# ---------------------------------------
|
| 204 |
+
|
| 205 |
+
# Hard limit the maximum allowable URL length.
|
| 206 |
+
if len(url) > MAX_URL_LENGTH:
|
| 207 |
+
raise InvalidURL("URL too long")
|
| 208 |
+
|
| 209 |
+
# If a URL includes any ASCII control characters including \t, \r, \n,
|
| 210 |
+
# then treat it as invalid.
|
| 211 |
+
if any(char.isascii() and not char.isprintable() for char in url):
|
| 212 |
+
char = next(char for char in url if char.isascii() and not char.isprintable())
|
| 213 |
+
idx = url.find(char)
|
| 214 |
+
error = f"Invalid non-printable ASCII character in URL, {char!r} at position {idx}."
|
| 215 |
+
raise InvalidURL(error)
|
| 216 |
+
|
| 217 |
+
# Some keyword arguments require special handling.
|
| 218 |
+
# ------------------------------------------------
|
| 219 |
+
|
| 220 |
+
# Coerce "port" to a string, if it is provided as an integer.
|
| 221 |
+
if "port" in kwargs:
|
| 222 |
+
port = kwargs["port"]
|
| 223 |
+
kwargs["port"] = str(port) if isinstance(port, int) else port
|
| 224 |
+
|
| 225 |
+
# Replace "netloc" with "host and "port".
|
| 226 |
+
if "netloc" in kwargs:
|
| 227 |
+
netloc = kwargs.pop("netloc") or ""
|
| 228 |
+
kwargs["host"], _, kwargs["port"] = netloc.partition(":")
|
| 229 |
+
|
| 230 |
+
# Replace "username" and/or "password" with "userinfo".
|
| 231 |
+
if "username" in kwargs or "password" in kwargs:
|
| 232 |
+
username = quote(kwargs.pop("username", "") or "", safe=USERNAME_SAFE)
|
| 233 |
+
password = quote(kwargs.pop("password", "") or "", safe=PASSWORD_SAFE)
|
| 234 |
+
kwargs["userinfo"] = f"{username}:{password}" if password else username
|
| 235 |
+
|
| 236 |
+
# Replace "raw_path" with "path" and "query".
|
| 237 |
+
if "raw_path" in kwargs:
|
| 238 |
+
raw_path = kwargs.pop("raw_path") or ""
|
| 239 |
+
kwargs["path"], separator, kwargs["query"] = raw_path.partition("?")
|
| 240 |
+
if not separator:
|
| 241 |
+
kwargs["query"] = None
|
| 242 |
+
|
| 243 |
+
# Ensure that IPv6 "host" addresses are always escaped with "[...]".
|
| 244 |
+
if "host" in kwargs:
|
| 245 |
+
host = kwargs.get("host") or ""
|
| 246 |
+
if ":" in host and not (host.startswith("[") and host.endswith("]")):
|
| 247 |
+
kwargs["host"] = f"[{host}]"
|
| 248 |
+
|
| 249 |
+
# If any keyword arguments are provided, ensure they are valid.
|
| 250 |
+
# -------------------------------------------------------------
|
| 251 |
+
|
| 252 |
+
for key, value in kwargs.items():
|
| 253 |
+
if value is not None:
|
| 254 |
+
if len(value) > MAX_URL_LENGTH:
|
| 255 |
+
raise InvalidURL(f"URL component '{key}' too long")
|
| 256 |
+
|
| 257 |
+
# If a component includes any ASCII control characters including \t, \r, \n,
|
| 258 |
+
# then treat it as invalid.
|
| 259 |
+
if any(char.isascii() and not char.isprintable() for char in value):
|
| 260 |
+
char = next(char for char in value if char.isascii() and not char.isprintable())
|
| 261 |
+
idx = value.find(char)
|
| 262 |
+
error = f"Invalid non-printable ASCII character in URL {key} component, {char!r} at position {idx}."
|
| 263 |
+
raise InvalidURL(error)
|
| 264 |
+
|
| 265 |
+
# Ensure that keyword arguments match as a valid regex.
|
| 266 |
+
if not COMPONENT_REGEX[key].fullmatch(value):
|
| 267 |
+
raise InvalidURL(f"Invalid URL component '{key}'")
|
| 268 |
+
|
| 269 |
+
# The URL_REGEX will always match, but may have empty components.
|
| 270 |
+
url_match = URL_REGEX.match(url)
|
| 271 |
+
assert url_match is not None
|
| 272 |
+
url_dict = url_match.groupdict()
|
| 273 |
+
|
| 274 |
+
# * 'scheme', 'authority', and 'path' may be empty strings.
|
| 275 |
+
# * 'query' may be 'None', indicating no trailing "?" portion.
|
| 276 |
+
# Any string including the empty string, indicates a trailing "?".
|
| 277 |
+
# * 'fragment' may be 'None', indicating no trailing "#" portion.
|
| 278 |
+
# Any string including the empty string, indicates a trailing "#".
|
| 279 |
+
scheme = kwargs.get("scheme", url_dict["scheme"]) or ""
|
| 280 |
+
authority = kwargs.get("authority", url_dict["authority"]) or ""
|
| 281 |
+
path = kwargs.get("path", url_dict["path"]) or ""
|
| 282 |
+
query = kwargs.get("query", url_dict["query"])
|
| 283 |
+
frag = kwargs.get("fragment", url_dict["fragment"])
|
| 284 |
+
|
| 285 |
+
# The AUTHORITY_REGEX will always match, but may have empty components.
|
| 286 |
+
authority_match = AUTHORITY_REGEX.match(authority)
|
| 287 |
+
assert authority_match is not None
|
| 288 |
+
authority_dict = authority_match.groupdict()
|
| 289 |
+
|
| 290 |
+
# * 'userinfo' and 'host' may be empty strings.
|
| 291 |
+
# * 'port' may be 'None'.
|
| 292 |
+
userinfo = kwargs.get("userinfo", authority_dict["userinfo"]) or ""
|
| 293 |
+
host = kwargs.get("host", authority_dict["host"]) or ""
|
| 294 |
+
port = kwargs.get("port", authority_dict["port"])
|
| 295 |
+
|
| 296 |
+
# Normalize and validate each component.
|
| 297 |
+
# We end up with a parsed representation of the URL,
|
| 298 |
+
# with components that are plain ASCII bytestrings.
|
| 299 |
+
parsed_scheme: str = scheme.lower()
|
| 300 |
+
parsed_userinfo: str = quote(userinfo, safe=USERINFO_SAFE)
|
| 301 |
+
parsed_host: str = encode_host(host)
|
| 302 |
+
parsed_port: int | None = normalize_port(port, scheme)
|
| 303 |
+
|
| 304 |
+
has_scheme = parsed_scheme != ""
|
| 305 |
+
has_authority = parsed_userinfo != "" or parsed_host != "" or parsed_port is not None
|
| 306 |
+
validate_path(path, has_scheme=has_scheme, has_authority=has_authority)
|
| 307 |
+
if has_scheme or has_authority:
|
| 308 |
+
path = normalize_path(path)
|
| 309 |
+
|
| 310 |
+
parsed_path: str = quote(path, safe=PATH_SAFE)
|
| 311 |
+
parsed_query: str | None = None if query is None else quote(query, safe=QUERY_SAFE)
|
| 312 |
+
parsed_frag: str | None = None if frag is None else quote(frag, safe=FRAG_SAFE)
|
| 313 |
+
|
| 314 |
+
# The parsed ASCII bytestrings are our canonical form.
|
| 315 |
+
# All properties of the URL are derived from these.
|
| 316 |
+
return ParseResult(
|
| 317 |
+
parsed_scheme,
|
| 318 |
+
parsed_userinfo,
|
| 319 |
+
parsed_host,
|
| 320 |
+
parsed_port,
|
| 321 |
+
parsed_path,
|
| 322 |
+
parsed_query,
|
| 323 |
+
parsed_frag,
|
| 324 |
+
)
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def encode_host(host: str) -> str:
|
| 328 |
+
if not host:
|
| 329 |
+
return ""
|
| 330 |
+
|
| 331 |
+
elif IPv4_STYLE_HOSTNAME.match(host):
|
| 332 |
+
# Validate IPv4 hostnames like #.#.#.#
|
| 333 |
+
#
|
| 334 |
+
# From https://datatracker.ietf.org/doc/html/rfc3986/#section-3.2.2
|
| 335 |
+
#
|
| 336 |
+
# IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet
|
| 337 |
+
try:
|
| 338 |
+
ipaddress.IPv4Address(host)
|
| 339 |
+
except ipaddress.AddressValueError:
|
| 340 |
+
raise InvalidURL(f"Invalid IPv4 address: {host!r}")
|
| 341 |
+
return host
|
| 342 |
+
|
| 343 |
+
elif IPv6_STYLE_HOSTNAME.match(host):
|
| 344 |
+
# Validate IPv6 hostnames like [...]
|
| 345 |
+
#
|
| 346 |
+
# From https://datatracker.ietf.org/doc/html/rfc3986/#section-3.2.2
|
| 347 |
+
#
|
| 348 |
+
# "A host identified by an Internet Protocol literal address, version 6
|
| 349 |
+
# [RFC3513] or later, is distinguished by enclosing the IP literal
|
| 350 |
+
# within square brackets ("[" and "]"). This is the only place where
|
| 351 |
+
# square bracket characters are allowed in the URI syntax."
|
| 352 |
+
try:
|
| 353 |
+
ipaddress.IPv6Address(host[1:-1])
|
| 354 |
+
except ipaddress.AddressValueError:
|
| 355 |
+
raise InvalidURL(f"Invalid IPv6 address: {host!r}")
|
| 356 |
+
return host[1:-1]
|
| 357 |
+
|
| 358 |
+
elif host.isascii():
|
| 359 |
+
# Regular ASCII hostnames
|
| 360 |
+
#
|
| 361 |
+
# From https://datatracker.ietf.org/doc/html/rfc3986/#section-3.2.2
|
| 362 |
+
#
|
| 363 |
+
# reg-name = *( unreserved / pct-encoded / sub-delims )
|
| 364 |
+
WHATWG_SAFE = '"`{}%|\\'
|
| 365 |
+
return quote(host.lower(), safe=SUB_DELIMS + WHATWG_SAFE)
|
| 366 |
+
|
| 367 |
+
# IDNA hostnames
|
| 368 |
+
try:
|
| 369 |
+
return idna.encode(host.lower()).decode("ascii")
|
| 370 |
+
except idna.IDNAError:
|
| 371 |
+
raise InvalidURL(f"Invalid IDNA hostname: {host!r}")
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
def normalize_port(port: str | int | None, scheme: str) -> int | None:
|
| 375 |
+
# From https://tools.ietf.org/html/rfc3986#section-3.2.3
|
| 376 |
+
#
|
| 377 |
+
# "A scheme may define a default port. For example, the "http" scheme
|
| 378 |
+
# defines a default port of "80", corresponding to its reserved TCP
|
| 379 |
+
# port number. The type of port designated by the port number (e.g.,
|
| 380 |
+
# TCP, UDP, SCTP) is defined by the URI scheme. URI producers and
|
| 381 |
+
# normalizers should omit the port component and its ":" delimiter if
|
| 382 |
+
# port is empty or if its value would be the same as that of the
|
| 383 |
+
# scheme's default."
|
| 384 |
+
if port is None or port == "":
|
| 385 |
+
return None
|
| 386 |
+
|
| 387 |
+
try:
|
| 388 |
+
port_as_int = int(port)
|
| 389 |
+
except ValueError:
|
| 390 |
+
raise InvalidURL(f"Invalid port: {port!r}")
|
| 391 |
+
|
| 392 |
+
# See https://url.spec.whatwg.org/#url-miscellaneous
|
| 393 |
+
default_port = {"ftp": 21, "http": 80, "https": 443, "ws": 80, "wss": 443}.get(scheme)
|
| 394 |
+
if port_as_int == default_port:
|
| 395 |
+
return None
|
| 396 |
+
return port_as_int
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
def validate_path(path: str, has_scheme: bool, has_authority: bool) -> None:
|
| 400 |
+
"""
|
| 401 |
+
Path validation rules that depend on if the URL contains
|
| 402 |
+
a scheme or authority component.
|
| 403 |
+
|
| 404 |
+
See https://datatracker.ietf.org/doc/html/rfc3986.html#section-3.3
|
| 405 |
+
"""
|
| 406 |
+
if has_authority:
|
| 407 |
+
# If a URI contains an authority component, then the path component
|
| 408 |
+
# must either be empty or begin with a slash ("/") character."
|
| 409 |
+
if path and not path.startswith("/"):
|
| 410 |
+
raise InvalidURL("For absolute URLs, path must be empty or begin with '/'")
|
| 411 |
+
|
| 412 |
+
if not has_scheme and not has_authority:
|
| 413 |
+
# If a URI does not contain an authority component, then the path cannot begin
|
| 414 |
+
# with two slash characters ("//").
|
| 415 |
+
if path.startswith("//"):
|
| 416 |
+
raise InvalidURL("Relative URLs cannot have a path starting with '//'")
|
| 417 |
+
|
| 418 |
+
# In addition, a URI reference (Section 4.1) may be a relative-path reference,
|
| 419 |
+
# in which case the first path segment cannot contain a colon (":") character.
|
| 420 |
+
if path.startswith(":"):
|
| 421 |
+
raise InvalidURL("Relative URLs cannot have a path starting with ':'")
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
def normalize_path(path: str) -> str:
|
| 425 |
+
"""
|
| 426 |
+
Drop "." and ".." segments from a URL path.
|
| 427 |
+
|
| 428 |
+
For example:
|
| 429 |
+
|
| 430 |
+
normalize_path("/path/./to/somewhere/..") == "/path/to"
|
| 431 |
+
"""
|
| 432 |
+
# Fast return when no '.' characters in the path.
|
| 433 |
+
if "." not in path:
|
| 434 |
+
return path
|
| 435 |
+
|
| 436 |
+
components = path.split("/")
|
| 437 |
+
|
| 438 |
+
# Fast return when no '.' or '..' components in the path.
|
| 439 |
+
if "." not in components and ".." not in components:
|
| 440 |
+
return path
|
| 441 |
+
|
| 442 |
+
# https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4
|
| 443 |
+
output: list[str] = []
|
| 444 |
+
for component in components:
|
| 445 |
+
if component == ".":
|
| 446 |
+
pass
|
| 447 |
+
elif component == "..":
|
| 448 |
+
if output and output != [""]:
|
| 449 |
+
output.pop()
|
| 450 |
+
else:
|
| 451 |
+
output.append(component)
|
| 452 |
+
return "/".join(output)
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
def PERCENT(string: str) -> str:
|
| 456 |
+
return "".join([f"%{byte:02X}" for byte in string.encode("utf-8")])
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
def percent_encoded(string: str, safe: str) -> str:
|
| 460 |
+
"""
|
| 461 |
+
Use percent-encoding to quote a string.
|
| 462 |
+
"""
|
| 463 |
+
NON_ESCAPED_CHARS = UNRESERVED_CHARACTERS + safe
|
| 464 |
+
|
| 465 |
+
# Fast path for strings that don't need escaping.
|
| 466 |
+
if not string.rstrip(NON_ESCAPED_CHARS):
|
| 467 |
+
return string
|
| 468 |
+
|
| 469 |
+
return "".join([char if char in NON_ESCAPED_CHARS else PERCENT(char) for char in string])
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
def quote(string: str, safe: str) -> str:
|
| 473 |
+
"""
|
| 474 |
+
Use percent-encoding to quote a string, omitting existing '%xx' escape sequences.
|
| 475 |
+
|
| 476 |
+
See: https://www.rfc-editor.org/rfc/rfc3986#section-2.1
|
| 477 |
+
|
| 478 |
+
* `string`: The string to be percent-escaped.
|
| 479 |
+
* `safe`: A string containing characters that may be treated as safe, and do not
|
| 480 |
+
need to be escaped. Unreserved characters are always treated as safe.
|
| 481 |
+
See: https://www.rfc-editor.org/rfc/rfc3986#section-2.3
|
| 482 |
+
"""
|
| 483 |
+
parts: list[str] = []
|
| 484 |
+
current_position = 0
|
| 485 |
+
for match in re.finditer(PERCENT_ENCODED_REGEX, string):
|
| 486 |
+
start_position, end_position = match.start(), match.end()
|
| 487 |
+
matched_text = match.group(0)
|
| 488 |
+
# Add any text up to the '%xx' escape sequence.
|
| 489 |
+
if start_position != current_position:
|
| 490 |
+
leading_text = string[current_position:start_position]
|
| 491 |
+
parts.append(percent_encoded(leading_text, safe=safe))
|
| 492 |
+
|
| 493 |
+
# Add the '%xx' escape sequence.
|
| 494 |
+
parts.append(matched_text)
|
| 495 |
+
current_position = end_position
|
| 496 |
+
|
| 497 |
+
# Add any text after the final '%xx' escape sequence.
|
| 498 |
+
if current_position != len(string):
|
| 499 |
+
trailing_text = string[current_position:]
|
| 500 |
+
parts.append(percent_encoded(trailing_text, safe=safe))
|
| 501 |
+
|
| 502 |
+
return "".join(parts)
|
.venv/lib/python3.12/site-packages/httpx2/_urls.py
ADDED
|
@@ -0,0 +1,689 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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ddress
|
| 4 |
+
import sys
|
| 5 |
+
import typing
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
from urllib.parse import parse_qs, unquote, urlencode
|
| 8 |
+
|
| 9 |
+
import idna
|
| 10 |
+
|
| 11 |
+
if sys.version_info >= (3, 13):
|
| 12 |
+
from warnings import deprecated # pragma: no cover
|
| 13 |
+
else:
|
| 14 |
+
from typing_extensions import deprecated # pragma: no cover
|
| 15 |
+
|
| 16 |
+
from ._exceptions import HTTPXDeprecationWarning
|
| 17 |
+
from ._types import QueryParamTypes
|
| 18 |
+
from ._urlparse import urlparse
|
| 19 |
+
from ._utils import primitive_value_to_str
|
| 20 |
+
|
| 21 |
+
__all__ = ["URL", "Origin", "QueryParams"]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class URL:
|
| 25 |
+
"""
|
| 26 |
+
url = httpx2.URL("HTTPS://jo%40email.com:a%20secret@müller.de:1234/pa%20th?search=ab#anchorlink")
|
| 27 |
+
|
| 28 |
+
assert url.scheme == "https"
|
| 29 |
+
assert url.username == "jo@email.com"
|
| 30 |
+
assert url.password == "a secret"
|
| 31 |
+
assert url.userinfo == b"jo%40email.com:a%20secret"
|
| 32 |
+
assert url.host == "müller.de"
|
| 33 |
+
assert url.raw_host == b"xn--mller-kva.de"
|
| 34 |
+
assert url.port == 1234
|
| 35 |
+
assert url.netloc == b"xn--mller-kva.de:1234"
|
| 36 |
+
assert url.path == "/pa th"
|
| 37 |
+
assert url.query == b"search=ab"
|
| 38 |
+
assert url.raw_path == b"/pa%20th?search=ab"
|
| 39 |
+
assert url.fragment == "anchorlink"
|
| 40 |
+
|
| 41 |
+
The components of a URL are broken down like this:
|
| 42 |
+
|
| 43 |
+
https://jo%40email.com:a%20secret@müller.de:1234/pa%20th?search=ab#anchorlink
|
| 44 |
+
[scheme] [ username ] [password] [ host ][port][ path ] [ query ] [fragment]
|
| 45 |
+
[ userinfo ] [ netloc ][ raw_path ]
|
| 46 |
+
|
| 47 |
+
Note that:
|
| 48 |
+
|
| 49 |
+
* `url.scheme` is normalized to always be lowercased.
|
| 50 |
+
|
| 51 |
+
* `url.host` is normalized to always be lowercased. Internationalized domain
|
| 52 |
+
names are represented in unicode, without IDNA encoding applied. For instance:
|
| 53 |
+
|
| 54 |
+
url = httpx2.URL("http://中国.icom.museum")
|
| 55 |
+
assert url.host == "中国.icom.museum"
|
| 56 |
+
url = httpx2.URL("http://xn--fiqs8s.icom.museum")
|
| 57 |
+
assert url.host == "中国.icom.museum"
|
| 58 |
+
|
| 59 |
+
* `url.raw_host` is normalized to always be lowercased, and is IDNA encoded.
|
| 60 |
+
|
| 61 |
+
url = httpx2.URL("http://中国.icom.museum")
|
| 62 |
+
assert url.raw_host == b"xn--fiqs8s.icom.museum"
|
| 63 |
+
url = httpx2.URL("http://xn--fiqs8s.icom.museum")
|
| 64 |
+
assert url.raw_host == b"xn--fiqs8s.icom.museum"
|
| 65 |
+
|
| 66 |
+
* `url.port` is either None or an integer. URLs that include the default port for
|
| 67 |
+
"http", "https", "ws", "wss", and "ftp" schemes have their port
|
| 68 |
+
normalized to `None`.
|
| 69 |
+
|
| 70 |
+
assert httpx2.URL("http://example.com") == httpx2.URL("http://example.com:80")
|
| 71 |
+
assert httpx2.URL("http://example.com").port is None
|
| 72 |
+
assert httpx2.URL("http://example.com:80").port is None
|
| 73 |
+
|
| 74 |
+
* `url.userinfo` is raw bytes, without URL escaping. Usually you'll want to work
|
| 75 |
+
with `url.username` and `url.password` instead, which handle the URL escaping.
|
| 76 |
+
|
| 77 |
+
* `url.raw_path` is raw bytes of both the path and query, without URL escaping.
|
| 78 |
+
This portion is used as the target when constructing HTTP requests. Usually you'll
|
| 79 |
+
want to work with `url.path` instead.
|
| 80 |
+
|
| 81 |
+
* `url.query` is raw bytes, without URL escaping. A URL query string portion can
|
| 82 |
+
only be properly URL escaped when decoding the parameter names and values
|
| 83 |
+
themselves.
|
| 84 |
+
"""
|
| 85 |
+
|
| 86 |
+
def __init__(self, url: URL | str = "", **kwargs: typing.Any) -> None:
|
| 87 |
+
if kwargs:
|
| 88 |
+
allowed = {
|
| 89 |
+
"scheme": str,
|
| 90 |
+
"username": str,
|
| 91 |
+
"password": str,
|
| 92 |
+
"userinfo": bytes,
|
| 93 |
+
"host": str,
|
| 94 |
+
"port": int,
|
| 95 |
+
"netloc": bytes,
|
| 96 |
+
"path": str,
|
| 97 |
+
"query": bytes,
|
| 98 |
+
"raw_path": bytes,
|
| 99 |
+
"fragment": str,
|
| 100 |
+
"params": object,
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
# Perform type checking for all supported keyword arguments.
|
| 104 |
+
for key, value in kwargs.items():
|
| 105 |
+
if key not in allowed:
|
| 106 |
+
message = f"{key!r} is an invalid keyword argument for URL()"
|
| 107 |
+
raise TypeError(message)
|
| 108 |
+
if value is not None and not isinstance(value, allowed[key]):
|
| 109 |
+
expected = allowed[key].__name__
|
| 110 |
+
seen = type(value).__name__
|
| 111 |
+
message = f"Argument {key!r} must be {expected} but got {seen}"
|
| 112 |
+
raise TypeError(message)
|
| 113 |
+
if isinstance(value, bytes):
|
| 114 |
+
kwargs[key] = value.decode("ascii")
|
| 115 |
+
|
| 116 |
+
if "params" in kwargs:
|
| 117 |
+
# Replace any "params" keyword with the raw "query" instead.
|
| 118 |
+
#
|
| 119 |
+
# Ensure that empty params use `kwargs["query"] = None` rather
|
| 120 |
+
# than `kwargs["query"] = ""`, so that generated URLs do not
|
| 121 |
+
# include an empty trailing "?".
|
| 122 |
+
params = kwargs.pop("params")
|
| 123 |
+
kwargs["query"] = None if not params else str(QueryParams(params))
|
| 124 |
+
|
| 125 |
+
if isinstance(url, str):
|
| 126 |
+
self._uri_reference = urlparse(url, **kwargs)
|
| 127 |
+
elif isinstance(url, URL):
|
| 128 |
+
self._uri_reference = url._uri_reference.copy_with(**kwargs)
|
| 129 |
+
else:
|
| 130 |
+
raise TypeError(f"Invalid type for url. Expected str or httpx2.URL, got {type(url)}: {url!r}")
|
| 131 |
+
|
| 132 |
+
@property
|
| 133 |
+
def scheme(self) -> str:
|
| 134 |
+
"""
|
| 135 |
+
The URL scheme, such as "http", "https".
|
| 136 |
+
Always normalised to lowercase.
|
| 137 |
+
"""
|
| 138 |
+
return self._uri_reference.scheme
|
| 139 |
+
|
| 140 |
+
@property
|
| 141 |
+
def raw_scheme(self) -> bytes:
|
| 142 |
+
"""
|
| 143 |
+
The raw bytes representation of the URL scheme, such as b"http", b"https".
|
| 144 |
+
Always normalised to lowercase.
|
| 145 |
+
"""
|
| 146 |
+
return self._uri_reference.scheme.encode("ascii")
|
| 147 |
+
|
| 148 |
+
@property
|
| 149 |
+
def userinfo(self) -> bytes:
|
| 150 |
+
"""
|
| 151 |
+
The URL userinfo as a raw bytestring.
|
| 152 |
+
For example: b"jo%40email.com:a%20secret".
|
| 153 |
+
"""
|
| 154 |
+
return self._uri_reference.userinfo.encode("ascii")
|
| 155 |
+
|
| 156 |
+
@property
|
| 157 |
+
def username(self) -> str:
|
| 158 |
+
"""
|
| 159 |
+
The URL username as a string, with URL decoding applied.
|
| 160 |
+
For example: "jo@email.com"
|
| 161 |
+
"""
|
| 162 |
+
userinfo = self._uri_reference.userinfo
|
| 163 |
+
return unquote(userinfo.partition(":")[0])
|
| 164 |
+
|
| 165 |
+
@property
|
| 166 |
+
def password(self) -> str:
|
| 167 |
+
"""
|
| 168 |
+
The URL password as a string, with URL decoding applied.
|
| 169 |
+
For example: "a secret"
|
| 170 |
+
"""
|
| 171 |
+
userinfo = self._uri_reference.userinfo
|
| 172 |
+
return unquote(userinfo.partition(":")[2])
|
| 173 |
+
|
| 174 |
+
@property
|
| 175 |
+
def host(self) -> str:
|
| 176 |
+
"""
|
| 177 |
+
The URL host as a string.
|
| 178 |
+
Always normalized to lowercase, with IDNA hosts decoded into unicode.
|
| 179 |
+
|
| 180 |
+
Examples:
|
| 181 |
+
|
| 182 |
+
url = httpx2.URL("http://www.EXAMPLE.org")
|
| 183 |
+
assert url.host == "www.example.org"
|
| 184 |
+
|
| 185 |
+
url = httpx2.URL("http://中国.icom.museum")
|
| 186 |
+
assert url.host == "中国.icom.museum"
|
| 187 |
+
|
| 188 |
+
url = httpx2.URL("http://xn--fiqs8s.icom.museum")
|
| 189 |
+
assert url.host == "中国.icom.museum"
|
| 190 |
+
|
| 191 |
+
url = httpx2.URL("https://[::ffff:192.168.0.1]")
|
| 192 |
+
assert url.host == "::ffff:192.168.0.1"
|
| 193 |
+
"""
|
| 194 |
+
host: str = self._uri_reference.host
|
| 195 |
+
|
| 196 |
+
if "xn--" in host:
|
| 197 |
+
host = idna.decode(host, display=True)
|
| 198 |
+
|
| 199 |
+
return host
|
| 200 |
+
|
| 201 |
+
@property
|
| 202 |
+
def raw_host(self) -> bytes:
|
| 203 |
+
"""
|
| 204 |
+
The raw bytes representation of the URL host.
|
| 205 |
+
Always normalized to lowercase, and IDNA encoded.
|
| 206 |
+
|
| 207 |
+
Examples:
|
| 208 |
+
|
| 209 |
+
url = httpx2.URL("http://www.EXAMPLE.org")
|
| 210 |
+
assert url.raw_host == b"www.example.org"
|
| 211 |
+
|
| 212 |
+
url = httpx2.URL("http://中国.icom.museum")
|
| 213 |
+
assert url.raw_host == b"xn--fiqs8s.icom.museum"
|
| 214 |
+
|
| 215 |
+
url = httpx2.URL("http://xn--fiqs8s.icom.museum")
|
| 216 |
+
assert url.raw_host == b"xn--fiqs8s.icom.museum"
|
| 217 |
+
|
| 218 |
+
url = httpx2.URL("https://[::ffff:192.168.0.1]")
|
| 219 |
+
assert url.raw_host == b"::ffff:192.168.0.1"
|
| 220 |
+
"""
|
| 221 |
+
return self._uri_reference.host.encode("ascii")
|
| 222 |
+
|
| 223 |
+
@property
|
| 224 |
+
def port(self) -> int | None:
|
| 225 |
+
"""
|
| 226 |
+
The URL port as an integer.
|
| 227 |
+
|
| 228 |
+
Note that the URL class performs port normalization as per the WHATWG spec.
|
| 229 |
+
Default ports for "http", "https", "ws", "wss", and "ftp" schemes are always
|
| 230 |
+
treated as `None`.
|
| 231 |
+
|
| 232 |
+
For example:
|
| 233 |
+
|
| 234 |
+
assert httpx2.URL("http://www.example.com") == httpx2.URL("http://www.example.com:80")
|
| 235 |
+
assert httpx2.URL("http://www.example.com:80").port is None
|
| 236 |
+
"""
|
| 237 |
+
return self._uri_reference.port
|
| 238 |
+
|
| 239 |
+
@property
|
| 240 |
+
def netloc(self) -> bytes:
|
| 241 |
+
"""
|
| 242 |
+
Either `<host>` or `<host>:<port>` as bytes.
|
| 243 |
+
Always normalized to lowercase, and IDNA encoded.
|
| 244 |
+
|
| 245 |
+
This property may be used for generating the value of a request
|
| 246 |
+
"Host" header.
|
| 247 |
+
"""
|
| 248 |
+
return self._uri_reference.netloc.encode("ascii")
|
| 249 |
+
|
| 250 |
+
@property
|
| 251 |
+
def path(self) -> str:
|
| 252 |
+
"""
|
| 253 |
+
The URL path as a string. Excluding the query string, and URL decoded.
|
| 254 |
+
|
| 255 |
+
For example:
|
| 256 |
+
|
| 257 |
+
url = httpx2.URL("https://example.com/pa%20th")
|
| 258 |
+
assert url.path == "/pa th"
|
| 259 |
+
"""
|
| 260 |
+
path = self._uri_reference.path or "/"
|
| 261 |
+
return unquote(path)
|
| 262 |
+
|
| 263 |
+
@property
|
| 264 |
+
def query(self) -> bytes:
|
| 265 |
+
"""
|
| 266 |
+
The URL query string, as raw bytes, excluding the leading b"?".
|
| 267 |
+
|
| 268 |
+
This is necessarily a bytewise interface, because we cannot
|
| 269 |
+
perform URL decoding of this representation until we've parsed
|
| 270 |
+
the keys and values into a QueryParams instance.
|
| 271 |
+
|
| 272 |
+
For example:
|
| 273 |
+
|
| 274 |
+
url = httpx2.URL("https://example.com/?filter=some%20search%20terms")
|
| 275 |
+
assert url.query == b"filter=some%20search%20terms"
|
| 276 |
+
"""
|
| 277 |
+
query = self._uri_reference.query or ""
|
| 278 |
+
return query.encode("ascii")
|
| 279 |
+
|
| 280 |
+
@property
|
| 281 |
+
def params(self) -> QueryParams:
|
| 282 |
+
"""
|
| 283 |
+
The URL query parameters, neatly parsed and packaged into an immutable
|
| 284 |
+
multidict representation.
|
| 285 |
+
"""
|
| 286 |
+
return QueryParams(self._uri_reference.query)
|
| 287 |
+
|
| 288 |
+
@property
|
| 289 |
+
def raw_path(self) -> bytes:
|
| 290 |
+
"""
|
| 291 |
+
The complete URL path and query string as raw bytes.
|
| 292 |
+
Used as the target when constructing HTTP requests.
|
| 293 |
+
|
| 294 |
+
For example:
|
| 295 |
+
|
| 296 |
+
GET /users?search=some%20text HTTP/1.1
|
| 297 |
+
Host: www.example.org
|
| 298 |
+
Connection: close
|
| 299 |
+
"""
|
| 300 |
+
path = self._uri_reference.path or "/"
|
| 301 |
+
if self._uri_reference.query is not None:
|
| 302 |
+
path += "?" + self._uri_reference.query
|
| 303 |
+
return path.encode("ascii")
|
| 304 |
+
|
| 305 |
+
@property
|
| 306 |
+
def fragment(self) -> str:
|
| 307 |
+
"""
|
| 308 |
+
The URL fragments, as used in HTML anchors.
|
| 309 |
+
As a string, without the leading '#'.
|
| 310 |
+
"""
|
| 311 |
+
return unquote(self._uri_reference.fragment or "")
|
| 312 |
+
|
| 313 |
+
@property
|
| 314 |
+
def is_absolute_url(self) -> bool:
|
| 315 |
+
"""
|
| 316 |
+
Return `True` for absolute URLs such as 'http://example.com/path',
|
| 317 |
+
and `False` for relative URLs such as '/path'.
|
| 318 |
+
"""
|
| 319 |
+
# We don't use `.is_absolute` from `rfc3986` because it treats
|
| 320 |
+
# URLs with a fragment portion as not absolute.
|
| 321 |
+
# What we actually care about is if the URL provides
|
| 322 |
+
# a scheme and hostname to which connections should be made.
|
| 323 |
+
return bool(self._uri_reference.scheme and self._uri_reference.host)
|
| 324 |
+
|
| 325 |
+
@property
|
| 326 |
+
def is_relative_url(self) -> bool:
|
| 327 |
+
"""
|
| 328 |
+
Return `False` for absolute URLs such as 'http://example.com/path',
|
| 329 |
+
and `True` for relative URLs such as '/path'.
|
| 330 |
+
"""
|
| 331 |
+
return not self.is_absolute_url
|
| 332 |
+
|
| 333 |
+
@property
|
| 334 |
+
def origin(self) -> Origin:
|
| 335 |
+
"""
|
| 336 |
+
The URL origin as an immutable, hashable `Origin` value.
|
| 337 |
+
|
| 338 |
+
The origin consists of the URL scheme, host, and effective port.
|
| 339 |
+
User information, path, query, and fragment components are excluded.
|
| 340 |
+
"""
|
| 341 |
+
return Origin(self)
|
| 342 |
+
|
| 343 |
+
def copy_with(self, **kwargs: typing.Any) -> URL:
|
| 344 |
+
"""
|
| 345 |
+
Copy this URL, returning a new URL with some components altered.
|
| 346 |
+
Accepts the same set of parameters as the components that are made
|
| 347 |
+
available via properties on the `URL` class.
|
| 348 |
+
|
| 349 |
+
For example:
|
| 350 |
+
|
| 351 |
+
url = httpx2.URL("https://www.example.com").copy_with(
|
| 352 |
+
username="jo@gmail.com", password="a secret"
|
| 353 |
+
)
|
| 354 |
+
assert url == "https://jo%40email.com:a%20secret@www.example.com"
|
| 355 |
+
"""
|
| 356 |
+
return URL(self, **kwargs)
|
| 357 |
+
|
| 358 |
+
def copy_set_param(self, key: str, value: typing.Any = None) -> URL:
|
| 359 |
+
return self.copy_with(params=self.params.set(key, value))
|
| 360 |
+
|
| 361 |
+
def copy_add_param(self, key: str, value: typing.Any = None) -> URL:
|
| 362 |
+
return self.copy_with(params=self.params.add(key, value))
|
| 363 |
+
|
| 364 |
+
def copy_remove_param(self, key: str) -> URL:
|
| 365 |
+
return self.copy_with(params=self.params.remove(key))
|
| 366 |
+
|
| 367 |
+
def copy_merge_params(self, params: QueryParamTypes) -> URL:
|
| 368 |
+
return self.copy_with(params=self.params.merge(params))
|
| 369 |
+
|
| 370 |
+
def join(self, url: URL | str) -> URL:
|
| 371 |
+
"""
|
| 372 |
+
Return an absolute URL, using this URL as the base.
|
| 373 |
+
|
| 374 |
+
Eg.
|
| 375 |
+
|
| 376 |
+
url = httpx2.URL("https://www.example.com/test")
|
| 377 |
+
url = url.join("/new/path")
|
| 378 |
+
assert url == "https://www.example.com/new/path"
|
| 379 |
+
"""
|
| 380 |
+
from urllib.parse import urljoin
|
| 381 |
+
|
| 382 |
+
return URL(urljoin(str(self), str(URL(url))))
|
| 383 |
+
|
| 384 |
+
def __hash__(self) -> int:
|
| 385 |
+
return hash(str(self))
|
| 386 |
+
|
| 387 |
+
def __eq__(self, other: typing.Any) -> bool:
|
| 388 |
+
return isinstance(other, (URL, str)) and str(self) == str(URL(other))
|
| 389 |
+
|
| 390 |
+
def __str__(self) -> str:
|
| 391 |
+
return str(self._uri_reference)
|
| 392 |
+
|
| 393 |
+
def __repr__(self) -> str:
|
| 394 |
+
scheme, userinfo, host, port, path, query, fragment = self._uri_reference
|
| 395 |
+
|
| 396 |
+
if ":" in userinfo:
|
| 397 |
+
# Mask any password component.
|
| 398 |
+
userinfo = f"{userinfo.split(':')[0]}:[secure]"
|
| 399 |
+
|
| 400 |
+
authority = "".join(
|
| 401 |
+
[
|
| 402 |
+
f"{userinfo}@" if userinfo else "",
|
| 403 |
+
f"[{host}]" if ":" in host else host,
|
| 404 |
+
f":{port}" if port is not None else "",
|
| 405 |
+
]
|
| 406 |
+
)
|
| 407 |
+
url = "".join(
|
| 408 |
+
[
|
| 409 |
+
f"{self.scheme}:" if scheme else "",
|
| 410 |
+
f"//{authority}" if authority else "",
|
| 411 |
+
path,
|
| 412 |
+
f"?{query}" if query is not None else "",
|
| 413 |
+
f"#{fragment}" if fragment is not None else "",
|
| 414 |
+
]
|
| 415 |
+
)
|
| 416 |
+
|
| 417 |
+
return f"{self.__class__.__name__}({url!r})"
|
| 418 |
+
|
| 419 |
+
@property
|
| 420 |
+
@deprecated("URL.raw is deprecated.", category=HTTPXDeprecationWarning)
|
| 421 |
+
def raw(self) -> tuple[bytes, bytes, int, bytes]: # pragma: no cover
|
| 422 |
+
import collections
|
| 423 |
+
|
| 424 |
+
RawURL = collections.namedtuple("RawURL", ["raw_scheme", "raw_host", "port", "raw_path"])
|
| 425 |
+
return RawURL(
|
| 426 |
+
raw_scheme=self.raw_scheme,
|
| 427 |
+
raw_host=self.raw_host,
|
| 428 |
+
port=self.port,
|
| 429 |
+
raw_path=self.raw_path,
|
| 430 |
+
)
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
_ORIGIN_DEFAULT_PORTS = {
|
| 434 |
+
"ftp": 21,
|
| 435 |
+
"http": 80,
|
| 436 |
+
"https": 443,
|
| 437 |
+
"ws": 80,
|
| 438 |
+
"wss": 443,
|
| 439 |
+
}
|
| 440 |
+
|
| 441 |
+
|
| 442 |
+
@dataclass(frozen=True, slots=True, init=False)
|
| 443 |
+
class Origin:
|
| 444 |
+
"""
|
| 445 |
+
The scheme, host, and effective port of a URL.
|
| 446 |
+
|
| 447 |
+
Origins are normalized, immutable, comparable, and hashable.
|
| 448 |
+
|
| 449 |
+
See RFC 9110, Section 4.3.1: https://www.rfc-editor.org/rfc/rfc9110.html#name-uri-origin
|
| 450 |
+
"""
|
| 451 |
+
|
| 452 |
+
scheme: str
|
| 453 |
+
host: str
|
| 454 |
+
port: int | None
|
| 455 |
+
|
| 456 |
+
def __init__(self, url: URL | str) -> None:
|
| 457 |
+
if not isinstance(url, URL):
|
| 458 |
+
url = URL(url)
|
| 459 |
+
|
| 460 |
+
if url.is_relative_url:
|
| 461 |
+
raise ValueError("URL must be absolute to have an origin")
|
| 462 |
+
|
| 463 |
+
host = url.host
|
| 464 |
+
if b":" in url.raw_host:
|
| 465 |
+
# IPv6 addresses may have multiple equivalent string forms. Store
|
| 466 |
+
# their canonical compressed form so origin equality is numeric.
|
| 467 |
+
host = str(ipaddress.IPv6Address(url.raw_host.decode("ascii")))
|
| 468 |
+
|
| 469 |
+
port = url.port
|
| 470 |
+
if port is None:
|
| 471 |
+
port = _ORIGIN_DEFAULT_PORTS.get(url.scheme)
|
| 472 |
+
|
| 473 |
+
object.__setattr__(self, "scheme", url.scheme)
|
| 474 |
+
object.__setattr__(self, "host", host)
|
| 475 |
+
object.__setattr__(self, "port", port)
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
class QueryParams(typing.Mapping[str, str]):
|
| 479 |
+
"""
|
| 480 |
+
URL query parameters, as a multi-dict.
|
| 481 |
+
"""
|
| 482 |
+
|
| 483 |
+
def __init__(self, *args: QueryParamTypes | None, **kwargs: typing.Any) -> None:
|
| 484 |
+
assert len(args) < 2, "Too many arguments."
|
| 485 |
+
assert not (args and kwargs), "Cannot mix named and unnamed arguments."
|
| 486 |
+
|
| 487 |
+
value = args[0] if args else kwargs
|
| 488 |
+
|
| 489 |
+
if value is None or isinstance(value, (str, bytes)):
|
| 490 |
+
value = value.decode("ascii") if isinstance(value, bytes) else value
|
| 491 |
+
self._dict = parse_qs(value, keep_blank_values=True)
|
| 492 |
+
elif isinstance(value, QueryParams):
|
| 493 |
+
self._dict = {k: list(v) for k, v in value._dict.items()}
|
| 494 |
+
else:
|
| 495 |
+
dict_value: dict[typing.Any, list[typing.Any]] = {}
|
| 496 |
+
if isinstance(value, (list, tuple)):
|
| 497 |
+
# Convert list inputs like:
|
| 498 |
+
# [("a", "123"), ("a", "456"), ("b", "789")]
|
| 499 |
+
# To a dict representation, like:
|
| 500 |
+
# {"a": ["123", "456"], "b": ["789"]}
|
| 501 |
+
for item in value:
|
| 502 |
+
dict_value.setdefault(item[0], []).append(item[1])
|
| 503 |
+
else:
|
| 504 |
+
# Convert dict inputs like:
|
| 505 |
+
# {"a": "123", "b": ["456", "789"]}
|
| 506 |
+
# To dict inputs where values are always lists, like:
|
| 507 |
+
# {"a": ["123"], "b": ["456", "789"]}
|
| 508 |
+
dict_value = {k: list(v) if isinstance(v, (list, tuple)) else [v] for k, v in value.items()}
|
| 509 |
+
|
| 510 |
+
# Ensure that keys and values are neatly coerced to strings.
|
| 511 |
+
# We coerce values `True` and `False` to JSON-like "true" and "false"
|
| 512 |
+
# representations, and coerce `None` values to the empty string.
|
| 513 |
+
self._dict = {str(k): [primitive_value_to_str(item) for item in v] for k, v in dict_value.items()}
|
| 514 |
+
|
| 515 |
+
def keys(self) -> typing.KeysView[str]:
|
| 516 |
+
"""
|
| 517 |
+
Return all the keys in the query params.
|
| 518 |
+
|
| 519 |
+
Usage:
|
| 520 |
+
|
| 521 |
+
q = httpx2.QueryParams("a=123&a=456&b=789")
|
| 522 |
+
assert list(q.keys()) == ["a", "b"]
|
| 523 |
+
"""
|
| 524 |
+
return self._dict.keys()
|
| 525 |
+
|
| 526 |
+
def values(self) -> typing.ValuesView[str]:
|
| 527 |
+
"""
|
| 528 |
+
Return all the values in the query params. If a key occurs more than once
|
| 529 |
+
only the first item for that key is returned.
|
| 530 |
+
|
| 531 |
+
Usage:
|
| 532 |
+
|
| 533 |
+
q = httpx2.QueryParams("a=123&a=456&b=789")
|
| 534 |
+
assert list(q.values()) == ["123", "789"]
|
| 535 |
+
"""
|
| 536 |
+
return {k: v[0] for k, v in self._dict.items()}.values()
|
| 537 |
+
|
| 538 |
+
def items(self) -> typing.ItemsView[str, str]:
|
| 539 |
+
"""
|
| 540 |
+
Return all items in the query params. If a key occurs more than once
|
| 541 |
+
only the first item for that key is returned.
|
| 542 |
+
|
| 543 |
+
Usage:
|
| 544 |
+
|
| 545 |
+
q = httpx2.QueryParams("a=123&a=456&b=789")
|
| 546 |
+
assert list(q.items()) == [("a", "123"), ("b", "789")]
|
| 547 |
+
"""
|
| 548 |
+
return {k: v[0] for k, v in self._dict.items()}.items()
|
| 549 |
+
|
| 550 |
+
def multi_items(self) -> list[tuple[str, str]]:
|
| 551 |
+
"""
|
| 552 |
+
Return all items in the query params. Allow duplicate keys to occur.
|
| 553 |
+
|
| 554 |
+
Usage:
|
| 555 |
+
|
| 556 |
+
q = httpx2.QueryParams("a=123&a=456&b=789")
|
| 557 |
+
assert list(q.multi_items()) == [("a", "123"), ("a", "456"), ("b", "789")]
|
| 558 |
+
"""
|
| 559 |
+
multi_items: list[tuple[str, str]] = []
|
| 560 |
+
for k, v in self._dict.items():
|
| 561 |
+
multi_items.extend([(k, i) for i in v])
|
| 562 |
+
return multi_items
|
| 563 |
+
|
| 564 |
+
def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:
|
| 565 |
+
"""
|
| 566 |
+
Get a value from the query param for a given key. If the key occurs
|
| 567 |
+
more than once, then only the first value is returned.
|
| 568 |
+
|
| 569 |
+
Usage:
|
| 570 |
+
|
| 571 |
+
q = httpx2.QueryParams("a=123&a=456&b=789")
|
| 572 |
+
assert q.get("a") == "123"
|
| 573 |
+
"""
|
| 574 |
+
if key in self._dict:
|
| 575 |
+
return self._dict[str(key)][0]
|
| 576 |
+
return default
|
| 577 |
+
|
| 578 |
+
def get_list(self, key: str) -> list[str]:
|
| 579 |
+
"""
|
| 580 |
+
Get all values from the query param for a given key.
|
| 581 |
+
|
| 582 |
+
Usage:
|
| 583 |
+
|
| 584 |
+
q = httpx2.QueryParams("a=123&a=456&b=789")
|
| 585 |
+
assert q.get_list("a") == ["123", "456"]
|
| 586 |
+
"""
|
| 587 |
+
return list(self._dict.get(str(key), []))
|
| 588 |
+
|
| 589 |
+
def set(self, key: str, value: typing.Any = None) -> QueryParams:
|
| 590 |
+
"""
|
| 591 |
+
Return a new QueryParams instance, setting the value of a key.
|
| 592 |
+
|
| 593 |
+
Usage:
|
| 594 |
+
|
| 595 |
+
q = httpx2.QueryParams("a=123")
|
| 596 |
+
q = q.set("a", "456")
|
| 597 |
+
assert q == httpx2.QueryParams("a=456")
|
| 598 |
+
"""
|
| 599 |
+
q = QueryParams()
|
| 600 |
+
q._dict = dict(self._dict)
|
| 601 |
+
q._dict[str(key)] = [primitive_value_to_str(value)]
|
| 602 |
+
return q
|
| 603 |
+
|
| 604 |
+
def add(self, key: str, value: typing.Any = None) -> QueryParams:
|
| 605 |
+
"""
|
| 606 |
+
Return a new QueryParams instance, setting or appending the value of a key.
|
| 607 |
+
|
| 608 |
+
Usage:
|
| 609 |
+
|
| 610 |
+
q = httpx2.QueryParams("a=123")
|
| 611 |
+
q = q.add("a", "456")
|
| 612 |
+
assert q == httpx2.QueryParams("a=123&a=456")
|
| 613 |
+
"""
|
| 614 |
+
q = QueryParams()
|
| 615 |
+
q._dict = dict(self._dict)
|
| 616 |
+
q._dict[str(key)] = q.get_list(key) + [primitive_value_to_str(value)]
|
| 617 |
+
return q
|
| 618 |
+
|
| 619 |
+
def remove(self, key: str) -> QueryParams:
|
| 620 |
+
"""
|
| 621 |
+
Return a new QueryParams instance, removing the value of a key.
|
| 622 |
+
|
| 623 |
+
Usage:
|
| 624 |
+
|
| 625 |
+
q = httpx2.QueryParams("a=123")
|
| 626 |
+
q = q.remove("a")
|
| 627 |
+
assert q == httpx2.QueryParams("")
|
| 628 |
+
"""
|
| 629 |
+
q = QueryParams()
|
| 630 |
+
q._dict = dict(self._dict)
|
| 631 |
+
q._dict.pop(str(key), None)
|
| 632 |
+
return q
|
| 633 |
+
|
| 634 |
+
def merge(self, params: QueryParamTypes | None = None) -> QueryParams:
|
| 635 |
+
"""
|
| 636 |
+
Return a new QueryParams instance, updated with.
|
| 637 |
+
|
| 638 |
+
Usage:
|
| 639 |
+
|
| 640 |
+
q = httpx2.QueryParams("a=123")
|
| 641 |
+
q = q.merge({"b": "456"})
|
| 642 |
+
assert q == httpx2.QueryParams("a=123&b=456")
|
| 643 |
+
|
| 644 |
+
q = httpx2.QueryParams("a=123")
|
| 645 |
+
q = q.merge({"a": "456", "b": "789"})
|
| 646 |
+
assert q == httpx2.QueryParams("a=456&b=789")
|
| 647 |
+
"""
|
| 648 |
+
q = QueryParams(params)
|
| 649 |
+
q._dict = {**self._dict, **q._dict}
|
| 650 |
+
return q
|
| 651 |
+
|
| 652 |
+
def __getitem__(self, key: typing.Any) -> str:
|
| 653 |
+
return self._dict[key][0]
|
| 654 |
+
|
| 655 |
+
def __contains__(self, key: typing.Any) -> bool:
|
| 656 |
+
return key in self._dict
|
| 657 |
+
|
| 658 |
+
def __iter__(self) -> typing.Iterator[typing.Any]:
|
| 659 |
+
return iter(self.keys())
|
| 660 |
+
|
| 661 |
+
def __len__(self) -> int:
|
| 662 |
+
return len(self._dict)
|
| 663 |
+
|
| 664 |
+
def __bool__(self) -> bool:
|
| 665 |
+
return bool(self._dict)
|
| 666 |
+
|
| 667 |
+
def __hash__(self) -> int:
|
| 668 |
+
return hash(str(self))
|
| 669 |
+
|
| 670 |
+
def __eq__(self, other: typing.Any) -> bool:
|
| 671 |
+
if not isinstance(other, self.__class__):
|
| 672 |
+
return False
|
| 673 |
+
return sorted(self.multi_items()) == sorted(other.multi_items())
|
| 674 |
+
|
| 675 |
+
def __str__(self) -> str:
|
| 676 |
+
return urlencode(self.multi_items())
|
| 677 |
+
|
| 678 |
+
def __repr__(self) -> str:
|
| 679 |
+
class_name = self.__class__.__name__
|
| 680 |
+
query_string = str(self)
|
| 681 |
+
return f"{class_name}({query_string!r})"
|
| 682 |
+
|
| 683 |
+
def update(self, params: QueryParamTypes | None = None) -> None:
|
| 684 |
+
raise RuntimeError("QueryParams are immutable since 0.18.0. Use `q = q.merge(...)` to create an updated copy.")
|
| 685 |
+
|
| 686 |
+
def __setitem__(self, key: str, value: str) -> None:
|
| 687 |
+
raise RuntimeError(
|
| 688 |
+
"QueryParams are immutable since 0.18.0. Use `q = q.set(key, value)` to create an updated copy."
|
| 689 |
+
)
|
.venv/lib/python3.12/site-packages/httpx2/_utils.py
ADDED
|
@@ -0,0 +1,282 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import ipaddress
|
| 4 |
+
import os
|
| 5 |
+
import re
|
| 6 |
+
import typing
|
| 7 |
+
from urllib.request import getproxies
|
| 8 |
+
|
| 9 |
+
from ._exceptions import InvalidURL
|
| 10 |
+
from ._types import PrimitiveData
|
| 11 |
+
|
| 12 |
+
if typing.TYPE_CHECKING:
|
| 13 |
+
from ._urls import URL
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def primitive_value_to_str(value: PrimitiveData) -> str:
|
| 17 |
+
"""
|
| 18 |
+
Coerce a primitive data type into a string value.
|
| 19 |
+
|
| 20 |
+
Note that we prefer JSON-style 'true'/'false' for boolean values here.
|
| 21 |
+
"""
|
| 22 |
+
if value is True:
|
| 23 |
+
return "true"
|
| 24 |
+
elif value is False:
|
| 25 |
+
return "false"
|
| 26 |
+
elif value is None:
|
| 27 |
+
return ""
|
| 28 |
+
return str(value)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def get_environment_proxies() -> dict[str, str | None]:
|
| 32 |
+
"""Gets proxy information from the environment"""
|
| 33 |
+
|
| 34 |
+
# urllib.request.getproxies() falls back on System
|
| 35 |
+
# Registry and Config for proxies on Windows and macOS.
|
| 36 |
+
# We don't want to propagate non-HTTP proxies into
|
| 37 |
+
# our configuration such as 'TRAVIS_APT_PROXY'.
|
| 38 |
+
proxy_info = getproxies()
|
| 39 |
+
mounts: dict[str, str | None] = {}
|
| 40 |
+
|
| 41 |
+
for scheme in ("http", "https", "all"):
|
| 42 |
+
if proxy_info.get(scheme):
|
| 43 |
+
hostname = proxy_info[scheme]
|
| 44 |
+
mounts[f"{scheme}://"] = hostname if "://" in hostname else f"http://{hostname}"
|
| 45 |
+
|
| 46 |
+
no_proxy_hosts = [host.strip() for host in proxy_info.get("no", "").split(",")]
|
| 47 |
+
for hostname in no_proxy_hosts:
|
| 48 |
+
# See https://curl.haxx.se/libcurl/c/CURLOPT_NOPROXY.html for details
|
| 49 |
+
# on how names in `NO_PROXY` are handled.
|
| 50 |
+
if hostname == "*":
|
| 51 |
+
# If NO_PROXY=* is used or if "*" occurs as any one of the comma
|
| 52 |
+
# separated hostnames, then we should just bypass any information
|
| 53 |
+
# from HTTP_PROXY, HTTPS_PROXY, ALL_PROXY, and always ignore
|
| 54 |
+
# proxies.
|
| 55 |
+
return {}
|
| 56 |
+
elif hostname:
|
| 57 |
+
# NO_PROXY=.google.com is marked as "all://*.google.com,
|
| 58 |
+
# which disables "www.google.com" but not "google.com"
|
| 59 |
+
# NO_PROXY=google.com is marked as "all://*google.com,
|
| 60 |
+
# which disables "www.google.com" and "google.com".
|
| 61 |
+
# (But not "wwwgoogle.com")
|
| 62 |
+
# NO_PROXY can include domains, IPv6, IPv4 addresses and "localhost"
|
| 63 |
+
# NO_PROXY=example.com,::1,localhost,192.168.0.0/16
|
| 64 |
+
if "://" in hostname:
|
| 65 |
+
mounts[hostname] = None
|
| 66 |
+
elif is_ipv4_hostname(hostname):
|
| 67 |
+
mounts[f"all://{hostname}"] = None
|
| 68 |
+
elif is_ipv6_hostname(hostname):
|
| 69 |
+
if "/" in hostname:
|
| 70 |
+
addr, _, subnet = hostname.partition("/")
|
| 71 |
+
mounts[f"all://[{addr}]/{subnet}"] = None
|
| 72 |
+
else:
|
| 73 |
+
mounts[f"all://[{hostname}]"] = None
|
| 74 |
+
elif hostname.lower() == "localhost":
|
| 75 |
+
mounts[f"all://{hostname}"] = None
|
| 76 |
+
elif hostname.startswith("["):
|
| 77 |
+
mounts[f"all://{hostname}"] = None
|
| 78 |
+
elif "/" not in hostname:
|
| 79 |
+
mounts[f"all://*{hostname}"] = None
|
| 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 |
+
|
| 87 |
+
return mounts
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def to_bytes(value: str | bytes, encoding: str = "utf-8") -> bytes:
|
| 91 |
+
return value.encode(encoding) if isinstance(value, str) else value
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def to_str(value: str | bytes, encoding: str = "utf-8") -> str:
|
| 95 |
+
return value if isinstance(value, str) else value.decode(encoding)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def to_bytes_or_str(value: str, match_type_of: typing.AnyStr) -> typing.AnyStr:
|
| 99 |
+
return value if isinstance(match_type_of, str) else value.encode()
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def peek_filelike_length(stream: typing.Any) -> int | None:
|
| 103 |
+
"""
|
| 104 |
+
Given a file-like stream object, return its length in number of bytes
|
| 105 |
+
without reading it into memory.
|
| 106 |
+
"""
|
| 107 |
+
try:
|
| 108 |
+
# Is it an actual file?
|
| 109 |
+
fd = stream.fileno()
|
| 110 |
+
# Yup, seems to be an actual file.
|
| 111 |
+
length = os.fstat(fd).st_size
|
| 112 |
+
except (AttributeError, OSError):
|
| 113 |
+
# No... Maybe it's something that supports random access, like `io.BytesIO`?
|
| 114 |
+
try:
|
| 115 |
+
# Assuming so, go to end of stream to figure out its length,
|
| 116 |
+
# then put it back in place.
|
| 117 |
+
offset = stream.tell()
|
| 118 |
+
length = stream.seek(0, os.SEEK_END)
|
| 119 |
+
stream.seek(offset)
|
| 120 |
+
except (AttributeError, OSError):
|
| 121 |
+
# Not even that? Sorry, we're doomed...
|
| 122 |
+
return None
|
| 123 |
+
|
| 124 |
+
return length
|
| 125 |
+
|
| 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 |
+
|
| 139 |
+
class URLPattern:
|
| 140 |
+
"""
|
| 141 |
+
A utility class currently used for making lookups against proxy keys...
|
| 142 |
+
|
| 143 |
+
# Wildcard matching...
|
| 144 |
+
>>> pattern = URLPattern("all://")
|
| 145 |
+
>>> pattern.matches(httpx2.URL("http://example.com"))
|
| 146 |
+
True
|
| 147 |
+
|
| 148 |
+
# Witch scheme matching...
|
| 149 |
+
>>> pattern = URLPattern("https://")
|
| 150 |
+
>>> pattern.matches(httpx2.URL("https://example.com"))
|
| 151 |
+
True
|
| 152 |
+
>>> pattern.matches(httpx2.URL("http://example.com"))
|
| 153 |
+
False
|
| 154 |
+
|
| 155 |
+
# With domain matching...
|
| 156 |
+
>>> pattern = URLPattern("https://example.com")
|
| 157 |
+
>>> pattern.matches(httpx2.URL("https://example.com"))
|
| 158 |
+
True
|
| 159 |
+
>>> pattern.matches(httpx2.URL("http://example.com"))
|
| 160 |
+
False
|
| 161 |
+
>>> pattern.matches(httpx2.URL("https://other.com"))
|
| 162 |
+
False
|
| 163 |
+
|
| 164 |
+
# Wildcard scheme, with domain matching...
|
| 165 |
+
>>> pattern = URLPattern("all://example.com")
|
| 166 |
+
>>> pattern.matches(httpx2.URL("https://example.com"))
|
| 167 |
+
True
|
| 168 |
+
>>> pattern.matches(httpx2.URL("http://example.com"))
|
| 169 |
+
True
|
| 170 |
+
>>> pattern.matches(httpx2.URL("https://other.com"))
|
| 171 |
+
False
|
| 172 |
+
|
| 173 |
+
# With port matching...
|
| 174 |
+
>>> pattern = URLPattern("https://example.com:1234")
|
| 175 |
+
>>> pattern.matches(httpx2.URL("https://example.com:1234"))
|
| 176 |
+
True
|
| 177 |
+
>>> pattern.matches(httpx2.URL("https://example.com"))
|
| 178 |
+
False
|
| 179 |
+
"""
|
| 180 |
+
|
| 181 |
+
def __init__(self, pattern: str) -> None:
|
| 182 |
+
from ._urls import URL
|
| 183 |
+
|
| 184 |
+
if pattern and ":" not in pattern:
|
| 185 |
+
raise ValueError(
|
| 186 |
+
f"Proxy keys should use proper URL forms rather "
|
| 187 |
+
f"than plain scheme strings. "
|
| 188 |
+
f'Instead of "{pattern}", use "{pattern}://"'
|
| 189 |
+
)
|
| 190 |
+
|
| 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 |
+
|
| 204 |
+
self.pattern = pattern
|
| 205 |
+
self.scheme = "" if url.scheme == "all" else url.scheme
|
| 206 |
+
self.host = "" if url.host == "*" else url.host
|
| 207 |
+
self.port = url.port
|
| 208 |
+
if self.network is not None:
|
| 209 |
+
self.host_regex: typing.Pattern[str] | None = None
|
| 210 |
+
elif not url.host or url.host == "*":
|
| 211 |
+
self.host_regex = None
|
| 212 |
+
elif url.host.startswith("*."):
|
| 213 |
+
# *.example.com should match "www.example.com", but not "example.com"
|
| 214 |
+
domain = re.escape(url.host[2:])
|
| 215 |
+
self.host_regex = re.compile(f"^.+\\.{domain}$")
|
| 216 |
+
elif url.host.startswith("*"):
|
| 217 |
+
# *example.com should match "www.example.com" and "example.com"
|
| 218 |
+
domain = re.escape(url.host[1:])
|
| 219 |
+
self.host_regex = re.compile(f"^(.+\\.)?{domain}$")
|
| 220 |
+
else:
|
| 221 |
+
# example.com should match "example.com" but not "www.example.com"
|
| 222 |
+
domain = re.escape(url.host)
|
| 223 |
+
self.host_regex = re.compile(f"^{domain}$")
|
| 224 |
+
|
| 225 |
+
def matches(self, other: URL) -> bool:
|
| 226 |
+
if self.scheme and self.scheme != other.scheme:
|
| 227 |
+
return False
|
| 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):
|
| 236 |
+
return False
|
| 237 |
+
if self.port is not None and self.port != other.port:
|
| 238 |
+
return False
|
| 239 |
+
return True
|
| 240 |
+
|
| 241 |
+
@property
|
| 242 |
+
def priority(self) -> tuple[int, int, int, int, int]:
|
| 243 |
+
"""
|
| 244 |
+
The priority allows URLPattern instances to be sortable, so that
|
| 245 |
+
we can match from most specific to least specific.
|
| 246 |
+
"""
|
| 247 |
+
# URLs with a port should take priority over URLs without a port.
|
| 248 |
+
port_priority = 0 if self.port is not None else 1
|
| 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
|
| 255 |
+
# Longer schemes should match first.
|
| 256 |
+
scheme_priority = -len(self.scheme)
|
| 257 |
+
return (port_priority, host_kind_priority, network_priority, host_priority, scheme_priority)
|
| 258 |
+
|
| 259 |
+
def __hash__(self) -> int:
|
| 260 |
+
return hash(self.pattern)
|
| 261 |
+
|
| 262 |
+
def __lt__(self, other: URLPattern) -> bool:
|
| 263 |
+
return self.priority < other.priority
|
| 264 |
+
|
| 265 |
+
def __eq__(self, other: typing.Any) -> bool:
|
| 266 |
+
return isinstance(other, URLPattern) and self.pattern == other.pattern
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def is_ipv4_hostname(hostname: str) -> bool:
|
| 270 |
+
try:
|
| 271 |
+
ipaddress.IPv4Address(hostname.split("/")[0])
|
| 272 |
+
except Exception:
|
| 273 |
+
return False
|
| 274 |
+
return True
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
def is_ipv6_hostname(hostname: str) -> bool:
|
| 278 |
+
try:
|
| 279 |
+
ipaddress.IPv6Address(hostname.split("/")[0])
|
| 280 |
+
except Exception:
|
| 281 |
+
return False
|
| 282 |
+
return True
|
.venv/lib/python3.12/site-packages/httpx2/py.typed
ADDED
|
File without changes
|
.venv/lib/python3.12/site-packages/httpx2/websockets/__init__.py
ADDED
|
@@ -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 |
+
]
|
.venv/lib/python3.12/site-packages/httpx2/websockets/_api.py
ADDED
|
@@ -0,0 +1,1676 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import base64
|
| 4 |
+
import concurrent.futures
|
| 5 |
+
import contextlib
|
| 6 |
+
import json
|
| 7 |
+
import queue
|
| 8 |
+
import secrets
|
| 9 |
+
import sys
|
| 10 |
+
import threading
|
| 11 |
+
import typing
|
| 12 |
+
from types import TracebackType
|
| 13 |
+
|
| 14 |
+
if sys.version_info >= (3, 13):
|
| 15 |
+
from queue import ShutDown as QueueShutDown # pragma: no cover
|
| 16 |
+
from typing import TypeVar # pragma: no cover
|
| 17 |
+
else:
|
| 18 |
+
from typing_extensions import TypeVar # pragma: no cover
|
| 19 |
+
|
| 20 |
+
class QueueShutDown(Exception): # pragma: no cover
|
| 21 |
+
"""Stand-in for `queue.ShutDown`, which is never raised before Python 3.13."""
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
import anyio
|
| 25 |
+
import wsproto
|
| 26 |
+
import wsproto.utilities
|
| 27 |
+
from anyio.streams.memory import MemoryObjectReceiveStream, MemoryObjectSendStream
|
| 28 |
+
from wsproto.frame_protocol import CloseReason
|
| 29 |
+
|
| 30 |
+
from .._client import USE_CLIENT_DEFAULT
|
| 31 |
+
from .._config import (
|
| 32 |
+
DEFAULT_KEEPALIVE_PING_INTERVAL_SECONDS,
|
| 33 |
+
DEFAULT_KEEPALIVE_PING_TIMEOUT_SECONDS,
|
| 34 |
+
DEFAULT_MAX_MESSAGE_SIZE_BYTES,
|
| 35 |
+
DEFAULT_QUEUE_SIZE,
|
| 36 |
+
)
|
| 37 |
+
from .._models import Headers
|
| 38 |
+
from ._exceptions import (
|
| 39 |
+
HTTPXWSException,
|
| 40 |
+
WebSocketDisconnect,
|
| 41 |
+
WebSocketInvalidTypeReceived,
|
| 42 |
+
WebSocketNetworkError,
|
| 43 |
+
WebSocketUpgradeError,
|
| 44 |
+
)
|
| 45 |
+
from ._ping import AsyncPingManager, PingManager
|
| 46 |
+
from ._transport import ASGIWebSocketAsyncNetworkStream
|
| 47 |
+
|
| 48 |
+
if typing.TYPE_CHECKING:
|
| 49 |
+
from httpcore2 import AsyncNetworkStream, NetworkStream
|
| 50 |
+
|
| 51 |
+
from .._client import AsyncClient, Client, UseClientDefault
|
| 52 |
+
from .._models import Response
|
| 53 |
+
from .._types import (
|
| 54 |
+
AuthTypes,
|
| 55 |
+
CookieTypes,
|
| 56 |
+
HeaderTypes,
|
| 57 |
+
QueryParamTypes,
|
| 58 |
+
RequestExtensions,
|
| 59 |
+
TimeoutTypes,
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
JSONMode = typing.Literal["text", "binary"]
|
| 63 |
+
TaskFunction = typing.TypeVar("TaskFunction")
|
| 64 |
+
TaskResult = typing.TypeVar("TaskResult")
|
| 65 |
+
SyncSession = TypeVar("SyncSession", bound="WebSocketSession", default="WebSocketSession")
|
| 66 |
+
AsyncSession = TypeVar("AsyncSession", bound="AsyncWebSocketSession", default="AsyncWebSocketSession")
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class ShouldClose(Exception):
|
| 70 |
+
pass
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class EndOfStream(Exception):
|
| 74 |
+
pass
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class WebSocketSession:
|
| 78 |
+
"""
|
| 79 |
+
Sync context manager representing an opened WebSocket session.
|
| 80 |
+
|
| 81 |
+
Attributes:
|
| 82 |
+
subprotocol (typing.Optional[str]):
|
| 83 |
+
Optional protocol that has been accepted by the server.
|
| 84 |
+
response (Response | None):
|
| 85 |
+
The webSocket handshake response.
|
| 86 |
+
"""
|
| 87 |
+
|
| 88 |
+
subprotocol: str | None
|
| 89 |
+
response: Response | None
|
| 90 |
+
|
| 91 |
+
def __init__(
|
| 92 |
+
self,
|
| 93 |
+
stream: NetworkStream,
|
| 94 |
+
*,
|
| 95 |
+
max_message_size_bytes: int = DEFAULT_MAX_MESSAGE_SIZE_BYTES,
|
| 96 |
+
queue_size: int = DEFAULT_QUEUE_SIZE,
|
| 97 |
+
keepalive_ping_interval_seconds: float | None = DEFAULT_KEEPALIVE_PING_INTERVAL_SECONDS,
|
| 98 |
+
keepalive_ping_timeout_seconds: float | None = DEFAULT_KEEPALIVE_PING_TIMEOUT_SECONDS,
|
| 99 |
+
response: Response | None = None,
|
| 100 |
+
) -> None:
|
| 101 |
+
self.stream = stream
|
| 102 |
+
self.connection = wsproto.connection.Connection(wsproto.ConnectionType.CLIENT)
|
| 103 |
+
self.response = response
|
| 104 |
+
if self.response is not None:
|
| 105 |
+
self.subprotocol = self.response.headers.get("sec-websocket-protocol")
|
| 106 |
+
else:
|
| 107 |
+
self.subprotocol = None
|
| 108 |
+
|
| 109 |
+
self._events: queue.Queue[wsproto.events.Event | HTTPXWSException] = queue.Queue(queue_size)
|
| 110 |
+
|
| 111 |
+
self._ping_manager = PingManager()
|
| 112 |
+
self._should_close = threading.Event()
|
| 113 |
+
self._write_lock = threading.Lock()
|
| 114 |
+
self._should_close_task: concurrent.futures.Future[bool] | None = None
|
| 115 |
+
self._executor: concurrent.futures.ThreadPoolExecutor | None = None
|
| 116 |
+
|
| 117 |
+
self._max_message_size_bytes = max_message_size_bytes
|
| 118 |
+
self._queue_size = queue_size
|
| 119 |
+
self._keepalive_ping_interval_seconds = keepalive_ping_interval_seconds
|
| 120 |
+
self._keepalive_ping_timeout_seconds = keepalive_ping_timeout_seconds
|
| 121 |
+
|
| 122 |
+
def _get_executor_should_close_task(
|
| 123 |
+
self,
|
| 124 |
+
) -> tuple[concurrent.futures.ThreadPoolExecutor, concurrent.futures.Future[bool]]:
|
| 125 |
+
if self._should_close_task is None:
|
| 126 |
+
self._executor = concurrent.futures.ThreadPoolExecutor()
|
| 127 |
+
self._should_close_task = self._executor.submit(self._should_close.wait)
|
| 128 |
+
assert self._executor is not None
|
| 129 |
+
return self._executor, self._should_close_task
|
| 130 |
+
|
| 131 |
+
def __enter__(self) -> WebSocketSession:
|
| 132 |
+
self._background_receive_task = threading.Thread(
|
| 133 |
+
target=self._background_receive, args=(self._max_message_size_bytes,)
|
| 134 |
+
)
|
| 135 |
+
self._background_receive_task.start()
|
| 136 |
+
|
| 137 |
+
self._background_keepalive_ping_task: threading.Thread | None = None
|
| 138 |
+
if self._keepalive_ping_interval_seconds is not None:
|
| 139 |
+
self._background_keepalive_ping_task = threading.Thread(
|
| 140 |
+
target=self._background_keepalive_ping,
|
| 141 |
+
args=(
|
| 142 |
+
self._keepalive_ping_interval_seconds,
|
| 143 |
+
self._keepalive_ping_timeout_seconds,
|
| 144 |
+
),
|
| 145 |
+
)
|
| 146 |
+
self._background_keepalive_ping_task.start()
|
| 147 |
+
|
| 148 |
+
return self
|
| 149 |
+
|
| 150 |
+
def __exit__(
|
| 151 |
+
self,
|
| 152 |
+
exc_type: type[BaseException] | None,
|
| 153 |
+
exc: BaseException | None,
|
| 154 |
+
tb: TracebackType | None,
|
| 155 |
+
) -> None:
|
| 156 |
+
self.close()
|
| 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)
|
| 168 |
+
|
| 169 |
+
def ping(self, payload: bytes = b"") -> threading.Event:
|
| 170 |
+
"""
|
| 171 |
+
Send a Ping message.
|
| 172 |
+
|
| 173 |
+
Args:
|
| 174 |
+
payload:
|
| 175 |
+
Payload to attach to the Ping event.
|
| 176 |
+
Internally, it's used to track this specific event.
|
| 177 |
+
If left empty, a random one will be generated.
|
| 178 |
+
|
| 179 |
+
Returns:
|
| 180 |
+
An event that can be used to wait for the corresponding Pong response.
|
| 181 |
+
|
| 182 |
+
Examples:
|
| 183 |
+
Send a Ping and wait for the Pong
|
| 184 |
+
|
| 185 |
+
pong_callback = ws.ping()
|
| 186 |
+
# Will block until the corresponding Pong is received.
|
| 187 |
+
pong_callback.wait()
|
| 188 |
+
"""
|
| 189 |
+
ping_id, callback = self._ping_manager.create(payload)
|
| 190 |
+
event = wsproto.events.Ping(ping_id)
|
| 191 |
+
self.send(event)
|
| 192 |
+
return callback
|
| 193 |
+
|
| 194 |
+
def send(self, event: wsproto.events.Event) -> None:
|
| 195 |
+
"""
|
| 196 |
+
Send an Event message.
|
| 197 |
+
|
| 198 |
+
Mainly useful to send events that are not supported by the library.
|
| 199 |
+
Most of the time, [ping()][httpx_ws.WebSocketSession.ping],
|
| 200 |
+
[send_text()][httpx_ws.WebSocketSession.send_text],
|
| 201 |
+
[send_bytes()][httpx_ws.WebSocketSession.send_bytes]
|
| 202 |
+
and [send_json()][httpx_ws.WebSocketSession.send_json] are preferred.
|
| 203 |
+
|
| 204 |
+
Args:
|
| 205 |
+
event: The event to send.
|
| 206 |
+
|
| 207 |
+
Raises:
|
| 208 |
+
WebSocketNetworkError: A network error occured.
|
| 209 |
+
|
| 210 |
+
Examples:
|
| 211 |
+
Send an event.
|
| 212 |
+
|
| 213 |
+
event = wsproto.events.Message(b"Hello!")
|
| 214 |
+
ws.send(event)
|
| 215 |
+
"""
|
| 216 |
+
import httpcore2
|
| 217 |
+
|
| 218 |
+
try:
|
| 219 |
+
data = self.connection.send(event)
|
| 220 |
+
with self._write_lock:
|
| 221 |
+
self.stream.write(data)
|
| 222 |
+
except httpcore2.WriteError as e:
|
| 223 |
+
self.close(CloseReason.INTERNAL_ERROR, "Stream write error")
|
| 224 |
+
raise WebSocketNetworkError() from e
|
| 225 |
+
|
| 226 |
+
def send_text(self, data: str) -> None:
|
| 227 |
+
"""
|
| 228 |
+
Send a text message.
|
| 229 |
+
|
| 230 |
+
Args:
|
| 231 |
+
data: The text to send.
|
| 232 |
+
|
| 233 |
+
Raises:
|
| 234 |
+
WebSocketNetworkError: A network error occured.
|
| 235 |
+
|
| 236 |
+
Examples:
|
| 237 |
+
Send a text message.
|
| 238 |
+
|
| 239 |
+
ws.send_text("Hello!")
|
| 240 |
+
"""
|
| 241 |
+
event = wsproto.events.TextMessage(data=data)
|
| 242 |
+
self.send(event)
|
| 243 |
+
|
| 244 |
+
def send_bytes(self, data: bytes) -> None:
|
| 245 |
+
"""
|
| 246 |
+
Send a bytes message.
|
| 247 |
+
|
| 248 |
+
Args:
|
| 249 |
+
data: The data to send.
|
| 250 |
+
|
| 251 |
+
Raises:
|
| 252 |
+
WebSocketNetworkError: A network error occured.
|
| 253 |
+
|
| 254 |
+
Examples:
|
| 255 |
+
Send a bytes message.
|
| 256 |
+
|
| 257 |
+
ws.send_bytes(b"Hello!")
|
| 258 |
+
"""
|
| 259 |
+
event = wsproto.events.BytesMessage(data=data)
|
| 260 |
+
self.send(event)
|
| 261 |
+
|
| 262 |
+
def send_json(self, data: typing.Any, mode: JSONMode = "text") -> None:
|
| 263 |
+
"""
|
| 264 |
+
Send JSON data.
|
| 265 |
+
|
| 266 |
+
Args:
|
| 267 |
+
data:
|
| 268 |
+
The data to send. Must be serializable by [json.dumps][json.dumps].
|
| 269 |
+
mode:
|
| 270 |
+
The sending mode. Should either be `'text'` or `'bytes'`.
|
| 271 |
+
|
| 272 |
+
Raises:
|
| 273 |
+
WebSocketNetworkError: A network error occured.
|
| 274 |
+
|
| 275 |
+
Examples:
|
| 276 |
+
Send JSON data.
|
| 277 |
+
|
| 278 |
+
data = {"message": "Hello!"}
|
| 279 |
+
ws.send_json(data)
|
| 280 |
+
"""
|
| 281 |
+
assert mode in ["text", "binary"]
|
| 282 |
+
serialized_data = json.dumps(data)
|
| 283 |
+
if mode == "text":
|
| 284 |
+
self.send_text(serialized_data)
|
| 285 |
+
else:
|
| 286 |
+
self.send_bytes(serialized_data.encode("utf-8"))
|
| 287 |
+
|
| 288 |
+
def receive(self, timeout: float | None = None) -> wsproto.events.Event:
|
| 289 |
+
"""
|
| 290 |
+
Receive an event from the server.
|
| 291 |
+
|
| 292 |
+
Mainly useful to receive raw [wsproto.events.Event][wsproto.events.Event].
|
| 293 |
+
Most of the time, [receive_text()][httpx_ws.WebSocketSession.receive_text],
|
| 294 |
+
[receive_bytes()][httpx_ws.WebSocketSession.receive_bytes],
|
| 295 |
+
and [receive_json()][httpx_ws.WebSocketSession.receive_json] are preferred.
|
| 296 |
+
|
| 297 |
+
Args:
|
| 298 |
+
timeout:
|
| 299 |
+
Number of seconds to wait for an event.
|
| 300 |
+
If `None`, will block until an event is available.
|
| 301 |
+
|
| 302 |
+
Returns:
|
| 303 |
+
A raw [wsproto.events.Event][wsproto.events.Event].
|
| 304 |
+
|
| 305 |
+
Raises:
|
| 306 |
+
TimeoutError: No event was received before the timeout delay.
|
| 307 |
+
WebSocketDisconnect: The server closed the websocket.
|
| 308 |
+
WebSocketNetworkError: A network error occured.
|
| 309 |
+
|
| 310 |
+
Examples:
|
| 311 |
+
Wait for an event until one is available.
|
| 312 |
+
|
| 313 |
+
try:
|
| 314 |
+
event = ws.receive()
|
| 315 |
+
except WebSocketDisconnect:
|
| 316 |
+
print("Connection closed")
|
| 317 |
+
|
| 318 |
+
Wait for an event for 2 seconds.
|
| 319 |
+
|
| 320 |
+
try:
|
| 321 |
+
event = ws.receive(timeout=2.)
|
| 322 |
+
except TimeoutError:
|
| 323 |
+
print("No event received.")
|
| 324 |
+
except WebSocketDisconnect:
|
| 325 |
+
print("Connection closed")
|
| 326 |
+
"""
|
| 327 |
+
try:
|
| 328 |
+
event = self._events.get(block=True, timeout=timeout)
|
| 329 |
+
except queue.Empty as e:
|
| 330 |
+
raise TimeoutError from e
|
| 331 |
+
except QueueShutDown as e: # pragma: no cover - Python 3.13+ only
|
| 332 |
+
raise WebSocketDisconnect() from e
|
| 333 |
+
if isinstance(event, HTTPXWSException):
|
| 334 |
+
raise event
|
| 335 |
+
if isinstance(event, wsproto.events.CloseConnection):
|
| 336 |
+
raise WebSocketDisconnect(event.code, event.reason)
|
| 337 |
+
return event
|
| 338 |
+
|
| 339 |
+
def receive_text(self, timeout: float | None = None) -> str:
|
| 340 |
+
"""
|
| 341 |
+
Receive text from the server.
|
| 342 |
+
|
| 343 |
+
Args:
|
| 344 |
+
timeout:
|
| 345 |
+
Number of seconds to wait for an event.
|
| 346 |
+
If `None`, will block until an event is available.
|
| 347 |
+
|
| 348 |
+
Returns:
|
| 349 |
+
Text data.
|
| 350 |
+
|
| 351 |
+
Raises:
|
| 352 |
+
TimeoutError: No event was received before the timeout delay.
|
| 353 |
+
WebSocketDisconnect: The server closed the websocket.
|
| 354 |
+
WebSocketNetworkError: A network error occured.
|
| 355 |
+
WebSocketInvalidTypeReceived: The received event was not a text message.
|
| 356 |
+
|
| 357 |
+
Examples:
|
| 358 |
+
Wait for text until available.
|
| 359 |
+
|
| 360 |
+
try:
|
| 361 |
+
text = ws.receive_text()
|
| 362 |
+
except WebSocketDisconnect:
|
| 363 |
+
print("Connection closed")
|
| 364 |
+
|
| 365 |
+
Wait for text for 2 seconds.
|
| 366 |
+
|
| 367 |
+
try:
|
| 368 |
+
event = ws.receive_text(timeout=2.)
|
| 369 |
+
except TimeoutError:
|
| 370 |
+
print("No text received.")
|
| 371 |
+
except WebSocketDisconnect:
|
| 372 |
+
print("Connection closed")
|
| 373 |
+
"""
|
| 374 |
+
event = self.receive(timeout)
|
| 375 |
+
if isinstance(event, wsproto.events.TextMessage):
|
| 376 |
+
return event.data
|
| 377 |
+
raise WebSocketInvalidTypeReceived(event)
|
| 378 |
+
|
| 379 |
+
def receive_bytes(self, timeout: float | None = None) -> bytes:
|
| 380 |
+
"""
|
| 381 |
+
Receive bytes from the server.
|
| 382 |
+
|
| 383 |
+
Args:
|
| 384 |
+
timeout:
|
| 385 |
+
Number of seconds to wait for an event.
|
| 386 |
+
If `None`, will block until an event is available.
|
| 387 |
+
|
| 388 |
+
Returns:
|
| 389 |
+
Bytes data.
|
| 390 |
+
|
| 391 |
+
Raises:
|
| 392 |
+
TimeoutError: No event was received before the timeout delay.
|
| 393 |
+
WebSocketDisconnect: The server closed the websocket.
|
| 394 |
+
WebSocketNetworkError: A network error occured.
|
| 395 |
+
WebSocketInvalidTypeReceived: The received event was not a bytes message.
|
| 396 |
+
|
| 397 |
+
Examples:
|
| 398 |
+
Wait for bytes until available.
|
| 399 |
+
|
| 400 |
+
try:
|
| 401 |
+
data = ws.receive_bytes()
|
| 402 |
+
except WebSocketDisconnect:
|
| 403 |
+
print("Connection closed")
|
| 404 |
+
|
| 405 |
+
Wait for bytes for 2 seconds.
|
| 406 |
+
|
| 407 |
+
try:
|
| 408 |
+
data = ws.receive_bytes(timeout=2.)
|
| 409 |
+
except TimeoutError:
|
| 410 |
+
print("No data received.")
|
| 411 |
+
except WebSocketDisconnect:
|
| 412 |
+
print("Connection closed")
|
| 413 |
+
"""
|
| 414 |
+
event = self.receive(timeout)
|
| 415 |
+
if isinstance(event, wsproto.events.BytesMessage):
|
| 416 |
+
return bytes(event.data)
|
| 417 |
+
raise WebSocketInvalidTypeReceived(event)
|
| 418 |
+
|
| 419 |
+
def receive_json(self, timeout: float | None = None, mode: JSONMode = "text") -> typing.Any:
|
| 420 |
+
"""
|
| 421 |
+
Receive JSON data from the server.
|
| 422 |
+
|
| 423 |
+
The received data should be parseable by [json.loads][json.loads].
|
| 424 |
+
|
| 425 |
+
Args:
|
| 426 |
+
timeout:
|
| 427 |
+
Number of seconds to wait for an event.
|
| 428 |
+
If `None`, will block until an event is available.
|
| 429 |
+
mode:
|
| 430 |
+
Receive mode. Should either be `'text'` or `'bytes'`.
|
| 431 |
+
|
| 432 |
+
Returns:
|
| 433 |
+
Parsed JSON data.
|
| 434 |
+
|
| 435 |
+
Raises:
|
| 436 |
+
TimeoutError: No event was received before the timeout delay.
|
| 437 |
+
WebSocketDisconnect: The server closed the websocket.
|
| 438 |
+
WebSocketNetworkError: A network error occured.
|
| 439 |
+
WebSocketInvalidTypeReceived: The received event
|
| 440 |
+
didn't correspond to the specified mode.
|
| 441 |
+
|
| 442 |
+
Examples:
|
| 443 |
+
Wait for data until available.
|
| 444 |
+
|
| 445 |
+
try:
|
| 446 |
+
data = ws.receive_json()
|
| 447 |
+
except WebSocketDisconnect:
|
| 448 |
+
print("Connection closed")
|
| 449 |
+
|
| 450 |
+
Wait for data for 2 seconds.
|
| 451 |
+
|
| 452 |
+
try:
|
| 453 |
+
data = ws.receive_json(timeout=2.)
|
| 454 |
+
except TimeoutError:
|
| 455 |
+
print("No data received.")
|
| 456 |
+
except WebSocketDisconnect:
|
| 457 |
+
print("Connection closed")
|
| 458 |
+
"""
|
| 459 |
+
assert mode in ["text", "binary"]
|
| 460 |
+
data: str | bytes
|
| 461 |
+
if mode == "text":
|
| 462 |
+
data = self.receive_text(timeout)
|
| 463 |
+
elif mode == "binary":
|
| 464 |
+
data = self.receive_bytes(timeout)
|
| 465 |
+
return json.loads(data)
|
| 466 |
+
|
| 467 |
+
def close(self, code: int = 1000, reason: str | None = None) -> None:
|
| 468 |
+
"""
|
| 469 |
+
Close the WebSocket session.
|
| 470 |
+
|
| 471 |
+
Internally, it'll send the
|
| 472 |
+
[CloseConnection][wsproto.events.CloseConnection] event.
|
| 473 |
+
|
| 474 |
+
*This method is automatically called when exiting the context manager.*
|
| 475 |
+
|
| 476 |
+
Args:
|
| 477 |
+
code:
|
| 478 |
+
The integer close code to indicate why the connection has closed.
|
| 479 |
+
reason:
|
| 480 |
+
Additional reasoning for why the connection has closed.
|
| 481 |
+
|
| 482 |
+
Examples:
|
| 483 |
+
Close the WebSocket session.
|
| 484 |
+
|
| 485 |
+
ws.close()
|
| 486 |
+
"""
|
| 487 |
+
import httpcore2
|
| 488 |
+
|
| 489 |
+
self._should_close.set()
|
| 490 |
+
if self._executor is not None:
|
| 491 |
+
self._executor.shutdown(False)
|
| 492 |
+
if self.connection.state not in {
|
| 493 |
+
wsproto.connection.ConnectionState.LOCAL_CLOSING,
|
| 494 |
+
wsproto.connection.ConnectionState.CLOSED,
|
| 495 |
+
}:
|
| 496 |
+
event = wsproto.events.CloseConnection(code, reason)
|
| 497 |
+
data = self.connection.send(event)
|
| 498 |
+
try:
|
| 499 |
+
with self._write_lock:
|
| 500 |
+
self.stream.write(data)
|
| 501 |
+
except httpcore2.WriteError:
|
| 502 |
+
pass
|
| 503 |
+
self.stream.close()
|
| 504 |
+
|
| 505 |
+
def _background_receive(self, max_bytes: int) -> None:
|
| 506 |
+
"""
|
| 507 |
+
Background thread listening for data from the server.
|
| 508 |
+
|
| 509 |
+
Internally, it'll:
|
| 510 |
+
|
| 511 |
+
* Answer to Ping events.
|
| 512 |
+
* Acknowledge Pong events.
|
| 513 |
+
* Put other events in the [_events][_events]
|
| 514 |
+
queue that'll eventually be consumed by the user.
|
| 515 |
+
|
| 516 |
+
Args:
|
| 517 |
+
max_bytes: The maximum chunk size to read at each iteration.
|
| 518 |
+
"""
|
| 519 |
+
import httpcore2
|
| 520 |
+
|
| 521 |
+
partial_message_buffer: str | bytes | None = None
|
| 522 |
+
partial_message_size = 0
|
| 523 |
+
try:
|
| 524 |
+
while not self._should_close.is_set():
|
| 525 |
+
data = self._wait_until_closed(self._read_stream, max_bytes)
|
| 526 |
+
self.connection.receive_data(data)
|
| 527 |
+
for event in self.connection.events():
|
| 528 |
+
if isinstance(event, wsproto.events.Ping):
|
| 529 |
+
data = self.connection.send(event.response())
|
| 530 |
+
with self._write_lock:
|
| 531 |
+
self.stream.write(data)
|
| 532 |
+
continue
|
| 533 |
+
if isinstance(event, wsproto.events.Pong):
|
| 534 |
+
self._ping_manager.ack(event.payload)
|
| 535 |
+
continue
|
| 536 |
+
if isinstance(event, wsproto.events.CloseConnection):
|
| 537 |
+
self._should_close.set()
|
| 538 |
+
if isinstance(event, wsproto.events.Message):
|
| 539 |
+
partial_message_size += len(event.data.encode() if isinstance(event.data, str) else event.data)
|
| 540 |
+
if partial_message_size > max_bytes:
|
| 541 |
+
self.close(CloseReason.MESSAGE_TOO_BIG, "Message too big")
|
| 542 |
+
self._events.put(WebSocketDisconnect(CloseReason.MESSAGE_TOO_BIG, "Message too big"))
|
| 543 |
+
break
|
| 544 |
+
# Unfinished message: bufferize
|
| 545 |
+
if not event.message_finished:
|
| 546 |
+
if partial_message_buffer is None:
|
| 547 |
+
partial_message_buffer = event.data
|
| 548 |
+
else:
|
| 549 |
+
partial_message_buffer += event.data
|
| 550 |
+
# Finished message but no buffer: just emit the event
|
| 551 |
+
elif partial_message_buffer is None:
|
| 552 |
+
partial_message_size = 0
|
| 553 |
+
self._events.put(event)
|
| 554 |
+
# Finished message with buffer: emit the full event
|
| 555 |
+
else:
|
| 556 |
+
event_type = type(event)
|
| 557 |
+
full_message_event = event_type(partial_message_buffer + event.data)
|
| 558 |
+
partial_message_buffer = None
|
| 559 |
+
partial_message_size = 0
|
| 560 |
+
self._events.put(full_message_event)
|
| 561 |
+
continue
|
| 562 |
+
self._events.put(event)
|
| 563 |
+
except (httpcore2.ReadError, httpcore2.WriteError, EndOfStream):
|
| 564 |
+
self.close(CloseReason.INTERNAL_ERROR, "Stream error")
|
| 565 |
+
with contextlib.suppress(QueueShutDown):
|
| 566 |
+
self._events.put(WebSocketNetworkError())
|
| 567 |
+
except (ShouldClose, QueueShutDown):
|
| 568 |
+
pass
|
| 569 |
+
|
| 570 |
+
def _background_keepalive_ping(self, interval_seconds: float, timeout_seconds: float | None = None) -> None:
|
| 571 |
+
try:
|
| 572 |
+
while not self._should_close.is_set():
|
| 573 |
+
should_close = self._wait_until_closed(self._should_close.wait, interval_seconds)
|
| 574 |
+
if should_close: # pragma: no cover
|
| 575 |
+
raise ShouldClose()
|
| 576 |
+
try:
|
| 577 |
+
pong_callback = self.ping()
|
| 578 |
+
except wsproto.utilities.LocalProtocolError:
|
| 579 |
+
return
|
| 580 |
+
if timeout_seconds is not None:
|
| 581 |
+
acknowledged = self._wait_until_closed(pong_callback.wait, timeout_seconds)
|
| 582 |
+
if not acknowledged:
|
| 583 |
+
self.close(CloseReason.INTERNAL_ERROR, "Keepalive ping timeout")
|
| 584 |
+
self._events.put(WebSocketNetworkError())
|
| 585 |
+
except (ShouldClose, QueueShutDown):
|
| 586 |
+
pass
|
| 587 |
+
|
| 588 |
+
def _wait_until_closed(
|
| 589 |
+
self, callable: typing.Callable[..., TaskResult], *args: typing.Any, **kwargs: typing.Any
|
| 590 |
+
) -> TaskResult:
|
| 591 |
+
try:
|
| 592 |
+
executor, should_close_task = self._get_executor_should_close_task()
|
| 593 |
+
todo_task = executor.submit(callable, *args, **kwargs)
|
| 594 |
+
except RuntimeError as e:
|
| 595 |
+
raise ShouldClose() from e
|
| 596 |
+
else:
|
| 597 |
+
done, _ = concurrent.futures.wait(
|
| 598 |
+
(todo_task, should_close_task), # type: ignore[misc]
|
| 599 |
+
return_when=concurrent.futures.FIRST_COMPLETED,
|
| 600 |
+
)
|
| 601 |
+
if should_close_task in done:
|
| 602 |
+
raise ShouldClose()
|
| 603 |
+
assert todo_task in done
|
| 604 |
+
result = todo_task.result()
|
| 605 |
+
return result
|
| 606 |
+
|
| 607 |
+
def _read_stream(self, max_bytes: int) -> bytes:
|
| 608 |
+
data = self.stream.read(max_bytes)
|
| 609 |
+
if data == b"":
|
| 610 |
+
raise EndOfStream()
|
| 611 |
+
return data
|
| 612 |
+
|
| 613 |
+
|
| 614 |
+
class AsyncWebSocketSession(anyio.AsyncContextManagerMixin):
|
| 615 |
+
"""
|
| 616 |
+
Async context manager representing an opened WebSocket session.
|
| 617 |
+
|
| 618 |
+
Internally, this session uses an anyio task group to manage background tasks.
|
| 619 |
+
As a result, exceptions that are not caught inside the context manager
|
| 620 |
+
and propagate out of the `async with` block will be wrapped
|
| 621 |
+
in an [ExceptionGroup][ExceptionGroup].
|
| 622 |
+
|
| 623 |
+
To handle them, use the `except*` syntax:
|
| 624 |
+
|
| 625 |
+
async with AsyncWebSocketSession(stream) as ws:
|
| 626 |
+
try:
|
| 627 |
+
data = await ws.receive_text()
|
| 628 |
+
except WebSocketDisconnect:
|
| 629 |
+
# Caught inside the context manager: plain exception.
|
| 630 |
+
print("Connection closed")
|
| 631 |
+
|
| 632 |
+
# If not caught inside:
|
| 633 |
+
try:
|
| 634 |
+
async with AsyncWebSocketSession(stream) as ws:
|
| 635 |
+
data = await ws.receive_text()
|
| 636 |
+
except* WebSocketDisconnect:
|
| 637 |
+
# Propagated out of the context manager: wrapped in ExceptionGroup.
|
| 638 |
+
print("Connection closed")
|
| 639 |
+
|
| 640 |
+
Attributes:
|
| 641 |
+
subprotocol (typing.Optional[str]):
|
| 642 |
+
Optional protocol that has been accepted by the server.
|
| 643 |
+
response (Response | None):
|
| 644 |
+
The webSocket handshake response.
|
| 645 |
+
"""
|
| 646 |
+
|
| 647 |
+
subprotocol: str | None
|
| 648 |
+
response: Response | None
|
| 649 |
+
_send_event: MemoryObjectSendStream[wsproto.events.Event | HTTPXWSException]
|
| 650 |
+
_receive_event: MemoryObjectReceiveStream[wsproto.events.Event | HTTPXWSException]
|
| 651 |
+
|
| 652 |
+
def __init__(
|
| 653 |
+
self,
|
| 654 |
+
stream: AsyncNetworkStream,
|
| 655 |
+
*,
|
| 656 |
+
max_message_size_bytes: int = DEFAULT_MAX_MESSAGE_SIZE_BYTES,
|
| 657 |
+
queue_size: int = DEFAULT_QUEUE_SIZE,
|
| 658 |
+
keepalive_ping_interval_seconds: float | None = DEFAULT_KEEPALIVE_PING_INTERVAL_SECONDS,
|
| 659 |
+
keepalive_ping_timeout_seconds: float | None = DEFAULT_KEEPALIVE_PING_TIMEOUT_SECONDS,
|
| 660 |
+
response: Response | None = None,
|
| 661 |
+
) -> None:
|
| 662 |
+
self.stream = stream
|
| 663 |
+
self.connection = wsproto.connection.Connection(wsproto.ConnectionType.CLIENT)
|
| 664 |
+
self.response = response
|
| 665 |
+
if self.response is not None:
|
| 666 |
+
self.subprotocol = self.response.headers.get("sec-websocket-protocol")
|
| 667 |
+
else:
|
| 668 |
+
self.subprotocol = None
|
| 669 |
+
|
| 670 |
+
self._ping_manager = AsyncPingManager()
|
| 671 |
+
self._should_close = anyio.Event()
|
| 672 |
+
self._write_lock = anyio.Lock()
|
| 673 |
+
|
| 674 |
+
self._max_message_size_bytes = max_message_size_bytes
|
| 675 |
+
self._queue_size = queue_size
|
| 676 |
+
|
| 677 |
+
# Always disable keepalive ping when emulating ASGI
|
| 678 |
+
if isinstance(stream, ASGIWebSocketAsyncNetworkStream):
|
| 679 |
+
self._keepalive_ping_interval_seconds = None
|
| 680 |
+
self._keepalive_ping_timeout_seconds = None
|
| 681 |
+
else:
|
| 682 |
+
self._keepalive_ping_interval_seconds = keepalive_ping_interval_seconds
|
| 683 |
+
self._keepalive_ping_timeout_seconds = keepalive_ping_timeout_seconds
|
| 684 |
+
|
| 685 |
+
@contextlib.asynccontextmanager
|
| 686 |
+
async def __asynccontextmanager__(self) -> typing.AsyncGenerator[AsyncWebSocketSession, None]:
|
| 687 |
+
self._send_event, self._receive_event = anyio.create_memory_object_stream[
|
| 688 |
+
wsproto.events.Event | HTTPXWSException
|
| 689 |
+
]()
|
| 690 |
+
self._background_task_group = anyio.create_task_group()
|
| 691 |
+
|
| 692 |
+
async with self._send_event, self._receive_event, self._background_task_group:
|
| 693 |
+
self._background_task_group.start_soon(self._background_receive, self._max_message_size_bytes)
|
| 694 |
+
if self._keepalive_ping_interval_seconds is not None:
|
| 695 |
+
self._background_task_group.start_soon(
|
| 696 |
+
self._background_keepalive_ping,
|
| 697 |
+
self._keepalive_ping_interval_seconds,
|
| 698 |
+
self._keepalive_ping_timeout_seconds,
|
| 699 |
+
)
|
| 700 |
+
|
| 701 |
+
try:
|
| 702 |
+
yield self
|
| 703 |
+
finally:
|
| 704 |
+
self._background_task_group.cancel_scope.cancel()
|
| 705 |
+
with anyio.CancelScope(shield=True):
|
| 706 |
+
await self.close()
|
| 707 |
+
|
| 708 |
+
async def ping(self, payload: bytes = b"") -> anyio.Event:
|
| 709 |
+
"""
|
| 710 |
+
Send a Ping message.
|
| 711 |
+
|
| 712 |
+
Args:
|
| 713 |
+
payload:
|
| 714 |
+
Payload to attach to the Ping event.
|
| 715 |
+
Internally, it's used to track this specific event.
|
| 716 |
+
If left empty, a random one will be generated.
|
| 717 |
+
|
| 718 |
+
Returns:
|
| 719 |
+
An event that can be used to wait for the corresponding Pong response.
|
| 720 |
+
|
| 721 |
+
Examples:
|
| 722 |
+
Send a Ping and wait for the Pong
|
| 723 |
+
|
| 724 |
+
pong_callback = await ws.ping()
|
| 725 |
+
# Will block until the corresponding Pong is received.
|
| 726 |
+
await pong_callback.wait()
|
| 727 |
+
"""
|
| 728 |
+
ping_id, callback = self._ping_manager.create(payload)
|
| 729 |
+
event = wsproto.events.Ping(ping_id)
|
| 730 |
+
await self.send(event)
|
| 731 |
+
return callback
|
| 732 |
+
|
| 733 |
+
async def send(self, event: wsproto.events.Event) -> None:
|
| 734 |
+
"""
|
| 735 |
+
Send an Event message.
|
| 736 |
+
|
| 737 |
+
Mainly useful to send events that are not supported by the library.
|
| 738 |
+
Most of the time, [ping()][httpx_ws.AsyncWebSocketSession.ping],
|
| 739 |
+
[send_text()][httpx_ws.AsyncWebSocketSession.send_text],
|
| 740 |
+
[send_bytes()][httpx_ws.AsyncWebSocketSession.send_bytes]
|
| 741 |
+
and [send_json()][httpx_ws.AsyncWebSocketSession.send_json] are preferred.
|
| 742 |
+
|
| 743 |
+
Args:
|
| 744 |
+
event: The event to send.
|
| 745 |
+
|
| 746 |
+
Raises:
|
| 747 |
+
WebSocketNetworkError: A network error occured.
|
| 748 |
+
|
| 749 |
+
Note:
|
| 750 |
+
Exceptions not caught inside the context manager will be
|
| 751 |
+
wrapped in an [ExceptionGroup][ExceptionGroup]. Use `except*` to catch them
|
| 752 |
+
outside the `async with` block.
|
| 753 |
+
|
| 754 |
+
Examples:
|
| 755 |
+
Send an event.
|
| 756 |
+
|
| 757 |
+
event = await wsproto.events.Message(b"Hello!")
|
| 758 |
+
ws.send(event)
|
| 759 |
+
"""
|
| 760 |
+
import httpcore2
|
| 761 |
+
|
| 762 |
+
try:
|
| 763 |
+
data = self.connection.send(event)
|
| 764 |
+
async with self._write_lock:
|
| 765 |
+
await self.stream.write(data)
|
| 766 |
+
except httpcore2.WriteError as e:
|
| 767 |
+
await self.close(CloseReason.INTERNAL_ERROR, "Stream write error")
|
| 768 |
+
raise WebSocketNetworkError() from e
|
| 769 |
+
|
| 770 |
+
async def send_text(self, data: str) -> None:
|
| 771 |
+
"""
|
| 772 |
+
Send a text message.
|
| 773 |
+
|
| 774 |
+
Args:
|
| 775 |
+
data: The text to send.
|
| 776 |
+
|
| 777 |
+
Raises:
|
| 778 |
+
WebSocketNetworkError: A network error occured.
|
| 779 |
+
|
| 780 |
+
Note:
|
| 781 |
+
Exceptions not caught inside the context manager will be
|
| 782 |
+
wrapped in an [ExceptionGroup][ExceptionGroup]. Use `except*` to catch them
|
| 783 |
+
outside the `async with` block.
|
| 784 |
+
|
| 785 |
+
Examples:
|
| 786 |
+
Send a text message.
|
| 787 |
+
|
| 788 |
+
await ws.send_text("Hello!")
|
| 789 |
+
"""
|
| 790 |
+
event = wsproto.events.TextMessage(data=data)
|
| 791 |
+
await self.send(event)
|
| 792 |
+
|
| 793 |
+
async def send_bytes(self, data: bytes) -> None:
|
| 794 |
+
"""
|
| 795 |
+
Send a bytes message.
|
| 796 |
+
|
| 797 |
+
Args:
|
| 798 |
+
data: The data to send.
|
| 799 |
+
|
| 800 |
+
Raises:
|
| 801 |
+
WebSocketNetworkError: A network error occured.
|
| 802 |
+
|
| 803 |
+
Note:
|
| 804 |
+
Exceptions not caught inside the context manager will be
|
| 805 |
+
wrapped in an [ExceptionGroup][ExceptionGroup]. Use `except*` to catch them
|
| 806 |
+
outside the `async with` block.
|
| 807 |
+
|
| 808 |
+
Examples:
|
| 809 |
+
Send a bytes message.
|
| 810 |
+
|
| 811 |
+
await ws.send_bytes(b"Hello!")
|
| 812 |
+
"""
|
| 813 |
+
event = wsproto.events.BytesMessage(data=data)
|
| 814 |
+
await self.send(event)
|
| 815 |
+
|
| 816 |
+
async def send_json(self, data: typing.Any, mode: JSONMode = "text") -> None:
|
| 817 |
+
"""
|
| 818 |
+
Send JSON data.
|
| 819 |
+
|
| 820 |
+
Args:
|
| 821 |
+
data:
|
| 822 |
+
The data to send. Must be serializable by [json.dumps][json.dumps].
|
| 823 |
+
mode:
|
| 824 |
+
The sending mode. Should either be `'text'` or `'bytes'`.
|
| 825 |
+
|
| 826 |
+
Raises:
|
| 827 |
+
WebSocketNetworkError: A network error occured.
|
| 828 |
+
|
| 829 |
+
Note:
|
| 830 |
+
Exceptions not caught inside the context manager will be
|
| 831 |
+
wrapped in an [ExceptionGroup][ExceptionGroup]. Use `except*` to catch them
|
| 832 |
+
outside the `async with` block.
|
| 833 |
+
|
| 834 |
+
Examples:
|
| 835 |
+
Send JSON data.
|
| 836 |
+
|
| 837 |
+
data = {"message": "Hello!"}
|
| 838 |
+
await ws.send_json(data)
|
| 839 |
+
"""
|
| 840 |
+
assert mode in ["text", "binary"]
|
| 841 |
+
serialized_data = json.dumps(data)
|
| 842 |
+
if mode == "text":
|
| 843 |
+
await self.send_text(serialized_data)
|
| 844 |
+
else:
|
| 845 |
+
await self.send_bytes(serialized_data.encode("utf-8"))
|
| 846 |
+
|
| 847 |
+
async def receive(self, timeout: float | None = None) -> wsproto.events.Event:
|
| 848 |
+
"""
|
| 849 |
+
Receive an event from the server.
|
| 850 |
+
|
| 851 |
+
Mainly useful to receive raw [wsproto.events.Event][wsproto.events.Event].
|
| 852 |
+
Most of the time, [receive_text()][httpx_ws.AsyncWebSocketSession.receive_text],
|
| 853 |
+
[receive_bytes()][httpx_ws.AsyncWebSocketSession.receive_bytes],
|
| 854 |
+
and [receive_json()][httpx_ws.AsyncWebSocketSession.receive_json] are preferred.
|
| 855 |
+
|
| 856 |
+
Args:
|
| 857 |
+
timeout:
|
| 858 |
+
Number of seconds to wait for an event.
|
| 859 |
+
If `None`, will block until an event is available.
|
| 860 |
+
|
| 861 |
+
Returns:
|
| 862 |
+
A raw [wsproto.events.Event][wsproto.events.Event].
|
| 863 |
+
|
| 864 |
+
Raises:
|
| 865 |
+
TimeoutError: No event was received before the timeout delay.
|
| 866 |
+
WebSocketDisconnect: The server closed the websocket.
|
| 867 |
+
WebSocketNetworkError: A network error occured.
|
| 868 |
+
|
| 869 |
+
Note:
|
| 870 |
+
Exceptions not caught inside the context manager will be
|
| 871 |
+
wrapped in an [ExceptionGroup][ExceptionGroup]. Use `except*` to catch them
|
| 872 |
+
outside the `async with` block.
|
| 873 |
+
|
| 874 |
+
Examples:
|
| 875 |
+
Wait for an event until one is available.
|
| 876 |
+
|
| 877 |
+
try:
|
| 878 |
+
event = await ws.receive()
|
| 879 |
+
except WebSocketDisconnect:
|
| 880 |
+
print("Connection closed")
|
| 881 |
+
|
| 882 |
+
Wait for an event for 2 seconds.
|
| 883 |
+
|
| 884 |
+
try:
|
| 885 |
+
event = await ws.receive(timeout=2.)
|
| 886 |
+
except TimeoutError:
|
| 887 |
+
print("No event received.")
|
| 888 |
+
except WebSocketDisconnect:
|
| 889 |
+
print("Connection closed")
|
| 890 |
+
"""
|
| 891 |
+
with anyio.fail_after(timeout):
|
| 892 |
+
event = await self._receive_event.receive()
|
| 893 |
+
if isinstance(event, HTTPXWSException):
|
| 894 |
+
raise event
|
| 895 |
+
if isinstance(event, wsproto.events.CloseConnection):
|
| 896 |
+
raise WebSocketDisconnect(event.code, event.reason)
|
| 897 |
+
return event
|
| 898 |
+
|
| 899 |
+
async def receive_text(self, timeout: float | None = None) -> str:
|
| 900 |
+
"""
|
| 901 |
+
Receive text from the server.
|
| 902 |
+
|
| 903 |
+
Args:
|
| 904 |
+
timeout:
|
| 905 |
+
Number of seconds to wait for an event.
|
| 906 |
+
If `None`, will block until an event is available.
|
| 907 |
+
|
| 908 |
+
Returns:
|
| 909 |
+
Text data.
|
| 910 |
+
|
| 911 |
+
Raises:
|
| 912 |
+
TimeoutError: No event was received before the timeout delay.
|
| 913 |
+
WebSocketDisconnect: The server closed the websocket.
|
| 914 |
+
WebSocketNetworkError: A network error occured.
|
| 915 |
+
WebSocketInvalidTypeReceived: The received event was not a text message.
|
| 916 |
+
|
| 917 |
+
Note:
|
| 918 |
+
Exceptions not caught inside the context manager will be
|
| 919 |
+
wrapped in an [ExceptionGroup][ExceptionGroup]. Use `except*` to catch them
|
| 920 |
+
outside the `async with` block.
|
| 921 |
+
|
| 922 |
+
Examples:
|
| 923 |
+
Wait for text until available.
|
| 924 |
+
|
| 925 |
+
try:
|
| 926 |
+
text = await ws.receive_text()
|
| 927 |
+
except WebSocketDisconnect:
|
| 928 |
+
print("Connection closed")
|
| 929 |
+
|
| 930 |
+
Wait for text for 2 seconds.
|
| 931 |
+
|
| 932 |
+
try:
|
| 933 |
+
event = await ws.receive_text(timeout=2.)
|
| 934 |
+
except TimeoutError:
|
| 935 |
+
print("No text received.")
|
| 936 |
+
except WebSocketDisconnect:
|
| 937 |
+
print("Connection closed")
|
| 938 |
+
"""
|
| 939 |
+
event = await self.receive(timeout)
|
| 940 |
+
if isinstance(event, wsproto.events.TextMessage):
|
| 941 |
+
return event.data
|
| 942 |
+
raise WebSocketInvalidTypeReceived(event)
|
| 943 |
+
|
| 944 |
+
async def receive_bytes(self, timeout: float | None = None) -> bytes:
|
| 945 |
+
"""
|
| 946 |
+
Receive bytes from the server.
|
| 947 |
+
|
| 948 |
+
Args:
|
| 949 |
+
timeout:
|
| 950 |
+
Number of seconds to wait for an event.
|
| 951 |
+
If `None`, will block until an event is available.
|
| 952 |
+
|
| 953 |
+
Returns:
|
| 954 |
+
Bytes data.
|
| 955 |
+
|
| 956 |
+
Raises:
|
| 957 |
+
TimeoutError: No event was received before the timeout delay.
|
| 958 |
+
WebSocketDisconnect: The server closed the websocket.
|
| 959 |
+
WebSocketNetworkError: A network error occured.
|
| 960 |
+
WebSocketInvalidTypeReceived: The received event was not a bytes message.
|
| 961 |
+
|
| 962 |
+
Note:
|
| 963 |
+
Exceptions not caught inside the context manager will be
|
| 964 |
+
wrapped in an [ExceptionGroup][ExceptionGroup]. Use `except*` to catch them
|
| 965 |
+
outside the `async with` block.
|
| 966 |
+
|
| 967 |
+
Examples:
|
| 968 |
+
Wait for bytes until available.
|
| 969 |
+
|
| 970 |
+
try:
|
| 971 |
+
data = await ws.receive_bytes()
|
| 972 |
+
except WebSocketDisconnect:
|
| 973 |
+
print("Connection closed")
|
| 974 |
+
|
| 975 |
+
Wait for bytes for 2 seconds.
|
| 976 |
+
|
| 977 |
+
try:
|
| 978 |
+
data = await ws.receive_bytes(timeout=2.)
|
| 979 |
+
except TimeoutError:
|
| 980 |
+
print("No data received.")
|
| 981 |
+
except WebSocketDisconnect:
|
| 982 |
+
print("Connection closed")
|
| 983 |
+
"""
|
| 984 |
+
event = await self.receive(timeout)
|
| 985 |
+
if isinstance(event, wsproto.events.BytesMessage):
|
| 986 |
+
return bytes(event.data)
|
| 987 |
+
raise WebSocketInvalidTypeReceived(event)
|
| 988 |
+
|
| 989 |
+
async def receive_json(self, timeout: float | None = None, mode: JSONMode = "text") -> typing.Any:
|
| 990 |
+
"""
|
| 991 |
+
Receive JSON data from the server.
|
| 992 |
+
|
| 993 |
+
The received data should be parseable by [json.loads][json.loads].
|
| 994 |
+
|
| 995 |
+
Args:
|
| 996 |
+
timeout:
|
| 997 |
+
Number of seconds to wait for an event.
|
| 998 |
+
If `None`, will block until an event is available.
|
| 999 |
+
mode:
|
| 1000 |
+
Receive mode. Should either be `'text'` or `'bytes'`.
|
| 1001 |
+
|
| 1002 |
+
Returns:
|
| 1003 |
+
Parsed JSON data.
|
| 1004 |
+
|
| 1005 |
+
Raises:
|
| 1006 |
+
TimeoutError: No event was received before the timeout delay.
|
| 1007 |
+
WebSocketDisconnect: The server closed the websocket.
|
| 1008 |
+
WebSocketNetworkError: A network error occured.
|
| 1009 |
+
WebSocketInvalidTypeReceived: The received event
|
| 1010 |
+
didn't correspond to the specified mode.
|
| 1011 |
+
|
| 1012 |
+
Note:
|
| 1013 |
+
Exceptions not caught inside the context manager will be
|
| 1014 |
+
wrapped in an [ExceptionGroup][ExceptionGroup]. Use `except*` to catch them
|
| 1015 |
+
outside the `async with` block.
|
| 1016 |
+
|
| 1017 |
+
Examples:
|
| 1018 |
+
Wait for data until available.
|
| 1019 |
+
|
| 1020 |
+
try:
|
| 1021 |
+
data = await ws.receive_json()
|
| 1022 |
+
except WebSocketDisconnect:
|
| 1023 |
+
print("Connection closed")
|
| 1024 |
+
|
| 1025 |
+
Wait for data for 2 seconds.
|
| 1026 |
+
|
| 1027 |
+
try:
|
| 1028 |
+
data = await ws.receive_json(timeout=2.)
|
| 1029 |
+
except TimeoutError:
|
| 1030 |
+
print("No data received.")
|
| 1031 |
+
except WebSocketDisconnect:
|
| 1032 |
+
print("Connection closed")
|
| 1033 |
+
"""
|
| 1034 |
+
assert mode in ["text", "binary"]
|
| 1035 |
+
data: str | bytes
|
| 1036 |
+
if mode == "text":
|
| 1037 |
+
data = await self.receive_text(timeout)
|
| 1038 |
+
elif mode == "binary":
|
| 1039 |
+
data = await self.receive_bytes(timeout)
|
| 1040 |
+
return json.loads(data)
|
| 1041 |
+
|
| 1042 |
+
async def close(self, code: int = 1000, reason: str | None = None) -> None:
|
| 1043 |
+
"""
|
| 1044 |
+
Close the WebSocket session.
|
| 1045 |
+
|
| 1046 |
+
Internally, it'll send the
|
| 1047 |
+
[CloseConnection][wsproto.events.CloseConnection] event.
|
| 1048 |
+
|
| 1049 |
+
*This method is automatically called when exiting the context manager.*
|
| 1050 |
+
|
| 1051 |
+
Args:
|
| 1052 |
+
code:
|
| 1053 |
+
The integer close code to indicate why the connection has closed.
|
| 1054 |
+
reason:
|
| 1055 |
+
Additional reasoning for why the connection has closed.
|
| 1056 |
+
|
| 1057 |
+
Examples:
|
| 1058 |
+
Close the WebSocket session.
|
| 1059 |
+
|
| 1060 |
+
await ws.close()
|
| 1061 |
+
"""
|
| 1062 |
+
import httpcore2
|
| 1063 |
+
|
| 1064 |
+
self._should_close.set()
|
| 1065 |
+
if self.connection.state not in {
|
| 1066 |
+
wsproto.connection.ConnectionState.LOCAL_CLOSING,
|
| 1067 |
+
wsproto.connection.ConnectionState.CLOSED,
|
| 1068 |
+
}:
|
| 1069 |
+
event = wsproto.events.CloseConnection(code, reason)
|
| 1070 |
+
data = self.connection.send(event)
|
| 1071 |
+
try:
|
| 1072 |
+
async with self._write_lock:
|
| 1073 |
+
await self.stream.write(data)
|
| 1074 |
+
except httpcore2.WriteError:
|
| 1075 |
+
pass
|
| 1076 |
+
await self.stream.aclose()
|
| 1077 |
+
|
| 1078 |
+
async def _background_receive(self, max_bytes: int) -> None:
|
| 1079 |
+
"""
|
| 1080 |
+
Background task listening for data from the server.
|
| 1081 |
+
|
| 1082 |
+
Internally, it'll:
|
| 1083 |
+
|
| 1084 |
+
* Answer to Ping events.
|
| 1085 |
+
* Acknowledge Pong events.
|
| 1086 |
+
* Put other events in the [_events][_events]
|
| 1087 |
+
queue that'll eventually be consumed by the user.
|
| 1088 |
+
|
| 1089 |
+
Args:
|
| 1090 |
+
max_bytes: The maximum chunk size to read at each iteration.
|
| 1091 |
+
"""
|
| 1092 |
+
import httpcore2
|
| 1093 |
+
|
| 1094 |
+
partial_message_buffer: str | bytes | None = None
|
| 1095 |
+
partial_message_size = 0
|
| 1096 |
+
try:
|
| 1097 |
+
while not self._should_close.is_set():
|
| 1098 |
+
data = await self._read_stream(max_bytes)
|
| 1099 |
+
self.connection.receive_data(data)
|
| 1100 |
+
for event in self.connection.events():
|
| 1101 |
+
if isinstance(event, wsproto.events.Ping):
|
| 1102 |
+
data = self.connection.send(event.response())
|
| 1103 |
+
async with self._write_lock:
|
| 1104 |
+
await self.stream.write(data)
|
| 1105 |
+
continue
|
| 1106 |
+
if isinstance(event, wsproto.events.Pong):
|
| 1107 |
+
self._ping_manager.ack(event.payload)
|
| 1108 |
+
continue
|
| 1109 |
+
if isinstance(event, wsproto.events.CloseConnection):
|
| 1110 |
+
self._should_close.set()
|
| 1111 |
+
if isinstance(event, wsproto.events.Message):
|
| 1112 |
+
partial_message_size += len(event.data.encode() if isinstance(event.data, str) else event.data)
|
| 1113 |
+
if partial_message_size > max_bytes:
|
| 1114 |
+
await self.close(CloseReason.MESSAGE_TOO_BIG, "Message too big")
|
| 1115 |
+
await self._send_event.send(
|
| 1116 |
+
WebSocketDisconnect(CloseReason.MESSAGE_TOO_BIG, "Message too big")
|
| 1117 |
+
)
|
| 1118 |
+
break
|
| 1119 |
+
# Unfinished message: bufferize
|
| 1120 |
+
if not event.message_finished:
|
| 1121 |
+
if partial_message_buffer is None:
|
| 1122 |
+
partial_message_buffer = event.data
|
| 1123 |
+
else:
|
| 1124 |
+
partial_message_buffer += event.data
|
| 1125 |
+
# Finished message but no buffer: just emit the event
|
| 1126 |
+
elif partial_message_buffer is None:
|
| 1127 |
+
partial_message_size = 0
|
| 1128 |
+
await self._send_event.send(event)
|
| 1129 |
+
# Finished message with buffer: emit the full event
|
| 1130 |
+
else:
|
| 1131 |
+
event_type = type(event)
|
| 1132 |
+
full_message_event = event_type(partial_message_buffer + event.data)
|
| 1133 |
+
partial_message_buffer = None
|
| 1134 |
+
partial_message_size = 0
|
| 1135 |
+
await self._send_event.send(full_message_event)
|
| 1136 |
+
continue
|
| 1137 |
+
await self._send_event.send(event)
|
| 1138 |
+
except (httpcore2.ReadError, httpcore2.WriteError, EndOfStream):
|
| 1139 |
+
await self.close(CloseReason.INTERNAL_ERROR, "Stream error")
|
| 1140 |
+
await self._send_event.send(WebSocketNetworkError())
|
| 1141 |
+
|
| 1142 |
+
async def _background_keepalive_ping(self, interval_seconds: float, timeout_seconds: float | None = None) -> None:
|
| 1143 |
+
while not self._should_close.is_set():
|
| 1144 |
+
await anyio.sleep(interval_seconds)
|
| 1145 |
+
|
| 1146 |
+
try:
|
| 1147 |
+
pong_callback = await self.ping()
|
| 1148 |
+
# Connection is closing, exit the task
|
| 1149 |
+
except wsproto.utilities.LocalProtocolError:
|
| 1150 |
+
return
|
| 1151 |
+
|
| 1152 |
+
if timeout_seconds is not None:
|
| 1153 |
+
try:
|
| 1154 |
+
with anyio.fail_after(timeout_seconds):
|
| 1155 |
+
await pong_callback.wait()
|
| 1156 |
+
except TimeoutError:
|
| 1157 |
+
await self.close(CloseReason.INTERNAL_ERROR, "Keepalive ping timeout")
|
| 1158 |
+
await self._send_event.send(WebSocketNetworkError())
|
| 1159 |
+
|
| 1160 |
+
async def _read_stream(self, max_bytes: int) -> bytes:
|
| 1161 |
+
data = await self.stream.read(max_bytes)
|
| 1162 |
+
if data == b"":
|
| 1163 |
+
raise EndOfStream()
|
| 1164 |
+
return data
|
| 1165 |
+
|
| 1166 |
+
|
| 1167 |
+
def _get_headers(
|
| 1168 |
+
subprotocols: list[str] | None,
|
| 1169 |
+
) -> dict[str, typing.Any]:
|
| 1170 |
+
headers = {
|
| 1171 |
+
"connection": "upgrade",
|
| 1172 |
+
"upgrade": "websocket",
|
| 1173 |
+
"sec-websocket-key": base64.b64encode(secrets.token_bytes(16)).decode("utf-8"),
|
| 1174 |
+
"sec-websocket-version": "13",
|
| 1175 |
+
}
|
| 1176 |
+
if subprotocols is not None:
|
| 1177 |
+
headers["sec-websocket-protocol"] = ", ".join(subprotocols)
|
| 1178 |
+
return headers
|
| 1179 |
+
|
| 1180 |
+
|
| 1181 |
+
class WebSocketClient(typing.Generic[SyncSession]):
|
| 1182 |
+
"""
|
| 1183 |
+
A sync WebSocket client.
|
| 1184 |
+
|
| 1185 |
+
This class provides an API for connecting to WebSocket.
|
| 1186 |
+
|
| 1187 |
+
Attributes:
|
| 1188 |
+
client:
|
| 1189 |
+
HTTPX client to use.
|
| 1190 |
+
max_message_size_bytes:
|
| 1191 |
+
Maximum incoming message size in bytes.
|
| 1192 |
+
Larger messages, including fragmented messages whose
|
| 1193 |
+
cumulative size exceeds the limit, close the connection
|
| 1194 |
+
with `MESSAGE_TOO_BIG`.
|
| 1195 |
+
Defaults to 65 KiB.
|
| 1196 |
+
queue_size:
|
| 1197 |
+
Size of the queue where the received messages will be held
|
| 1198 |
+
until they are consumed.
|
| 1199 |
+
If the queue is full, the client will stop receive messages
|
| 1200 |
+
from the server until the queue has room available.
|
| 1201 |
+
Defaults to 512.
|
| 1202 |
+
keepalive_ping_interval_seconds:
|
| 1203 |
+
Interval at which the client will automatically send a Ping event
|
| 1204 |
+
to keep the connection alive. Set it to `None` to disable this mechanism.
|
| 1205 |
+
Defaults to 20 seconds.
|
| 1206 |
+
keepalive_ping_timeout_seconds:
|
| 1207 |
+
Maximum delay the client will wait for an answer to its Ping event.
|
| 1208 |
+
If the delay is exceeded,
|
| 1209 |
+
[WebSocketNetworkError][httpx_ws.WebSocketNetworkError]
|
| 1210 |
+
will be raised and the connection closed.
|
| 1211 |
+
Defaults to 20 seconds.
|
| 1212 |
+
session_class:
|
| 1213 |
+
The session class to use.
|
| 1214 |
+
Defaults to [WebSocketSession][httpx_ws.WebSocketSession].
|
| 1215 |
+
"""
|
| 1216 |
+
|
| 1217 |
+
def __init__(
|
| 1218 |
+
self,
|
| 1219 |
+
client: Client,
|
| 1220 |
+
*,
|
| 1221 |
+
max_message_size_bytes: int = DEFAULT_MAX_MESSAGE_SIZE_BYTES,
|
| 1222 |
+
queue_size: int = DEFAULT_QUEUE_SIZE,
|
| 1223 |
+
keepalive_ping_interval_seconds: float | None = DEFAULT_KEEPALIVE_PING_INTERVAL_SECONDS,
|
| 1224 |
+
keepalive_ping_timeout_seconds: float | None = DEFAULT_KEEPALIVE_PING_TIMEOUT_SECONDS,
|
| 1225 |
+
session_class: type[SyncSession] = WebSocketSession, # type: ignore[assignment]
|
| 1226 |
+
) -> None:
|
| 1227 |
+
self.client = client
|
| 1228 |
+
self.max_message_size_bytes = max_message_size_bytes
|
| 1229 |
+
self.queue_size = queue_size
|
| 1230 |
+
self.keepalive_ping_interval_seconds = keepalive_ping_interval_seconds
|
| 1231 |
+
self.keepalive_ping_timeout_seconds = keepalive_ping_timeout_seconds
|
| 1232 |
+
self.session_class = session_class
|
| 1233 |
+
|
| 1234 |
+
@contextlib.contextmanager
|
| 1235 |
+
def connect(
|
| 1236 |
+
self,
|
| 1237 |
+
url: str,
|
| 1238 |
+
*,
|
| 1239 |
+
subprotocols: list[str] | None = None,
|
| 1240 |
+
params: QueryParamTypes | None = None,
|
| 1241 |
+
headers: HeaderTypes | None = None,
|
| 1242 |
+
cookies: CookieTypes | None = None,
|
| 1243 |
+
auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
|
| 1244 |
+
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1245 |
+
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1246 |
+
extensions: RequestExtensions | None = None,
|
| 1247 |
+
) -> typing.Generator[SyncSession, None, None]:
|
| 1248 |
+
"""
|
| 1249 |
+
Start a sync WebSocket session.
|
| 1250 |
+
|
| 1251 |
+
It returns a context manager that'll automatically
|
| 1252 |
+
call [close()][httpx_ws.WebSocketSession.close] when exiting.
|
| 1253 |
+
|
| 1254 |
+
Args:
|
| 1255 |
+
url: The WebSocket URL.
|
| 1256 |
+
subprotocols:
|
| 1257 |
+
Optional list of subprotocols to negotiate with the server.
|
| 1258 |
+
params:
|
| 1259 |
+
Query parameters to include in the handshake request.
|
| 1260 |
+
headers:
|
| 1261 |
+
Headers to include in the handshake request.
|
| 1262 |
+
cookies:
|
| 1263 |
+
Cookies to include in the handshake request.
|
| 1264 |
+
auth:
|
| 1265 |
+
Authentication to use for the handshake request.
|
| 1266 |
+
follow_redirects:
|
| 1267 |
+
Whether to follow redirects on the handshake request.
|
| 1268 |
+
timeout:
|
| 1269 |
+
Timeout configuration for the handshake request.
|
| 1270 |
+
extensions:
|
| 1271 |
+
Request extensions for the handshake request.
|
| 1272 |
+
|
| 1273 |
+
Returns:
|
| 1274 |
+
A [context manager][contextlib.AbstractContextManager]
|
| 1275 |
+
for [WebSocketSession][httpx_ws.WebSocketSession].
|
| 1276 |
+
|
| 1277 |
+
Examples:
|
| 1278 |
+
Initialize the client and connect to a WebSocket.
|
| 1279 |
+
|
| 1280 |
+
with httpx2.Client() as client:
|
| 1281 |
+
ws_client = WebSocketClient(client)
|
| 1282 |
+
with ws_client.connect("http://localhost:8000/ws") as ws:
|
| 1283 |
+
message = ws.receive_text()
|
| 1284 |
+
print(message)
|
| 1285 |
+
ws.send_text("Hello!")
|
| 1286 |
+
"""
|
| 1287 |
+
with self.client.stream(
|
| 1288 |
+
"GET",
|
| 1289 |
+
url,
|
| 1290 |
+
params=params,
|
| 1291 |
+
headers=Headers(headers) | _get_headers(subprotocols),
|
| 1292 |
+
cookies=cookies,
|
| 1293 |
+
auth=auth,
|
| 1294 |
+
follow_redirects=follow_redirects,
|
| 1295 |
+
timeout=timeout,
|
| 1296 |
+
extensions=extensions,
|
| 1297 |
+
) as response:
|
| 1298 |
+
if response.status_code != 101:
|
| 1299 |
+
raise WebSocketUpgradeError(response)
|
| 1300 |
+
|
| 1301 |
+
session = self.session_class(
|
| 1302 |
+
response.extensions["network_stream"],
|
| 1303 |
+
max_message_size_bytes=self.max_message_size_bytes,
|
| 1304 |
+
queue_size=self.queue_size,
|
| 1305 |
+
keepalive_ping_interval_seconds=self.keepalive_ping_interval_seconds,
|
| 1306 |
+
keepalive_ping_timeout_seconds=self.keepalive_ping_timeout_seconds,
|
| 1307 |
+
response=response,
|
| 1308 |
+
)
|
| 1309 |
+
with session:
|
| 1310 |
+
yield session
|
| 1311 |
+
|
| 1312 |
+
|
| 1313 |
+
@contextlib.contextmanager
|
| 1314 |
+
def connect_ws(
|
| 1315 |
+
url: str,
|
| 1316 |
+
client: Client | None = None,
|
| 1317 |
+
*,
|
| 1318 |
+
max_message_size_bytes: int = DEFAULT_MAX_MESSAGE_SIZE_BYTES,
|
| 1319 |
+
queue_size: int = DEFAULT_QUEUE_SIZE,
|
| 1320 |
+
keepalive_ping_interval_seconds: float | None = DEFAULT_KEEPALIVE_PING_INTERVAL_SECONDS,
|
| 1321 |
+
keepalive_ping_timeout_seconds: float | None = DEFAULT_KEEPALIVE_PING_TIMEOUT_SECONDS,
|
| 1322 |
+
subprotocols: list[str] | None = None,
|
| 1323 |
+
params: QueryParamTypes | None = None,
|
| 1324 |
+
headers: HeaderTypes | None = None,
|
| 1325 |
+
cookies: CookieTypes | None = None,
|
| 1326 |
+
auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
|
| 1327 |
+
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1328 |
+
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1329 |
+
extensions: RequestExtensions | None = None,
|
| 1330 |
+
) -> typing.Generator[WebSocketSession, None, None]:
|
| 1331 |
+
"""
|
| 1332 |
+
Start a sync WebSocket session.
|
| 1333 |
+
|
| 1334 |
+
It returns a context manager that'll automatically
|
| 1335 |
+
call [close()][httpx_ws.WebSocketSession.close] when exiting.
|
| 1336 |
+
|
| 1337 |
+
Args:
|
| 1338 |
+
url: The WebSocket URL.
|
| 1339 |
+
client:
|
| 1340 |
+
HTTPX client to use.
|
| 1341 |
+
If not provided, a default one will be initialized.
|
| 1342 |
+
max_message_size_bytes:
|
| 1343 |
+
Maximum incoming message size in bytes.
|
| 1344 |
+
Larger messages, including fragmented messages whose
|
| 1345 |
+
cumulative size exceeds the limit, close the connection
|
| 1346 |
+
with `MESSAGE_TOO_BIG`.
|
| 1347 |
+
Defaults to 65 KiB.
|
| 1348 |
+
queue_size:
|
| 1349 |
+
Size of the queue where the received messages will be held
|
| 1350 |
+
until they are consumed.
|
| 1351 |
+
If the queue is full, the client will stop receive messages
|
| 1352 |
+
from the server until the queue has room available.
|
| 1353 |
+
Defaults to 512.
|
| 1354 |
+
keepalive_ping_interval_seconds:
|
| 1355 |
+
Interval at which the client will automatically send a Ping event
|
| 1356 |
+
to keep the connection alive. Set it to `None` to disable this mechanism.
|
| 1357 |
+
Defaults to 20 seconds.
|
| 1358 |
+
keepalive_ping_timeout_seconds:
|
| 1359 |
+
Maximum delay the client will wait for an answer to its Ping event.
|
| 1360 |
+
If the delay is exceeded,
|
| 1361 |
+
[WebSocketNetworkError][httpx_ws.WebSocketNetworkError]
|
| 1362 |
+
will be raised and the connection closed.
|
| 1363 |
+
Defaults to 20 seconds.
|
| 1364 |
+
subprotocols:
|
| 1365 |
+
Optional list of subprotocols to negotiate with the server.
|
| 1366 |
+
params:
|
| 1367 |
+
Query parameters to include in the handshake request.
|
| 1368 |
+
headers:
|
| 1369 |
+
Headers to include in the handshake request.
|
| 1370 |
+
cookies:
|
| 1371 |
+
Cookies to include in the handshake request.
|
| 1372 |
+
auth:
|
| 1373 |
+
Authentication to use for the handshake request.
|
| 1374 |
+
follow_redirects:
|
| 1375 |
+
Whether to follow redirects on the handshake request.
|
| 1376 |
+
timeout:
|
| 1377 |
+
Timeout configuration for the handshake request.
|
| 1378 |
+
extensions:
|
| 1379 |
+
Request extensions for the handshake request.
|
| 1380 |
+
|
| 1381 |
+
Returns:
|
| 1382 |
+
A [context manager][contextlib.AbstractContextManager]
|
| 1383 |
+
for [WebSocketSession][httpx_ws.WebSocketSession].
|
| 1384 |
+
|
| 1385 |
+
Examples:
|
| 1386 |
+
Without explicit HTTPX client.
|
| 1387 |
+
|
| 1388 |
+
with connect_ws("http://localhost:8000/ws") as ws:
|
| 1389 |
+
message = ws.receive_text()
|
| 1390 |
+
print(message)
|
| 1391 |
+
ws.send_text("Hello!")
|
| 1392 |
+
|
| 1393 |
+
With explicit HTTPX client.
|
| 1394 |
+
|
| 1395 |
+
with httpx2.Client() as client:
|
| 1396 |
+
with connect_ws("http://localhost:8000/ws", client) as ws:
|
| 1397 |
+
message = ws.receive_text()
|
| 1398 |
+
print(message)
|
| 1399 |
+
ws.send_text("Hello!")
|
| 1400 |
+
"""
|
| 1401 |
+
if client is None:
|
| 1402 |
+
from .._client import Client
|
| 1403 |
+
|
| 1404 |
+
owned_client: contextlib.AbstractContextManager[Client] = Client()
|
| 1405 |
+
else:
|
| 1406 |
+
owned_client = contextlib.nullcontext(client)
|
| 1407 |
+
|
| 1408 |
+
with owned_client as client:
|
| 1409 |
+
ws_client = WebSocketClient(
|
| 1410 |
+
client=client,
|
| 1411 |
+
max_message_size_bytes=max_message_size_bytes,
|
| 1412 |
+
queue_size=queue_size,
|
| 1413 |
+
keepalive_ping_interval_seconds=keepalive_ping_interval_seconds,
|
| 1414 |
+
keepalive_ping_timeout_seconds=keepalive_ping_timeout_seconds,
|
| 1415 |
+
)
|
| 1416 |
+
with ws_client.connect(
|
| 1417 |
+
url,
|
| 1418 |
+
subprotocols=subprotocols,
|
| 1419 |
+
params=params,
|
| 1420 |
+
headers=headers,
|
| 1421 |
+
cookies=cookies,
|
| 1422 |
+
auth=auth,
|
| 1423 |
+
follow_redirects=follow_redirects,
|
| 1424 |
+
timeout=timeout,
|
| 1425 |
+
extensions=extensions,
|
| 1426 |
+
) as websocket:
|
| 1427 |
+
yield websocket
|
| 1428 |
+
|
| 1429 |
+
|
| 1430 |
+
class AsyncWebSocketClient(typing.Generic[AsyncSession]):
|
| 1431 |
+
"""
|
| 1432 |
+
An async WebSocket client.
|
| 1433 |
+
|
| 1434 |
+
This class provides an API for connecting to WebSocket.
|
| 1435 |
+
|
| 1436 |
+
Attributes:
|
| 1437 |
+
client:
|
| 1438 |
+
HTTPX client to use.
|
| 1439 |
+
max_message_size_bytes:
|
| 1440 |
+
Maximum incoming message size in bytes.
|
| 1441 |
+
Larger messages, including fragmented messages whose
|
| 1442 |
+
cumulative size exceeds the limit, close the connection
|
| 1443 |
+
with `MESSAGE_TOO_BIG`.
|
| 1444 |
+
Defaults to 65 KiB.
|
| 1445 |
+
queue_size:
|
| 1446 |
+
Size of the queue where the received messages will be held
|
| 1447 |
+
until they are consumed.
|
| 1448 |
+
If the queue is full, the client will stop receive messages
|
| 1449 |
+
from the server until the queue has room available.
|
| 1450 |
+
Defaults to 512.
|
| 1451 |
+
keepalive_ping_interval_seconds:
|
| 1452 |
+
Interval at which the client will automatically send a Ping event
|
| 1453 |
+
to keep the connection alive. Set it to `None` to disable this mechanism.
|
| 1454 |
+
Defaults to 20 seconds.
|
| 1455 |
+
keepalive_ping_timeout_seconds:
|
| 1456 |
+
Maximum delay the client will wait for an answer to its Ping event.
|
| 1457 |
+
If the delay is exceeded,
|
| 1458 |
+
[WebSocketNetworkError][httpx_ws.WebSocketNetworkError]
|
| 1459 |
+
will be raised in an [ExceptionGroup][ExceptionGroup] and the connection closed.
|
| 1460 |
+
Defaults to 20 seconds.
|
| 1461 |
+
session_class:
|
| 1462 |
+
The session class to use.
|
| 1463 |
+
Defaults to [AsyncWebSocketSession][httpx_ws.AsyncWebSocketSession].
|
| 1464 |
+
"""
|
| 1465 |
+
|
| 1466 |
+
def __init__(
|
| 1467 |
+
self,
|
| 1468 |
+
client: AsyncClient,
|
| 1469 |
+
*,
|
| 1470 |
+
max_message_size_bytes: int = DEFAULT_MAX_MESSAGE_SIZE_BYTES,
|
| 1471 |
+
queue_size: int = DEFAULT_QUEUE_SIZE,
|
| 1472 |
+
keepalive_ping_interval_seconds: float | None = DEFAULT_KEEPALIVE_PING_INTERVAL_SECONDS,
|
| 1473 |
+
keepalive_ping_timeout_seconds: float | None = DEFAULT_KEEPALIVE_PING_TIMEOUT_SECONDS,
|
| 1474 |
+
session_class: type[AsyncSession] = AsyncWebSocketSession, # type: ignore[assignment]
|
| 1475 |
+
) -> None:
|
| 1476 |
+
self.client = client
|
| 1477 |
+
self.max_message_size_bytes = max_message_size_bytes
|
| 1478 |
+
self.queue_size = queue_size
|
| 1479 |
+
self.keepalive_ping_interval_seconds = keepalive_ping_interval_seconds
|
| 1480 |
+
self.keepalive_ping_timeout_seconds = keepalive_ping_timeout_seconds
|
| 1481 |
+
self.session_class = session_class
|
| 1482 |
+
|
| 1483 |
+
@contextlib.asynccontextmanager
|
| 1484 |
+
async def connect(
|
| 1485 |
+
self,
|
| 1486 |
+
url: str,
|
| 1487 |
+
*,
|
| 1488 |
+
subprotocols: list[str] | None = None,
|
| 1489 |
+
params: QueryParamTypes | None = None,
|
| 1490 |
+
headers: HeaderTypes | None = None,
|
| 1491 |
+
cookies: CookieTypes | None = None,
|
| 1492 |
+
auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
|
| 1493 |
+
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1494 |
+
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1495 |
+
extensions: RequestExtensions | None = None,
|
| 1496 |
+
) -> typing.AsyncGenerator[AsyncSession, None]:
|
| 1497 |
+
"""
|
| 1498 |
+
Start an async WebSocket session.
|
| 1499 |
+
|
| 1500 |
+
It returns an async context manager that'll automatically
|
| 1501 |
+
call [close()][httpx_ws.AsyncWebSocketSession.close] when exiting.
|
| 1502 |
+
|
| 1503 |
+
Args:
|
| 1504 |
+
url: The WebSocket URL.
|
| 1505 |
+
subprotocols:
|
| 1506 |
+
Optional list of subprotocols to negotiate with the server.
|
| 1507 |
+
params:
|
| 1508 |
+
Query parameters to include in the handshake request.
|
| 1509 |
+
headers:
|
| 1510 |
+
Headers to include in the handshake request.
|
| 1511 |
+
cookies:
|
| 1512 |
+
Cookies to include in the handshake request.
|
| 1513 |
+
auth:
|
| 1514 |
+
Authentication to use for the handshake request.
|
| 1515 |
+
follow_redirects:
|
| 1516 |
+
Whether to follow redirects on the handshake request.
|
| 1517 |
+
timeout:
|
| 1518 |
+
Timeout configuration for the handshake request.
|
| 1519 |
+
extensions:
|
| 1520 |
+
Request extensions for the handshake request.
|
| 1521 |
+
|
| 1522 |
+
Returns:
|
| 1523 |
+
An [async context manager][contextlib.AbstractAsyncContextManager]
|
| 1524 |
+
for [AsyncWebSocketSession][httpx_ws.AsyncWebSocketSession].
|
| 1525 |
+
|
| 1526 |
+
Examples:
|
| 1527 |
+
Initialize the client and connect to a WebSocket.
|
| 1528 |
+
|
| 1529 |
+
async with httpx2.AsyncClient() as client:
|
| 1530 |
+
ws_client = AsyncWebSocketClient(client)
|
| 1531 |
+
async with ws_client.connect("http://localhost:8000/ws") as ws:
|
| 1532 |
+
message = await ws.receive_text()
|
| 1533 |
+
print(message)
|
| 1534 |
+
await ws.send_text("Hello!")
|
| 1535 |
+
"""
|
| 1536 |
+
async with self.client.stream(
|
| 1537 |
+
"GET",
|
| 1538 |
+
url,
|
| 1539 |
+
params=params,
|
| 1540 |
+
headers=Headers(headers) | _get_headers(subprotocols),
|
| 1541 |
+
cookies=cookies,
|
| 1542 |
+
auth=auth,
|
| 1543 |
+
follow_redirects=follow_redirects,
|
| 1544 |
+
timeout=timeout,
|
| 1545 |
+
extensions=extensions,
|
| 1546 |
+
) as response:
|
| 1547 |
+
if response.status_code != 101:
|
| 1548 |
+
raise WebSocketUpgradeError(response)
|
| 1549 |
+
|
| 1550 |
+
session = self.session_class(
|
| 1551 |
+
response.extensions["network_stream"],
|
| 1552 |
+
max_message_size_bytes=self.max_message_size_bytes,
|
| 1553 |
+
queue_size=self.queue_size,
|
| 1554 |
+
keepalive_ping_interval_seconds=self.keepalive_ping_interval_seconds,
|
| 1555 |
+
keepalive_ping_timeout_seconds=self.keepalive_ping_timeout_seconds,
|
| 1556 |
+
response=response,
|
| 1557 |
+
)
|
| 1558 |
+
async with session:
|
| 1559 |
+
yield session
|
| 1560 |
+
|
| 1561 |
+
|
| 1562 |
+
@contextlib.asynccontextmanager
|
| 1563 |
+
async def aconnect_ws(
|
| 1564 |
+
url: str,
|
| 1565 |
+
client: AsyncClient | None = None,
|
| 1566 |
+
*,
|
| 1567 |
+
max_message_size_bytes: int = DEFAULT_MAX_MESSAGE_SIZE_BYTES,
|
| 1568 |
+
queue_size: int = DEFAULT_QUEUE_SIZE,
|
| 1569 |
+
keepalive_ping_interval_seconds: float | None = DEFAULT_KEEPALIVE_PING_INTERVAL_SECONDS,
|
| 1570 |
+
keepalive_ping_timeout_seconds: float | None = DEFAULT_KEEPALIVE_PING_TIMEOUT_SECONDS,
|
| 1571 |
+
subprotocols: list[str] | None = None,
|
| 1572 |
+
params: QueryParamTypes | None = None,
|
| 1573 |
+
headers: HeaderTypes | None = None,
|
| 1574 |
+
cookies: CookieTypes | None = None,
|
| 1575 |
+
auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
|
| 1576 |
+
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1577 |
+
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
|
| 1578 |
+
extensions: RequestExtensions | None = None,
|
| 1579 |
+
) -> typing.AsyncGenerator[AsyncWebSocketSession, None]:
|
| 1580 |
+
"""
|
| 1581 |
+
Start an async WebSocket session.
|
| 1582 |
+
|
| 1583 |
+
It returns an async context manager that'll automatically
|
| 1584 |
+
call [close()][httpx_ws.AsyncWebSocketSession.close] when exiting.
|
| 1585 |
+
|
| 1586 |
+
Args:
|
| 1587 |
+
url: The WebSocket URL.
|
| 1588 |
+
client:
|
| 1589 |
+
HTTPX client to use.
|
| 1590 |
+
If not provided, a default one will be initialized.
|
| 1591 |
+
max_message_size_bytes:
|
| 1592 |
+
Maximum incoming message size in bytes.
|
| 1593 |
+
Larger messages, including fragmented messages whose
|
| 1594 |
+
cumulative size exceeds the limit, close the connection
|
| 1595 |
+
with `MESSAGE_TOO_BIG`.
|
| 1596 |
+
Defaults to 65 KiB.
|
| 1597 |
+
queue_size:
|
| 1598 |
+
Size of the queue where the received messages will be held
|
| 1599 |
+
until they are consumed.
|
| 1600 |
+
If the queue is full, the client will stop receive messages
|
| 1601 |
+
from the server until the queue has room available.
|
| 1602 |
+
Defaults to 512.
|
| 1603 |
+
keepalive_ping_interval_seconds:
|
| 1604 |
+
Interval at which the client will automatically send a Ping event
|
| 1605 |
+
to keep the connection alive. Set it to `None` to disable this mechanism.
|
| 1606 |
+
Defaults to 20 seconds.
|
| 1607 |
+
keepalive_ping_timeout_seconds:
|
| 1608 |
+
Maximum delay the client will wait for an answer to its Ping event.
|
| 1609 |
+
If the delay is exceeded,
|
| 1610 |
+
[WebSocketNetworkError][httpx_ws.WebSocketNetworkError]
|
| 1611 |
+
will be raised in an [ExceptionGroup][ExceptionGroup] and the connection closed.
|
| 1612 |
+
Defaults to 20 seconds.
|
| 1613 |
+
subprotocols:
|
| 1614 |
+
Optional list of subprotocols to negotiate with the server.
|
| 1615 |
+
params:
|
| 1616 |
+
Query parameters to include in the handshake request.
|
| 1617 |
+
headers:
|
| 1618 |
+
Headers to include in the handshake request.
|
| 1619 |
+
cookies:
|
| 1620 |
+
Cookies to include in the handshake request.
|
| 1621 |
+
auth:
|
| 1622 |
+
Authentication to use for the handshake request.
|
| 1623 |
+
follow_redirects:
|
| 1624 |
+
Whether to follow redirects on the handshake request.
|
| 1625 |
+
timeout:
|
| 1626 |
+
Timeout configuration for the handshake request.
|
| 1627 |
+
extensions:
|
| 1628 |
+
Request extensions for the handshake request.
|
| 1629 |
+
|
| 1630 |
+
Returns:
|
| 1631 |
+
An [async context manager][contextlib.AbstractAsyncContextManager]
|
| 1632 |
+
for [AsyncWebSocketSession][httpx_ws.AsyncWebSocketSession].
|
| 1633 |
+
|
| 1634 |
+
Examples:
|
| 1635 |
+
Without explicit HTTPX client.
|
| 1636 |
+
|
| 1637 |
+
async with aconnect_ws("http://localhost:8000/ws") as ws:
|
| 1638 |
+
message = await ws.receive_text()
|
| 1639 |
+
print(message)
|
| 1640 |
+
await ws.send_text("Hello!")
|
| 1641 |
+
|
| 1642 |
+
With explicit HTTPX client.
|
| 1643 |
+
|
| 1644 |
+
async with httpx2.AsyncClient() as client:
|
| 1645 |
+
async with aconnect_ws("http://localhost:8000/ws", client) as ws:
|
| 1646 |
+
message = await ws.receive_text()
|
| 1647 |
+
print(message)
|
| 1648 |
+
await ws.send_text("Hello!")
|
| 1649 |
+
"""
|
| 1650 |
+
if client is None:
|
| 1651 |
+
from .._client import AsyncClient
|
| 1652 |
+
|
| 1653 |
+
owned_client: contextlib.AbstractAsyncContextManager[AsyncClient] = AsyncClient()
|
| 1654 |
+
else:
|
| 1655 |
+
owned_client = contextlib.nullcontext(client)
|
| 1656 |
+
|
| 1657 |
+
async with owned_client as client:
|
| 1658 |
+
ws_client = AsyncWebSocketClient(
|
| 1659 |
+
client=client,
|
| 1660 |
+
max_message_size_bytes=max_message_size_bytes,
|
| 1661 |
+
queue_size=queue_size,
|
| 1662 |
+
keepalive_ping_interval_seconds=keepalive_ping_interval_seconds,
|
| 1663 |
+
keepalive_ping_timeout_seconds=keepalive_ping_timeout_seconds,
|
| 1664 |
+
)
|
| 1665 |
+
async with ws_client.connect(
|
| 1666 |
+
url,
|
| 1667 |
+
subprotocols=subprotocols,
|
| 1668 |
+
params=params,
|
| 1669 |
+
headers=headers,
|
| 1670 |
+
cookies=cookies,
|
| 1671 |
+
auth=auth,
|
| 1672 |
+
follow_redirects=follow_redirects,
|
| 1673 |
+
timeout=timeout,
|
| 1674 |
+
extensions=extensions,
|
| 1675 |
+
) as websocket:
|
| 1676 |
+
yield websocket
|
.venv/lib/python3.12/site-packages/httpx2/websockets/_exceptions.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import typing
|
| 4 |
+
|
| 5 |
+
if typing.TYPE_CHECKING:
|
| 6 |
+
import wsproto
|
| 7 |
+
|
| 8 |
+
from .._models import Response
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class HTTPXWSException(Exception):
|
| 12 |
+
"""
|
| 13 |
+
Base exception class for HTTPX WS.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class WebSocketUpgradeError(HTTPXWSException):
|
| 18 |
+
"""
|
| 19 |
+
Raised when the initial connection didn't correctly upgrade to a WebSocket session.
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
def __init__(self, response: Response) -> None:
|
| 23 |
+
self.response = response
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class WebSocketDisconnect(HTTPXWSException):
|
| 27 |
+
"""
|
| 28 |
+
Raised when the server closed the WebSocket session.
|
| 29 |
+
|
| 30 |
+
Args:
|
| 31 |
+
code:
|
| 32 |
+
The integer close code to indicate why the connection has closed.
|
| 33 |
+
reason:
|
| 34 |
+
Additional reasoning for why the connection has closed.
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
def __init__(self, code: int = 1000, reason: str | None = None) -> None:
|
| 38 |
+
self.code = code
|
| 39 |
+
self.reason = reason or ""
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class WebSocketInvalidTypeReceived(HTTPXWSException):
|
| 43 |
+
"""
|
| 44 |
+
Raised when an event is not of the expected type.
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
def __init__(self, event: wsproto.events.Event) -> None:
|
| 48 |
+
self.event = event
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class WebSocketNetworkError(HTTPXWSException):
|
| 52 |
+
"""
|
| 53 |
+
Raised when a network error occured,
|
| 54 |
+
typically if the underlying stream has closed or timeout.
|
| 55 |
+
"""
|
.venv/lib/python3.12/site-packages/httpx2/websockets/_ping.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import secrets
|
| 4 |
+
import threading
|
| 5 |
+
|
| 6 |
+
import anyio
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class PingManagerBase:
|
| 10 |
+
def _generate_id(self) -> bytes:
|
| 11 |
+
return secrets.token_bytes()
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class PingManager(PingManagerBase):
|
| 15 |
+
def __init__(self) -> None:
|
| 16 |
+
self._pings: dict[bytes, threading.Event] = {}
|
| 17 |
+
|
| 18 |
+
def create(self, ping_id: bytes | None = None) -> tuple[bytes, threading.Event]:
|
| 19 |
+
ping_id = self._generate_id() if not ping_id else ping_id
|
| 20 |
+
event = threading.Event()
|
| 21 |
+
self._pings[ping_id] = event
|
| 22 |
+
return ping_id, event
|
| 23 |
+
|
| 24 |
+
def ack(self, ping_id: bytes | bytearray) -> None:
|
| 25 |
+
event = self._pings.pop(bytes(ping_id), None)
|
| 26 |
+
if event is not None:
|
| 27 |
+
event.set()
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class AsyncPingManager(PingManagerBase):
|
| 31 |
+
def __init__(self) -> None:
|
| 32 |
+
self._pings: dict[bytes, anyio.Event] = {}
|
| 33 |
+
|
| 34 |
+
def create(self, ping_id: bytes | None = None) -> tuple[bytes, anyio.Event]:
|
| 35 |
+
ping_id = self._generate_id() if not ping_id else ping_id
|
| 36 |
+
event = anyio.Event()
|
| 37 |
+
self._pings[ping_id] = event
|
| 38 |
+
return ping_id, event
|
| 39 |
+
|
| 40 |
+
def ack(self, ping_id: bytes | bytearray) -> None:
|
| 41 |
+
event = self._pings.pop(bytes(ping_id), None)
|
| 42 |
+
if event is not None:
|
| 43 |
+
event.set()
|
.venv/lib/python3.12/site-packages/httpx2/websockets/_transport.py
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import contextlib
|
| 4 |
+
import math
|
| 5 |
+
import typing
|
| 6 |
+
from types import TracebackType
|
| 7 |
+
|
| 8 |
+
import anyio
|
| 9 |
+
import wsproto
|
| 10 |
+
from anyio.streams.stapled import StapledObjectStream
|
| 11 |
+
from wsproto.frame_protocol import CloseReason
|
| 12 |
+
|
| 13 |
+
from .._models import Request, Response
|
| 14 |
+
from .._transports.asgi import ASGITransport, _ASGIApp
|
| 15 |
+
from .._types import AsyncByteStream
|
| 16 |
+
from ._exceptions import WebSocketDisconnect, WebSocketUpgradeError
|
| 17 |
+
|
| 18 |
+
Scope = dict[str, typing.Any]
|
| 19 |
+
Message = dict[str, typing.Any]
|
| 20 |
+
Receive = typing.Callable[[], typing.Awaitable[Message]]
|
| 21 |
+
Send = typing.Callable[[Scope], typing.Coroutine[None, None, None]]
|
| 22 |
+
ASGIApp = typing.Callable[[Scope, Receive, Send], typing.Coroutine[None, None, None]]
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class ASGIWebSocketTransportError(Exception):
|
| 26 |
+
pass
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class UnhandledASGIMessageType(ASGIWebSocketTransportError):
|
| 30 |
+
def __init__(self, message: Message) -> None:
|
| 31 |
+
self.message = message
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class UnhandledWebSocketEvent(ASGIWebSocketTransportError):
|
| 35 |
+
def __init__(self, event: wsproto.events.Event) -> None:
|
| 36 |
+
self.event = event
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class ASGIWebSocketAsyncNetworkStream:
|
| 40 |
+
def __init__(
|
| 41 |
+
self,
|
| 42 |
+
app: ASGIApp,
|
| 43 |
+
scope: Scope,
|
| 44 |
+
task_group: anyio.abc.TaskGroup,
|
| 45 |
+
initial_receive_timeout: float = 1.0,
|
| 46 |
+
) -> None:
|
| 47 |
+
self.app = app
|
| 48 |
+
self.scope = scope
|
| 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))
|
| 51 |
+
self._task_group = task_group
|
| 52 |
+
self._initial_receive_timeout = initial_receive_timeout
|
| 53 |
+
self.connection = wsproto.WSConnection(wsproto.ConnectionType.SERVER)
|
| 54 |
+
self.connection.initiate_upgrade_connection(scope["headers"], scope["path"])
|
| 55 |
+
self._aentered = False
|
| 56 |
+
|
| 57 |
+
async def __aenter__(
|
| 58 |
+
self,
|
| 59 |
+
) -> tuple[ASGIWebSocketAsyncNetworkStream, bytes]:
|
| 60 |
+
if self._aentered:
|
| 61 |
+
raise RuntimeError("Cannot use ASGIWebSocketAsyncNetworkStream in a context manager twice")
|
| 62 |
+
self._aentered = True
|
| 63 |
+
self._task_group.start_soon(self._run)
|
| 64 |
+
async with contextlib.AsyncExitStack() as stack:
|
| 65 |
+
stack.push_async_callback(self.aclose)
|
| 66 |
+
await self.send({"type": "websocket.connect"})
|
| 67 |
+
|
| 68 |
+
try:
|
| 69 |
+
message = await self.receive(self._initial_receive_timeout)
|
| 70 |
+
except TimeoutError as e:
|
| 71 |
+
raise RuntimeError(
|
| 72 |
+
"WebSocket didn't accept the connection in time. Did you forget to call accept()?"
|
| 73 |
+
) from e
|
| 74 |
+
|
| 75 |
+
if message["type"] == "websocket.close":
|
| 76 |
+
await stack.aclose()
|
| 77 |
+
raise WebSocketDisconnect(message["code"], message.get("reason"))
|
| 78 |
+
|
| 79 |
+
# Websocket Denial Response extension
|
| 80 |
+
# Ref: https://asgi.readthedocs.io/en/latest/extensions.html#websocket-denial-response
|
| 81 |
+
if message["type"] == "websocket.http.response.start":
|
| 82 |
+
status_code: int = message["status"]
|
| 83 |
+
headers: list[tuple[bytes, bytes]] = message["headers"]
|
| 84 |
+
body: list[bytes] = []
|
| 85 |
+
while True:
|
| 86 |
+
message = await self.receive()
|
| 87 |
+
assert message["type"] == "websocket.http.response.body"
|
| 88 |
+
body.append(message["body"])
|
| 89 |
+
if not message.get("more_body", False):
|
| 90 |
+
break
|
| 91 |
+
|
| 92 |
+
await stack.aclose()
|
| 93 |
+
raise WebSocketUpgradeError(Response(status_code, headers=headers, content=b"".join(body)))
|
| 94 |
+
|
| 95 |
+
assert message["type"] == "websocket.accept"
|
| 96 |
+
retval = self, self._build_accept_response(message)
|
| 97 |
+
self._exit_stack = stack.pop_all()
|
| 98 |
+
return retval
|
| 99 |
+
|
| 100 |
+
async def __aexit__(
|
| 101 |
+
self,
|
| 102 |
+
exc_type: type[BaseException] | None,
|
| 103 |
+
exc_val: BaseException | None,
|
| 104 |
+
exc_tb: TracebackType | None,
|
| 105 |
+
) -> bool | None:
|
| 106 |
+
return await self._exit_stack.__aexit__(exc_type, exc_val, exc_tb)
|
| 107 |
+
|
| 108 |
+
async def read(self, max_bytes: int, timeout: float | None = None) -> bytes:
|
| 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
|
| 117 |
+
type = message["type"]
|
| 118 |
+
|
| 119 |
+
if type not in {"websocket.send", "websocket.close"}:
|
| 120 |
+
raise UnhandledASGIMessageType(message)
|
| 121 |
+
|
| 122 |
+
event: wsproto.events.Event
|
| 123 |
+
if type == "websocket.send":
|
| 124 |
+
data_str: str | None = message.get("text")
|
| 125 |
+
if data_str is not None:
|
| 126 |
+
event = wsproto.events.TextMessage(data_str)
|
| 127 |
+
data_bytes: bytes | None = message.get("bytes")
|
| 128 |
+
if data_bytes is not None:
|
| 129 |
+
event = wsproto.events.BytesMessage(data_bytes)
|
| 130 |
+
elif type == "websocket.close":
|
| 131 |
+
event = wsproto.events.CloseConnection(message["code"], message["reason"])
|
| 132 |
+
|
| 133 |
+
return self.connection.send(event)
|
| 134 |
+
|
| 135 |
+
async def write(self, buffer: bytes, timeout: float | None = None) -> None:
|
| 136 |
+
self.connection.receive_data(buffer)
|
| 137 |
+
for event in self.connection.events():
|
| 138 |
+
if isinstance(event, wsproto.events.Request):
|
| 139 |
+
pass
|
| 140 |
+
elif isinstance(event, wsproto.events.CloseConnection):
|
| 141 |
+
await self.send(
|
| 142 |
+
{
|
| 143 |
+
"type": "websocket.disconnect",
|
| 144 |
+
"code": event.code,
|
| 145 |
+
"reason": event.reason,
|
| 146 |
+
}
|
| 147 |
+
)
|
| 148 |
+
elif isinstance(event, wsproto.events.TextMessage):
|
| 149 |
+
await self.send({"type": "websocket.receive", "text": event.data})
|
| 150 |
+
elif isinstance(event, wsproto.events.BytesMessage):
|
| 151 |
+
await self.send({"type": "websocket.receive", "bytes": event.data})
|
| 152 |
+
else:
|
| 153 |
+
raise UnhandledWebSocketEvent(event)
|
| 154 |
+
|
| 155 |
+
async def aclose(self) -> None:
|
| 156 |
+
with contextlib.suppress(anyio.ClosedResourceError):
|
| 157 |
+
await self.send({"type": "websocket.disconnect"})
|
| 158 |
+
await self._receive_queue.aclose()
|
| 159 |
+
await self._send_queue.aclose()
|
| 160 |
+
|
| 161 |
+
async def send(self, message: Message) -> None:
|
| 162 |
+
await self._receive_queue.send(message)
|
| 163 |
+
|
| 164 |
+
async def receive(self, timeout: float | None = None) -> Message:
|
| 165 |
+
if timeout is None:
|
| 166 |
+
timeout = math.inf
|
| 167 |
+
with anyio.fail_after(timeout):
|
| 168 |
+
return await self._send_queue.receive()
|
| 169 |
+
|
| 170 |
+
async def _run(self) -> None:
|
| 171 |
+
"""
|
| 172 |
+
The sub-thread in which the websocket session runs.
|
| 173 |
+
"""
|
| 174 |
+
scope = self.scope
|
| 175 |
+
receive = self._receive_queue.receive
|
| 176 |
+
send = self._send_queue.send
|
| 177 |
+
try:
|
| 178 |
+
await self.app(scope, receive, send)
|
| 179 |
+
except Exception as e:
|
| 180 |
+
message = {
|
| 181 |
+
"type": "websocket.close",
|
| 182 |
+
"code": CloseReason.INTERNAL_ERROR,
|
| 183 |
+
"reason": str(e),
|
| 184 |
+
}
|
| 185 |
+
with contextlib.suppress(anyio.ClosedResourceError):
|
| 186 |
+
await send(message)
|
| 187 |
+
|
| 188 |
+
def _build_accept_response(self, message: Message) -> bytes:
|
| 189 |
+
subprotocol = message.get("subprotocol", None)
|
| 190 |
+
headers = message.get("headers", [])
|
| 191 |
+
return self.connection.send(
|
| 192 |
+
wsproto.events.AcceptConnection(
|
| 193 |
+
subprotocol=subprotocol,
|
| 194 |
+
extra_headers=headers,
|
| 195 |
+
)
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
class ASGIWebSocketTransport(ASGITransport):
|
| 200 |
+
def __init__(
|
| 201 |
+
self,
|
| 202 |
+
app: _ASGIApp,
|
| 203 |
+
raise_app_exceptions: bool = True,
|
| 204 |
+
root_path: str = "",
|
| 205 |
+
client: tuple[str, int] = ("127.0.0.1", 123),
|
| 206 |
+
initial_receive_timeout: float = 1.0,
|
| 207 |
+
) -> None:
|
| 208 |
+
super().__init__(app, raise_app_exceptions, root_path, client)
|
| 209 |
+
self._exit_stack: contextlib.AsyncExitStack | None = None
|
| 210 |
+
self._initial_receive_timeout = initial_receive_timeout
|
| 211 |
+
|
| 212 |
+
async def __aenter__(self) -> ASGIWebSocketTransport:
|
| 213 |
+
async with contextlib.AsyncExitStack() as stack:
|
| 214 |
+
self._task_group = await stack.enter_async_context(anyio.create_task_group())
|
| 215 |
+
self._exit_stack = stack.pop_all()
|
| 216 |
+
|
| 217 |
+
return self
|
| 218 |
+
|
| 219 |
+
async def __aexit__(
|
| 220 |
+
self,
|
| 221 |
+
exc_type: type[BaseException] | None = None,
|
| 222 |
+
exc_val: BaseException | None = None,
|
| 223 |
+
exc_tb: TracebackType | None = None,
|
| 224 |
+
) -> None:
|
| 225 |
+
await super().__aexit__(exc_type, exc_val, exc_tb)
|
| 226 |
+
assert self._exit_stack is not None
|
| 227 |
+
await self._exit_stack.__aexit__(exc_type, exc_val, exc_tb)
|
| 228 |
+
|
| 229 |
+
async def handle_async_request(self, request: Request) -> Response:
|
| 230 |
+
scheme = request.url.scheme
|
| 231 |
+
headers = request.headers
|
| 232 |
+
|
| 233 |
+
if scheme in {"ws", "wss"} or headers.get("upgrade") == "websocket":
|
| 234 |
+
subprotocols: list[str] = []
|
| 235 |
+
if (subprotocols_header := headers.get("sec-websocket-protocol")) is not None:
|
| 236 |
+
subprotocols = subprotocols_header.split(",")
|
| 237 |
+
|
| 238 |
+
scope = {
|
| 239 |
+
"type": "websocket",
|
| 240 |
+
"path": request.url.path,
|
| 241 |
+
"raw_path": request.url.raw_path,
|
| 242 |
+
"root_path": self.root_path,
|
| 243 |
+
"scheme": scheme,
|
| 244 |
+
"query_string": request.url.query,
|
| 245 |
+
"headers": [(k.lower(), v) for (k, v) in request.headers.raw],
|
| 246 |
+
"client": self.client,
|
| 247 |
+
"server": (request.url.host, request.url.port),
|
| 248 |
+
"subprotocols": subprotocols,
|
| 249 |
+
}
|
| 250 |
+
return await self._handle_ws_request(request, scope)
|
| 251 |
+
|
| 252 |
+
return await super().handle_async_request(request)
|
| 253 |
+
|
| 254 |
+
async def _create_asgi_websocket_async_network_stream(
|
| 255 |
+
self,
|
| 256 |
+
*,
|
| 257 |
+
task_status: anyio.abc.TaskStatus[tuple[ASGIWebSocketAsyncNetworkStream, bytes]],
|
| 258 |
+
) -> None:
|
| 259 |
+
stream = ASGIWebSocketAsyncNetworkStream(
|
| 260 |
+
self.app, # type: ignore[arg-type]
|
| 261 |
+
self.scope,
|
| 262 |
+
self._task_group,
|
| 263 |
+
self._initial_receive_timeout,
|
| 264 |
+
)
|
| 265 |
+
assert self._exit_stack is not None
|
| 266 |
+
result = await self._exit_stack.enter_async_context(stream)
|
| 267 |
+
task_status.started(result)
|
| 268 |
+
|
| 269 |
+
async def _handle_ws_request(
|
| 270 |
+
self,
|
| 271 |
+
request: Request,
|
| 272 |
+
scope: Scope,
|
| 273 |
+
) -> Response:
|
| 274 |
+
assert isinstance(request.stream, AsyncByteStream)
|
| 275 |
+
|
| 276 |
+
self.scope = scope
|
| 277 |
+
stream, accept_response = await self._task_group.start(self._create_asgi_websocket_async_network_stream)
|
| 278 |
+
accept_response_lines = accept_response.decode("utf-8").splitlines()
|
| 279 |
+
headers = [
|
| 280 |
+
typing.cast(tuple[str, str], line.split(": ", 1))
|
| 281 |
+
for line in accept_response_lines[1:]
|
| 282 |
+
if line.strip() != ""
|
| 283 |
+
]
|
| 284 |
+
|
| 285 |
+
return Response(
|
| 286 |
+
status_code=101,
|
| 287 |
+
headers=headers,
|
| 288 |
+
extensions={"network_stream": stream},
|
| 289 |
+
)
|
.venv/lib/python3.12/site-packages/huggingface_hub-2.4.0.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
uv
|
.venv/lib/python3.12/site-packages/huggingface_hub-2.4.0.dist-info/METADATA
ADDED
|
@@ -0,0 +1,366 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: huggingface_hub
|
| 3 |
+
Version: 2.4.0
|
| 4 |
+
Summary: Client library to download and publish models, datasets and other repos on the huggingface.co hub
|
| 5 |
+
Home-page: https://github.com/huggingface/huggingface_hub
|
| 6 |
+
Author: Hugging Face, Inc.
|
| 7 |
+
Author-email: julien@huggingface.co
|
| 8 |
+
License: Apache-2.0
|
| 9 |
+
Keywords: model-hub machine-learning models natural-language-processing deep-learning pytorch pretrained-models
|
| 10 |
+
Classifier: Intended Audience :: Developers
|
| 11 |
+
Classifier: Intended Audience :: Education
|
| 12 |
+
Classifier: Intended Audience :: Science/Research
|
| 13 |
+
Classifier: License :: OSI Approved :: Apache Software License
|
| 14 |
+
Classifier: Operating System :: OS Independent
|
| 15 |
+
Classifier: Programming Language :: Python :: 3
|
| 16 |
+
Classifier: Programming Language :: Python :: 3 :: Only
|
| 17 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 18 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 19 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 20 |
+
Classifier: Programming Language :: Python :: 3.13
|
| 21 |
+
Classifier: Programming Language :: Python :: 3.14
|
| 22 |
+
Classifier: Programming Language :: Python :: 3.15
|
| 23 |
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
| 24 |
+
Requires-Python: >=3.10.0
|
| 25 |
+
Description-Content-Type: text/markdown
|
| 26 |
+
License-File: LICENSE
|
| 27 |
+
Requires-Dist: click<9.0.0,>=8.4.2
|
| 28 |
+
Requires-Dist: filelock>=3.10.0
|
| 29 |
+
Requires-Dist: fsspec>=2023.5.0
|
| 30 |
+
Requires-Dist: hf-xet<2.0.0,>=1.6.0; platform_machine == "x86_64" or platform_machine == "amd64" or platform_machine == "AMD64" or platform_machine == "arm64" or platform_machine == "ARM64" or platform_machine == "aarch64"
|
| 31 |
+
Requires-Dist: httpx2<3,>=2.0.0
|
| 32 |
+
Requires-Dist: packaging>=20.9
|
| 33 |
+
Requires-Dist: pyyaml>=5.1
|
| 34 |
+
Requires-Dist: tomli>=1.1.0; python_version < "3.11"
|
| 35 |
+
Requires-Dist: tqdm>=4.42.1
|
| 36 |
+
Requires-Dist: typing-extensions>=4.1.0
|
| 37 |
+
Provides-Extra: oauth
|
| 38 |
+
Requires-Dist: authlib>=1.8.0; extra == "oauth"
|
| 39 |
+
Requires-Dist: fastapi; extra == "oauth"
|
| 40 |
+
Requires-Dist: itsdangerous; extra == "oauth"
|
| 41 |
+
Provides-Extra: torch
|
| 42 |
+
Requires-Dist: torch; extra == "torch"
|
| 43 |
+
Requires-Dist: safetensors[torch]; extra == "torch"
|
| 44 |
+
Provides-Extra: fastai
|
| 45 |
+
Requires-Dist: toml; extra == "fastai"
|
| 46 |
+
Requires-Dist: fastai>=2.4; extra == "fastai"
|
| 47 |
+
Requires-Dist: fastcore>=1.3.27; extra == "fastai"
|
| 48 |
+
Provides-Extra: hf-xet
|
| 49 |
+
Requires-Dist: hf-xet<2.0.0,>=1.6.0; extra == "hf-xet"
|
| 50 |
+
Provides-Extra: mcp
|
| 51 |
+
Requires-Dist: mcp<2.0.0,>=1.9.4; extra == "mcp"
|
| 52 |
+
Provides-Extra: testing
|
| 53 |
+
Requires-Dist: authlib>=1.8.0; extra == "testing"
|
| 54 |
+
Requires-Dist: fastapi; extra == "testing"
|
| 55 |
+
Requires-Dist: itsdangerous; extra == "testing"
|
| 56 |
+
Requires-Dist: jedi; extra == "testing"
|
| 57 |
+
Requires-Dist: Jinja2; extra == "testing"
|
| 58 |
+
Requires-Dist: pytest>=8.4.2; extra == "testing"
|
| 59 |
+
Requires-Dist: pytest-cov; extra == "testing"
|
| 60 |
+
Requires-Dist: pytest-env; extra == "testing"
|
| 61 |
+
Requires-Dist: pytest-xdist; extra == "testing"
|
| 62 |
+
Requires-Dist: pytest-vcr; extra == "testing"
|
| 63 |
+
Requires-Dist: pytest-asyncio; extra == "testing"
|
| 64 |
+
Requires-Dist: pytest-rerunfailures>=16.2; extra == "testing"
|
| 65 |
+
Requires-Dist: pytest-mock; extra == "testing"
|
| 66 |
+
Requires-Dist: soundfile; extra == "testing"
|
| 67 |
+
Requires-Dist: Pillow; extra == "testing"
|
| 68 |
+
Requires-Dist: numpy; extra == "testing"
|
| 69 |
+
Requires-Dist: duckdb; python_version < "3.15" and extra == "testing"
|
| 70 |
+
Requires-Dist: fastapi; extra == "testing"
|
| 71 |
+
Provides-Extra: gradio
|
| 72 |
+
Requires-Dist: gradio>=5.0.0; extra == "gradio"
|
| 73 |
+
Requires-Dist: requests; extra == "gradio"
|
| 74 |
+
Provides-Extra: typing
|
| 75 |
+
Requires-Dist: typing-extensions>=4.8.0; extra == "typing"
|
| 76 |
+
Requires-Dist: types-PyYAML; extra == "typing"
|
| 77 |
+
Requires-Dist: types-simplejson; extra == "typing"
|
| 78 |
+
Requires-Dist: types-toml; extra == "typing"
|
| 79 |
+
Requires-Dist: types-tqdm; extra == "typing"
|
| 80 |
+
Requires-Dist: types-urllib3; extra == "typing"
|
| 81 |
+
Provides-Extra: quality
|
| 82 |
+
Requires-Dist: ruff>=0.9.0; extra == "quality"
|
| 83 |
+
Requires-Dist: mypy==1.15.0; extra == "quality"
|
| 84 |
+
Requires-Dist: libcst>=1.4.0; extra == "quality"
|
| 85 |
+
Requires-Dist: ty; extra == "quality"
|
| 86 |
+
Provides-Extra: all
|
| 87 |
+
Requires-Dist: authlib>=1.8.0; extra == "all"
|
| 88 |
+
Requires-Dist: fastapi; extra == "all"
|
| 89 |
+
Requires-Dist: itsdangerous; extra == "all"
|
| 90 |
+
Requires-Dist: jedi; extra == "all"
|
| 91 |
+
Requires-Dist: Jinja2; extra == "all"
|
| 92 |
+
Requires-Dist: pytest>=8.4.2; extra == "all"
|
| 93 |
+
Requires-Dist: pytest-cov; extra == "all"
|
| 94 |
+
Requires-Dist: pytest-env; extra == "all"
|
| 95 |
+
Requires-Dist: pytest-xdist; extra == "all"
|
| 96 |
+
Requires-Dist: pytest-vcr; extra == "all"
|
| 97 |
+
Requires-Dist: pytest-asyncio; extra == "all"
|
| 98 |
+
Requires-Dist: pytest-rerunfailures>=16.2; extra == "all"
|
| 99 |
+
Requires-Dist: pytest-mock; extra == "all"
|
| 100 |
+
Requires-Dist: soundfile; extra == "all"
|
| 101 |
+
Requires-Dist: Pillow; extra == "all"
|
| 102 |
+
Requires-Dist: numpy; extra == "all"
|
| 103 |
+
Requires-Dist: duckdb; python_version < "3.15" and extra == "all"
|
| 104 |
+
Requires-Dist: fastapi; extra == "all"
|
| 105 |
+
Requires-Dist: ruff>=0.9.0; extra == "all"
|
| 106 |
+
Requires-Dist: mypy==1.15.0; extra == "all"
|
| 107 |
+
Requires-Dist: libcst>=1.4.0; extra == "all"
|
| 108 |
+
Requires-Dist: ty; extra == "all"
|
| 109 |
+
Requires-Dist: typing-extensions>=4.8.0; extra == "all"
|
| 110 |
+
Requires-Dist: types-PyYAML; extra == "all"
|
| 111 |
+
Requires-Dist: types-simplejson; extra == "all"
|
| 112 |
+
Requires-Dist: types-toml; extra == "all"
|
| 113 |
+
Requires-Dist: types-tqdm; extra == "all"
|
| 114 |
+
Requires-Dist: types-urllib3; extra == "all"
|
| 115 |
+
Provides-Extra: dev
|
| 116 |
+
Requires-Dist: authlib>=1.8.0; extra == "dev"
|
| 117 |
+
Requires-Dist: fastapi; extra == "dev"
|
| 118 |
+
Requires-Dist: itsdangerous; extra == "dev"
|
| 119 |
+
Requires-Dist: jedi; extra == "dev"
|
| 120 |
+
Requires-Dist: Jinja2; extra == "dev"
|
| 121 |
+
Requires-Dist: pytest>=8.4.2; extra == "dev"
|
| 122 |
+
Requires-Dist: pytest-cov; extra == "dev"
|
| 123 |
+
Requires-Dist: pytest-env; extra == "dev"
|
| 124 |
+
Requires-Dist: pytest-xdist; extra == "dev"
|
| 125 |
+
Requires-Dist: pytest-vcr; extra == "dev"
|
| 126 |
+
Requires-Dist: pytest-asyncio; extra == "dev"
|
| 127 |
+
Requires-Dist: pytest-rerunfailures>=16.2; extra == "dev"
|
| 128 |
+
Requires-Dist: pytest-mock; extra == "dev"
|
| 129 |
+
Requires-Dist: soundfile; extra == "dev"
|
| 130 |
+
Requires-Dist: Pillow; extra == "dev"
|
| 131 |
+
Requires-Dist: numpy; extra == "dev"
|
| 132 |
+
Requires-Dist: duckdb; python_version < "3.15" and extra == "dev"
|
| 133 |
+
Requires-Dist: fastapi; extra == "dev"
|
| 134 |
+
Requires-Dist: ruff>=0.9.0; extra == "dev"
|
| 135 |
+
Requires-Dist: mypy==1.15.0; extra == "dev"
|
| 136 |
+
Requires-Dist: libcst>=1.4.0; extra == "dev"
|
| 137 |
+
Requires-Dist: ty; extra == "dev"
|
| 138 |
+
Requires-Dist: typing-extensions>=4.8.0; extra == "dev"
|
| 139 |
+
Requires-Dist: types-PyYAML; extra == "dev"
|
| 140 |
+
Requires-Dist: types-simplejson; extra == "dev"
|
| 141 |
+
Requires-Dist: types-toml; extra == "dev"
|
| 142 |
+
Requires-Dist: types-tqdm; extra == "dev"
|
| 143 |
+
Requires-Dist: types-urllib3; extra == "dev"
|
| 144 |
+
Dynamic: author
|
| 145 |
+
Dynamic: author-email
|
| 146 |
+
Dynamic: classifier
|
| 147 |
+
Dynamic: description
|
| 148 |
+
Dynamic: description-content-type
|
| 149 |
+
Dynamic: home-page
|
| 150 |
+
Dynamic: keywords
|
| 151 |
+
Dynamic: license
|
| 152 |
+
Dynamic: license-file
|
| 153 |
+
Dynamic: provides-extra
|
| 154 |
+
Dynamic: requires-dist
|
| 155 |
+
Dynamic: requires-python
|
| 156 |
+
Dynamic: summary
|
| 157 |
+
|
| 158 |
+
<p align="center">
|
| 159 |
+
<picture>
|
| 160 |
+
<source media="(prefers-color-scheme: dark)" srcset="https://huggingface.co/datasets/huggingface/documentation-images/raw/main/huggingface_hub-dark.svg">
|
| 161 |
+
<source media="(prefers-color-scheme: light)" srcset="https://huggingface.co/datasets/huggingface/documentation-images/raw/main/huggingface_hub.svg">
|
| 162 |
+
<img alt="huggingface_hub library logo" src="https://huggingface.co/datasets/huggingface/documentation-images/raw/main/huggingface_hub.svg" width="352" height="59" style="max-width: 100%">
|
| 163 |
+
</picture>
|
| 164 |
+
<br/>
|
| 165 |
+
<br/>
|
| 166 |
+
</p>
|
| 167 |
+
|
| 168 |
+
<p align="center">
|
| 169 |
+
<i>The official CLI and Python client for the Hugging Face Hub.</i>
|
| 170 |
+
<br/>
|
| 171 |
+
<a href="#what-is-huggingface_hub">About</a>
|
| 172 |
+
·
|
| 173 |
+
<a href="https://huggingface.co/docs/huggingface_hub">Documentation</a>
|
| 174 |
+
·
|
| 175 |
+
<a href="https://huggingface.co/docs/huggingface_hub/en/installation">Install</a>
|
| 176 |
+
·
|
| 177 |
+
<a href="https://huggingface.co/docs/huggingface_hub/en/guides/cli">CLI Guide</a>
|
| 178 |
+
·
|
| 179 |
+
<a href="https://github.com/huggingface/huggingface_hub/blob/main/CONTRIBUTING.md">Contributing</a>
|
| 180 |
+
</p>
|
| 181 |
+
|
| 182 |
+
<p align="center">
|
| 183 |
+
<a href="https://huggingface.co/docs/huggingface_hub/en/index"><img alt="Documentation" src="https://img.shields.io/website/http/huggingface.co/docs/huggingface_hub/index.svg?down_color=red&down_message=offline&up_message=online&label=doc"></a>
|
| 184 |
+
<a href="https://github.com/huggingface/huggingface_hub/releases"><img alt="GitHub release" src="https://img.shields.io/github/release/huggingface/huggingface_hub.svg"></a>
|
| 185 |
+
<a href="https://github.com/huggingface/huggingface_hub"><img alt="PyPi version" src="https://img.shields.io/pypi/pyversions/huggingface_hub.svg"></a>
|
| 186 |
+
<a href="https://pypi.org/project/huggingface-hub"><img alt="PyPI - Downloads" src="https://img.shields.io/pypi/dm/huggingface_hub"></a>
|
| 187 |
+
<a href="https://codecov.io/gh/huggingface/huggingface_hub"><img alt="Code coverage" src="https://codecov.io/gh/huggingface/huggingface_hub/branch/main/graph/badge.svg?token=RXP95LE2XL"></a>
|
| 188 |
+
</p>
|
| 189 |
+
|
| 190 |
+
<h4 align="center">
|
| 191 |
+
<p>
|
| 192 |
+
<b>English</b> |
|
| 193 |
+
<a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_de.md">Deutsch</a> |
|
| 194 |
+
<a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_fr.md">Français</a> |
|
| 195 |
+
<a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_hi.md">हिंदी</a> |
|
| 196 |
+
<a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_ko.md">한국어</a> |
|
| 197 |
+
<a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_cn.md">中文 (简体)</a> |
|
| 198 |
+
<a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_kn.md">ಕನ್ನಡ</a>
|
| 199 |
+
</p>
|
| 200 |
+
</h4>
|
| 201 |
+
|
| 202 |
+
## Quick start
|
| 203 |
+
|
| 204 |
+
Install the [`hf` CLI](https://huggingface.co/docs/huggingface_hub/en/guides/cli) with the standalone installer:
|
| 205 |
+
|
| 206 |
+
```bash
|
| 207 |
+
# On macOS and Linux.
|
| 208 |
+
curl -LsSf https://hf.co/cli/install.sh | bash
|
| 209 |
+
```
|
| 210 |
+
|
| 211 |
+
```powershell
|
| 212 |
+
# On Windows.
|
| 213 |
+
powershell -ExecutionPolicy ByPass -c "irm https://hf.co/cli/install.ps1 | iex"
|
| 214 |
+
```
|
| 215 |
+
|
| 216 |
+
Log in, then start working with the Hub:
|
| 217 |
+
|
| 218 |
+
```bash
|
| 219 |
+
# Log in (use --token $HF_TOKEN in non-interactive environments)
|
| 220 |
+
hf auth login
|
| 221 |
+
|
| 222 |
+
# Find models served by Inference Providers
|
| 223 |
+
hf models ls --warm
|
| 224 |
+
|
| 225 |
+
# Download a model
|
| 226 |
+
hf download Qwen/Qwen3-0.6B
|
| 227 |
+
|
| 228 |
+
# Upload files to your own repo
|
| 229 |
+
hf upload username/my-cool-model ./model.safetensors
|
| 230 |
+
|
| 231 |
+
# Sync a local folder to a storage bucket
|
| 232 |
+
hf buckets sync ./checkpoints hf://buckets/username/my-bucket
|
| 233 |
+
|
| 234 |
+
# Run a job on Hugging Face infrastructure
|
| 235 |
+
hf jobs run python:3.12 python -c "print('Hello from the cloud!')"
|
| 236 |
+
|
| 237 |
+
# Discover everything else
|
| 238 |
+
hf --help
|
| 239 |
+
```
|
| 240 |
+
|
| 241 |
+
The Hub uses tokens to authenticate applications (see [docs](https://huggingface.co/docs/hub/security-tokens)). Check out the [CLI guide](https://huggingface.co/docs/huggingface_hub/en/guides/cli) for a tour of the main features.
|
| 242 |
+
|
| 243 |
+
## What is `huggingface_hub`?
|
| 244 |
+
|
| 245 |
+
The `huggingface_hub` library allows you to interact with the [Hugging Face Hub](https://huggingface.co/), a platform democratizing open-source Machine Learning for creators and collaborators. Discover pre-trained models and datasets for your projects, play with the thousands of machine learning apps hosted on the Hub, or create and share your own models, datasets and demos with the community. Everything ships in one package with two interfaces: the [`hf` CLI](https://huggingface.co/docs/huggingface_hub/en/guides/cli) for your terminal and the `huggingface_hub` library for Python — both designed to work well for humans and AI agents. Use them to:
|
| 246 |
+
|
| 247 |
+
- [Download files](https://huggingface.co/docs/huggingface_hub/en/guides/download) from the Hub.
|
| 248 |
+
- [Upload files](https://huggingface.co/docs/huggingface_hub/en/guides/upload) to the Hub.
|
| 249 |
+
- [Manage your repositories](https://huggingface.co/docs/huggingface_hub/en/guides/repository).
|
| 250 |
+
- [Run Inference](https://huggingface.co/docs/huggingface_hub/en/guides/inference) on deployed models.
|
| 251 |
+
- [Run Jobs](https://huggingface.co/docs/huggingface_hub/en/guides/jobs) on Hugging Face infrastructure.
|
| 252 |
+
- [Search](https://huggingface.co/docs/huggingface_hub/en/guides/search) for models, datasets and Spaces.
|
| 253 |
+
- [Share Model Cards](https://huggingface.co/docs/huggingface_hub/en/guides/model-cards) to document your models.
|
| 254 |
+
- [Engage with the community](https://huggingface.co/docs/huggingface_hub/en/guides/community) through PRs and comments.
|
| 255 |
+
- Do all of the above from the terminal with the [`hf` CLI](https://huggingface.co/docs/huggingface_hub/en/guides/cli).
|
| 256 |
+
|
| 257 |
+
## Built for humans and AI agents
|
| 258 |
+
|
| 259 |
+
The `hf` CLI is designed for people and coding agents alike: the same commands adapt their output when run by an agent. If you use Claude Code, Codex, Cursor, or another coding agent, install the `hf` CLI Skill — a command reference generated from your installed CLI:
|
| 260 |
+
|
| 261 |
+
```bash
|
| 262 |
+
# works with Claude Code, Codex, Cursor, OpenCode, Pi and any agent that loads skills from `.agents/skills`
|
| 263 |
+
hf skills add
|
| 264 |
+
```
|
| 265 |
+
|
| 266 |
+
Learn more in the [Hugging Face CLI for AI agents guide](https://huggingface.co/docs/hub/agents-cli) and the [announcement blog post](https://huggingface.co/blog/hf-cli-for-agents).
|
| 267 |
+
|
| 268 |
+
## Use the Python library
|
| 269 |
+
|
| 270 |
+
Install the `huggingface_hub` package with [pip](https://pypi.org/project/huggingface-hub/) (this also installs the `hf` CLI):
|
| 271 |
+
|
| 272 |
+
```bash
|
| 273 |
+
pip install huggingface_hub
|
| 274 |
+
```
|
| 275 |
+
|
| 276 |
+
We recommend using [`uv`](https://docs.astral.sh/uv/) for a fast and reliable install:
|
| 277 |
+
|
| 278 |
+
```bash
|
| 279 |
+
uv pip install huggingface_hub
|
| 280 |
+
```
|
| 281 |
+
|
| 282 |
+
In order to keep the package minimal by default, `huggingface_hub` comes with optional dependencies useful for some use cases. For example, if you want to use the MCP module, run:
|
| 283 |
+
|
| 284 |
+
```bash
|
| 285 |
+
pip install "huggingface_hub[mcp]"
|
| 286 |
+
```
|
| 287 |
+
|
| 288 |
+
To learn more about installation and optional dependencies, check out the [installation guide](https://huggingface.co/docs/huggingface_hub/en/installation).
|
| 289 |
+
|
| 290 |
+
### Download files
|
| 291 |
+
|
| 292 |
+
Download a single file
|
| 293 |
+
|
| 294 |
+
```py
|
| 295 |
+
from huggingface_hub import hf_hub_download
|
| 296 |
+
|
| 297 |
+
hf_hub_download(repo_id="zai-org/GLM-5.2", filename="config.json")
|
| 298 |
+
```
|
| 299 |
+
|
| 300 |
+
Or an entire repository
|
| 301 |
+
|
| 302 |
+
```py
|
| 303 |
+
from huggingface_hub import snapshot_download
|
| 304 |
+
|
| 305 |
+
snapshot_download("sentence-transformers/all-MiniLM-L6-v2")
|
| 306 |
+
```
|
| 307 |
+
|
| 308 |
+
Files will be downloaded in a local cache folder. More details in [this guide](https://huggingface.co/docs/huggingface_hub/en/guides/manage-cache).
|
| 309 |
+
|
| 310 |
+
### Create a repository
|
| 311 |
+
|
| 312 |
+
```py
|
| 313 |
+
from huggingface_hub import create_repo
|
| 314 |
+
|
| 315 |
+
create_repo(repo_id="super-cool-model")
|
| 316 |
+
```
|
| 317 |
+
|
| 318 |
+
### Upload files
|
| 319 |
+
|
| 320 |
+
Upload a single file
|
| 321 |
+
|
| 322 |
+
```py
|
| 323 |
+
from huggingface_hub import upload_file
|
| 324 |
+
|
| 325 |
+
upload_file(
|
| 326 |
+
path_or_fileobj="/home/lysandre/dummy-test/README.md",
|
| 327 |
+
path_in_repo="README.md",
|
| 328 |
+
repo_id="lysandre/test-model",
|
| 329 |
+
)
|
| 330 |
+
```
|
| 331 |
+
|
| 332 |
+
Or an entire folder
|
| 333 |
+
|
| 334 |
+
```py
|
| 335 |
+
from huggingface_hub import upload_folder
|
| 336 |
+
|
| 337 |
+
upload_folder(
|
| 338 |
+
folder_path="/path/to/local/space",
|
| 339 |
+
repo_id="username/my-cool-space",
|
| 340 |
+
repo_type="space",
|
| 341 |
+
)
|
| 342 |
+
```
|
| 343 |
+
|
| 344 |
+
More details in the [upload guide](https://huggingface.co/docs/huggingface_hub/en/guides/upload).
|
| 345 |
+
|
| 346 |
+
## Integrating with the Hub.
|
| 347 |
+
|
| 348 |
+
We're partnering with cool open source ML libraries to provide free model hosting and versioning. You can find the existing integrations [here](https://huggingface.co/docs/hub/libraries).
|
| 349 |
+
|
| 350 |
+
The advantages are:
|
| 351 |
+
|
| 352 |
+
- Free model or dataset hosting for libraries and their users.
|
| 353 |
+
- Built-in file versioning, even with very large files, made possible by [Xet](https://huggingface.co/docs/hub/xet/index), the Hub's chunk-deduplicated storage backend.
|
| 354 |
+
- In-browser widgets to play with the uploaded models.
|
| 355 |
+
- Anyone can upload a new model for your library, they just need to add the corresponding tag for the model to be discoverable.
|
| 356 |
+
- Fast downloads! We use Cloudfront (a CDN) to geo-replicate downloads so they're blazing fast from anywhere on the globe.
|
| 357 |
+
- Usage stats and more features to come.
|
| 358 |
+
|
| 359 |
+
If you would like to integrate your library, feel free to open an issue to begin the discussion. We wrote a [step-by-step guide](https://huggingface.co/docs/hub/adding-a-library) with ❤️ showing how to do this integration.
|
| 360 |
+
|
| 361 |
+
## Contributions (feature requests, bugs, etc.) are super welcome 💙💚💛💜🧡❤️
|
| 362 |
+
|
| 363 |
+
Everyone is welcome to contribute, and we value everybody's contribution. Code is not the only way to help the community.
|
| 364 |
+
Answering questions, helping others, reaching out and improving the documentations are immensely valuable to the community.
|
| 365 |
+
We wrote a [contribution guide](https://github.com/huggingface/huggingface_hub/blob/main/CONTRIBUTING.md) to summarize
|
| 366 |
+
how to get started to contribute to this repository.
|
.venv/lib/python3.12/site-packages/huggingface_hub-2.4.0.dist-info/RECORD
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
../../../bin/hf,sha256=kabb-uE5uJofdz7s47w3rQGQQ_jLaWzXFifCF4YgfN4,372
|
| 2 |
+
../../../bin/tiny-agents,sha256=NrV9kKFg1WD_7u7HcFSKd8ERb0SGW7VOF-N894tamGY,382
|
| 3 |
+
huggingface_hub-2.4.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
|
| 4 |
+
huggingface_hub-2.4.0.dist-info/METADATA,sha256=tXXV6r4LOBSJ2ywWO7OC9O9EWI_79GikBScZvxYbQhE,16212
|
| 5 |
+
huggingface_hub-2.4.0.dist-info/RECORD,,
|
| 6 |
+
huggingface_hub-2.4.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 7 |
+
huggingface_hub-2.4.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
| 8 |
+
huggingface_hub-2.4.0.dist-info/entry_points.txt,sha256=j3KnOggx2dIP7NUkPyYgXdRnLxd94aHmqJ8J6tEZwY8,154
|
| 9 |
+
huggingface_hub-2.4.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
|
| 10 |
+
huggingface_hub-2.4.0.dist-info/top_level.txt,sha256=8KzlQJAY4miUvjAssOAJodqKOw3harNzuiwGQ9qLSSk,16
|
| 11 |
+
huggingface_hub/__init__.py,sha256=A8NGYqCY-tGjrWk5praWD3jkKbb1-VY6OdnqpVJ5E2g,61730
|
| 12 |
+
huggingface_hub/_bucket_live_follow.py,sha256=p3eA6f5ufa_vKzmiD_95k6NdGA8NWhr-wv_kAqUinO0,19241
|
| 13 |
+
huggingface_hub/_buckets.py,sha256=EtUkG6OWBkfIF5BmIafMeBHtsC5OhcFcQ9A4GCL2Kbk,46065
|
| 14 |
+
huggingface_hub/_commit_api.py,sha256=_dgylJ67ADsnn7mSUcXHgU7YHr1dQ35BJSqlJvHcueM,45690
|
| 15 |
+
huggingface_hub/_commit_scheduler.py,sha256=Nn00XoWBcxC426nRx8gA835mioX6aXjuCOLWdCG-noc,14707
|
| 16 |
+
huggingface_hub/_dataset_viewer.py,sha256=deMfUXAboEfHP4a4l70KrmB-B6FePFtFUUCmIYuqwn4,5705
|
| 17 |
+
huggingface_hub/_eval_results.py,sha256=toIFXp9cwrwOCr21C8WuDV_o5_WP2Zh_1dYlkXorku8,8389
|
| 18 |
+
huggingface_hub/_hot_reload/__init__.py,sha256=nQEuyVZLAS_463Dff1JH5MorTpkYsBVFCyPhYWY3UyI,606
|
| 19 |
+
huggingface_hub/_hot_reload/client.py,sha256=3CrJMyJsIIrg7jZL95BA7YIt6dhSAjUdoy8IVplSg70,4271
|
| 20 |
+
huggingface_hub/_hot_reload/sse_client.py,sha256=49kmsB2P9sxgbZ16ed6F4aLDs3rsHrNpbp6iKlvF90c,4948
|
| 21 |
+
huggingface_hub/_hot_reload/types.py,sha256=d3AOJCLUxT41Fhz4jUrFevm9bfpooe_3PQhpBdgNYSs,2725
|
| 22 |
+
huggingface_hub/_inference_endpoints.py,sha256=K3G50whKgSPCMXm_7yhIqck7jQaEDf9FQ8FxZ-xv4qs,29398
|
| 23 |
+
huggingface_hub/_jobs_api.py,sha256=T24oDg8ZONMjBiU4SyWs2zYKrCkl_iMECoUlwLwTBuI,27226
|
| 24 |
+
huggingface_hub/_local_folder.py,sha256=nvH1s0_dUNlOMhYMgQ9ys_ysMVJdXdRz4msIq5glbHw,19551
|
| 25 |
+
huggingface_hub/_login.py,sha256=wAMdhqMSSh3GBJDozodmk4IIsAvb9J6LaLY9KnXFoyY,21818
|
| 26 |
+
huggingface_hub/_oauth.py,sha256=S8evEd8JLJHz-JiSjGH4WiIi_A7oDox_xH7E9rN1Jic,18628
|
| 27 |
+
huggingface_hub/_oidc.py,sha256=3kcCLavWQ5FQOwizUPzLaBb1ft2FIJo0bSXL24S3r4U,7098
|
| 28 |
+
huggingface_hub/_revision.py,sha256=_8BYj35dJ5u9iOzaCuTEPtWympQw4fvk-j_GSxQu49M,2549
|
| 29 |
+
huggingface_hub/_sandbox.py,sha256=3rNu3C4Md60Ox2QPLPqUqqhSMOeA1mCbRY-LJ6NOlqY,123668
|
| 30 |
+
huggingface_hub/_sandbox_cache.py,sha256=vA409SxJ-QLXxoS4it2Vc1oIwRzazxapkyjjAD-_R8g,15386
|
| 31 |
+
huggingface_hub/_snapshot_download.py,sha256=M66nYxht8tZgDiAI6R67hiz8EpB2OMrquX6YZc8FLZc,31753
|
| 32 |
+
huggingface_hub/_space_api.py,sha256=63B6F5iO58ELAHDqPjIgvWJ8_y5nSXr5M5gPocBeCKI,14990
|
| 33 |
+
huggingface_hub/_tensorboard_logger.py,sha256=WG4w2LgWxU4ITn1Dr3i9O0PG8Rzry3SPwKBO5vQfCnQ,8239
|
| 34 |
+
huggingface_hub/_tree_cache.py,sha256=mJ3oFOLSdjXQ5Y2zyA_oHgRi4Vza3LXEtTsZeuTR1c0,6111
|
| 35 |
+
huggingface_hub/_upload_pipeline.py,sha256=6u0x3312yYxjb308FRw0TjqJDoMsHRgzEvm0_OxDWIw,32084
|
| 36 |
+
huggingface_hub/_webhooks_payload.py,sha256=B9zqljcm20DGeVxJKba570i6RP-cR9CEupMGBuNDHHA,3544
|
| 37 |
+
huggingface_hub/_webhooks_server.py,sha256=fjEfZztSrLBLW3SoRdcfOHV9gHhR1Zrn_FYqMzWs2FY,15772
|
| 38 |
+
huggingface_hub/cli/__init__.py,sha256=tWu3Is-m2tlJwXhM_vT2mPRgpnt9KhU9qvw5aRsnjU0,664
|
| 39 |
+
huggingface_hub/cli/_city_game.py,sha256=2qkC9dCtPwf4-aqrnbN-vApf0YqIcGGjn2v-etrTfqg,20585
|
| 40 |
+
huggingface_hub/cli/_cli_utils.py,sha256=GG3Ko6ErsGAtoBlKjBZ7JSnqrBWvF7gd2a7yXKZMKII,49761
|
| 41 |
+
huggingface_hub/cli/_completion.py,sha256=BDP6Vob9TLFp6K3lr0XOY98FyD-rm22KrjwsO_YGNbE,3759
|
| 42 |
+
huggingface_hub/cli/_cp.py,sha256=Z-2Z_tBs1e4XBqRO5R9QnabU4qTi9HDlbA52jTBaCkY,10436
|
| 43 |
+
huggingface_hub/cli/_errors.py,sha256=X0rUTO-3eCK5v_MLGEza1BxcuXGccPY-h7ShzmuQc34,5907
|
| 44 |
+
huggingface_hub/cli/_file_listing.py,sha256=8e-0ZKNFau--fWD7V4pc1BSwnW-Z_grqRyv5Dy7gsI4,8147
|
| 45 |
+
huggingface_hub/cli/_framework.py,sha256=34sJGPQtX49jdudwaXO3vhwPPtS1HQS-asocQTAfTLE,28055
|
| 46 |
+
huggingface_hub/cli/_help_formatter.py,sha256=-vsa3HfHQFkKWms77EGyp9i22t44ETmVt2L-e8qP-KM,1288
|
| 47 |
+
huggingface_hub/cli/_output.py,sha256=oz4PMpTwTlGii8bDSrX5f1WMsTcRXgGrCCsDyEjAmtI,15558
|
| 48 |
+
huggingface_hub/cli/_skills.py,sha256=P2L2acXxKDRrF1z5GYGgX4T43VFDnEzH42TPxDVj1Qk,15109
|
| 49 |
+
huggingface_hub/cli/_uv_script_header.py,sha256=-LYNgaA4i3ZyETASlg5_KA8QL_o8qHPJdQwldNjzt2o,9397
|
| 50 |
+
huggingface_hub/cli/auth.py,sha256=WVxVkOeHCPB1Iy7oeVhtu-OzGck4Fa-VQPmxfGEfobY,6084
|
| 51 |
+
huggingface_hub/cli/buckets.py,sha256=o3jm3vVElrG9yvQykSGhHxjAr3yVWMlM2fWjPyWK_fs,23614
|
| 52 |
+
huggingface_hub/cli/cache.py,sha256=-qVQOQE5eNYHMdaO72sOmmyLw3E1IpIVlBlHQapclLo,32968
|
| 53 |
+
huggingface_hub/cli/collections.py,sha256=Ed41zJqrvK-AWkHdkeHWm_aJKR_ZeNIovCGvWG04itk,10120
|
| 54 |
+
huggingface_hub/cli/datasets.py,sha256=X1xMJTFhHH5NJtmjTS6NN1g4ffai6Abh_obDEJM5mvo,10497
|
| 55 |
+
huggingface_hub/cli/discussions.py,sha256=szO0j0B1Uj3kGJTnaE5zlUZG1N0ofr0BpkWOhJveGLM,16961
|
| 56 |
+
huggingface_hub/cli/download.py,sha256=jMk5JzOaUy0zR3_ZQNvZ_cJsG0bKqIUn-FTlwdJfN9s,9871
|
| 57 |
+
huggingface_hub/cli/extensions.py,sha256=YOXIEim06M84xedZFzoJyGFFQRPf416lfGtPkxZ3oi0,34000
|
| 58 |
+
huggingface_hub/cli/hf.py,sha256=i4cWibNWtUPPICsa68RUXr37T0i46zjgsOSX_TwRSGY,5983
|
| 59 |
+
huggingface_hub/cli/inference_endpoints.py,sha256=SEo7IG4G77j2NMyAkZmmOsrEtPmxtvUT9Nbpadaspog,33789
|
| 60 |
+
huggingface_hub/cli/jobs.py,sha256=mn13QE5aC48pouRLRli7N-ywN94l5kZapMT-wd9inqY,83074
|
| 61 |
+
huggingface_hub/cli/lfs.py,sha256=MAccazVPX0n-ySRaPocaQUHP7oBnVrvWZt0RhmNIavs,5936
|
| 62 |
+
huggingface_hub/cli/models.py,sha256=fyTNJtwt-2KakLTdwqKd0AOmnL8i92tESKqhLJuGLJg,10185
|
| 63 |
+
huggingface_hub/cli/papers.py,sha256=HvT-8zj2fi14ua6awWpHphlbJ362FEJIwSCBJRQZ_cM,4982
|
| 64 |
+
huggingface_hub/cli/repos.py,sha256=Jzki8qknLm-G6LHwlf8Fsj9IKx6i68r03EfOav-yJeg,20163
|
| 65 |
+
huggingface_hub/cli/sandbox.py,sha256=l3ZgwB13RowssIHBc_TppQO_heP5jcluqMGCitmcfvQ,18944
|
| 66 |
+
huggingface_hub/cli/skills.py,sha256=phrA52KaquPmWeIMAaG1f_iNqZgDiFKn9X5obkR_HJ4,20467
|
| 67 |
+
huggingface_hub/cli/spaces.py,sha256=RO0CRRIyDhCgfky5Oceu0C74xJSnvhJaURNjlYkwe3c,42011
|
| 68 |
+
huggingface_hub/cli/system.py,sha256=cB2GFlV9si0HbmUkyoj5nAKZf-vWpf9gi9XAq51s05Y,3850
|
| 69 |
+
huggingface_hub/cli/upload.py,sha256=ZcPnxkUB8Rk5EJlfXiUU5fD7oGc_6CwCOCa22M4XIEI,12181
|
| 70 |
+
huggingface_hub/cli/webhooks.py,sha256=wF10qGeCq2vJiyRrgqDYLEC8Lk0LMCTj0pL4PkFuMFQ,10372
|
| 71 |
+
huggingface_hub/community.py,sha256=RLlbbXs5P_84D8l9nKLPL0tudxZx-EN95oUCxgzGpvQ,12336
|
| 72 |
+
huggingface_hub/constants.py,sha256=jblN5u4rC9BKp2vQjjwv4r8hlnyJRv6mVUzXIT142eA,14112
|
| 73 |
+
huggingface_hub/dataclasses.py,sha256=WhbBsZEDwJdUgSMrlamBiY-1ghi5UMAkSFg5BGIbZt8,26285
|
| 74 |
+
huggingface_hub/errors.py,sha256=i31RI8q0ZHHKpB68pNsBJXHInVRtGFS2uSzvCf4Rb0c,19048
|
| 75 |
+
huggingface_hub/fastai_utils.py,sha256=jwKeVXH_VP0zxnOKVNQCVCkF-stH70l-bExbbrYkBKQ,16583
|
| 76 |
+
huggingface_hub/file_download.py,sha256=E1CHMc294DR0Ihn97jXOoIYO2FUZcoRWQW47EQPv6wI,94625
|
| 77 |
+
huggingface_hub/hf_api.py,sha256=OHH2UW8r-Xt3z0F52uqSmzC0yX1-h-kVj6dC9Gy_SGA,696491
|
| 78 |
+
huggingface_hub/hf_file_system.py,sha256=vIKEJmK2Fw-_pmXlgoTdBGhEuAeTSliqeuj58CxNzug,81290
|
| 79 |
+
huggingface_hub/hub_mixin.py,sha256=ygXdyZ9re7BGOTwn9nlr7j-ae1q6z3zgUPIaLhGL3Xo,36720
|
| 80 |
+
huggingface_hub/inference/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 81 |
+
huggingface_hub/inference/_client.py,sha256=VoBGCpaG9E7ARZu0NTdyS7frzLItdOdKMyb0bz7cElQ,156165
|
| 82 |
+
huggingface_hub/inference/_common.py,sha256=0I7-ogOUmW3Rnp-mJ5kCGOPuP5VrQLayrgdUZvmI3_c,15011
|
| 83 |
+
huggingface_hub/inference/_generated/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 84 |
+
huggingface_hub/inference/_generated/_async_client.py,sha256=xlNdEvqV_VrPmq03ov43x5QE06RShaC0lfDEBn2hp_M,159526
|
| 85 |
+
huggingface_hub/inference/_generated/types/__init__.py,sha256=e625ENOmTUM4uUL1eAlsZOK7CovNoGBDH-TxSNQhaC4,6869
|
| 86 |
+
huggingface_hub/inference/_generated/types/audio_classification.py,sha256=DGWEvrRPX7xpXlbYY4LMojGcULdEZFTshhNR81rTNcQ,1567
|
| 87 |
+
huggingface_hub/inference/_generated/types/audio_to_audio.py,sha256=2Ep4WkePL7oJwcp5nRJqApwviumGHbft9HhXE9XLHj4,891
|
| 88 |
+
huggingface_hub/inference/_generated/types/automatic_speech_recognition.py,sha256=X0uCj9qwAcOmlKtV3vWH5cAgLGY0PuYIy2eSH7GE1qs,5439
|
| 89 |
+
huggingface_hub/inference/_generated/types/base.py,sha256=EPWp1qudjeEimEAyQ-ptdxpAACoRM8tW342-Ds7pP3I,6938
|
| 90 |
+
huggingface_hub/inference/_generated/types/chat_completion.py,sha256=3yc06ZI0NCZzsaeoxSMWyIHqGc8Vn_6aExncuXa1llE,11100
|
| 91 |
+
huggingface_hub/inference/_generated/types/depth_estimation.py,sha256=5Kn4xNGJg235Cofr1lzO59eRGCuLTZun8z5t6a2do8Q,910
|
| 92 |
+
huggingface_hub/inference/_generated/types/document_question_answering.py,sha256=aUZcrDGexjw8Fnm2rACm_3my77V15NnQHZxj-sa7bjo,3146
|
| 93 |
+
huggingface_hub/inference/_generated/types/feature_extraction.py,sha256=DiO47PqwhdNta_KPDBsXfCPIL6BWNhyCLymxORlqUA0,1509
|
| 94 |
+
huggingface_hub/inference/_generated/types/fill_mask.py,sha256=NhEskgoiMst7U_0cV_S-wryga4_2T5LgpbyQ23vHMp0,1680
|
| 95 |
+
huggingface_hub/inference/_generated/types/image_classification.py,sha256=xWr4OY65EcIIhd7MI610a7xlaAVHQeydi8Gc7tlaPTU,1579
|
| 96 |
+
huggingface_hub/inference/_generated/types/image_segmentation.py,sha256=lZKzbn_gkSi1sYGLb9ryeRr0aDAVrfYh0H5Iiv5JNsY,1935
|
| 97 |
+
huggingface_hub/inference/_generated/types/image_text_to_image.py,sha256=pRQgYKXJbIpEjRBxuIE6NRDtk_km9DSTQ2s2qxkYJRM,2585
|
| 98 |
+
huggingface_hub/inference/_generated/types/image_text_to_video.py,sha256=MVhP8D4eYjpT3hWYkkpuiME-hWY09o7C4rIn_wmnAmY,2450
|
| 99 |
+
huggingface_hub/inference/_generated/types/image_to_image.py,sha256=P9TeMFSnZI_pa6DyinzDPWL0PNm_INJwsqFUEzpwIcU,2262
|
| 100 |
+
huggingface_hub/inference/_generated/types/image_to_text.py,sha256=DCDS0Nqi-4AuATitvZm4EgrzYQuQEQ5lzBcaHuCmHnY,4740
|
| 101 |
+
huggingface_hub/inference/_generated/types/image_to_video.py,sha256=iMCjiFTUza9AW_MyJ1videhYgvMY9QSzQ59kNdTE9QY,2206
|
| 102 |
+
huggingface_hub/inference/_generated/types/object_detection.py,sha256=zNILlyZJh59rNNfqXM5x9uprDCPfEU-bvBtabeKSMzI,1965
|
| 103 |
+
huggingface_hub/inference/_generated/types/question_answering.py,sha256=lIRf8DjRiAsjzWUBEsGt354SB4bvejLokf-8luHw6_o,2845
|
| 104 |
+
huggingface_hub/inference/_generated/types/sentence_similarity.py,sha256=eNGiO4dR-Lft9yOLE0E97jfVyOT_ExDWZW5GeJGdatU,1027
|
| 105 |
+
huggingface_hub/inference/_generated/types/summarization.py,sha256=5Dpt6LRteT-hO9esa3Ty_-xSL5U-zTtVZzy3iKwZRng,1472
|
| 106 |
+
huggingface_hub/inference/_generated/types/table_question_answering.py,sha256=bwn616XJ-eLa5JKzn3m9rZZ3z63INGEUwRSOCWlEh-4,2269
|
| 107 |
+
huggingface_hub/inference/_generated/types/text2text_generation.py,sha256=fotSlPWtIlp_LG26AQvNRXxU-jCUfda5PWsxCkbFeKM,1591
|
| 108 |
+
huggingface_hub/inference/_generated/types/text_classification.py,sha256=uamBzz4YzWQ9mb6yuriykX8r47ZHf0K3eJpOLzB2qJw,1439
|
| 109 |
+
huggingface_hub/inference/_generated/types/text_generation.py,sha256=FRUljypvCSQ2RaiylhlHeLJfHNy8qZvuty6SCB_zcaA,5813
|
| 110 |
+
huggingface_hub/inference/_generated/types/text_to_audio.py,sha256=CiaTUSBdFtOs3gGTosqyQrjCwrN8mVJLRxDDWUtwZpQ,4677
|
| 111 |
+
huggingface_hub/inference/_generated/types/text_to_image.py,sha256=Ju25WIDHE-1n8jlZ_udG4rpAaPYpmghR7-cDgVfuf48,1869
|
| 112 |
+
huggingface_hub/inference/_generated/types/text_to_speech.py,sha256=WqDzWkhZsDcjapkoFrkyjF903SKs7aHhjypsYrn8oBw,4693
|
| 113 |
+
huggingface_hub/inference/_generated/types/text_to_video.py,sha256=KjcDbtChwrIxIdTH6vcesUaMcjL2xjPf2nWEnHazj4Y,1756
|
| 114 |
+
huggingface_hub/inference/_generated/types/token_classification.py,sha256=8KRBlqgFDszaUnPMvdRkZNQaZBtDfBhKZ6SggQldQMM,1894
|
| 115 |
+
huggingface_hub/inference/_generated/types/translation.py,sha256=-j2PC1-qfoxvGMaKesqf5jXelqj0BDlEpfvZ7dsIEJM,1742
|
| 116 |
+
huggingface_hub/inference/_generated/types/video_classification.py,sha256=vfaCqp8MuRMMtGvYCX0x4-AcwEd71kPHgSYJTNIOxLQ,1668
|
| 117 |
+
huggingface_hub/inference/_generated/types/visual_question_answering.py,sha256=sWIB-SuEpW21oU6O5qQF3tt5PavUFsFOa8Xg4upTtek,1654
|
| 118 |
+
huggingface_hub/inference/_generated/types/zero_shot_classification.py,sha256=gx-7WHad7xsNa89iSKSteKHjaHrKbIyzN_nSdJN3HCY,1697
|
| 119 |
+
huggingface_hub/inference/_generated/types/zero_shot_image_classification.py,sha256=JZTQvcbSGrOQlWcPuJvAMT8YziDpBRn1O2RQSw507uY,1449
|
| 120 |
+
huggingface_hub/inference/_generated/types/zero_shot_object_detection.py,sha256=sjdpVUN5zW9aYBymLVUs6i5HVk2qkUBO9ysEjHmsXVM,1605
|
| 121 |
+
huggingface_hub/inference/_mcp/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 122 |
+
huggingface_hub/inference/_mcp/_cli_hacks.py,sha256=kIA8FfRfOWS3SrZrMTbuVOjE6yxfKfMK75Co5egTWHA,3284
|
| 123 |
+
huggingface_hub/inference/_mcp/agent.py,sha256=ufIzMGHore5n252hV5GZPM0ouDXIl6tv5Jl_5gHXnbg,4250
|
| 124 |
+
huggingface_hub/inference/_mcp/cli.py,sha256=RKdVQ_VdEgf1AL_QBCvwrsUQ0Ux4R1yerrE46DrV5C0,9642
|
| 125 |
+
huggingface_hub/inference/_mcp/constants.py,sha256=0Ih6ivEvG-pfF8NwErFngzP4Rof4lQoz6ms_eKSAkUI,2463
|
| 126 |
+
huggingface_hub/inference/_mcp/mcp_client.py,sha256=NxVSp_QZ2616AGi_ECrQKH5wvc1Y3j7qVfJrsUjQgmY,17480
|
| 127 |
+
huggingface_hub/inference/_mcp/types.py,sha256=yHNfPsM9MhD06oeKdkbmrBsW-3WhUeqA26fyfRfx_bk,929
|
| 128 |
+
huggingface_hub/inference/_mcp/utils.py,sha256=gxSB_rBjQ6VrkApKFsxk6-UzhijxkDVNuZrsjW5pL8k,4318
|
| 129 |
+
huggingface_hub/inference/_providers/__init__.py,sha256=fJ2JW4pBXzad2-Yn-q_DozE1PZBIs0pN-dAVFzCJotI,10165
|
| 130 |
+
huggingface_hub/inference/_providers/_common.py,sha256=T3iKT6McNs7GeVfK3q-l7CBbuih2mTFcqkRluQn7GnQ,14308
|
| 131 |
+
huggingface_hub/inference/_providers/baseten.py,sha256=1uucLZp6HiF8OjfeFOkiuJP6WqunP_xzwk3yWPF8vGE,213
|
| 132 |
+
huggingface_hub/inference/_providers/cerebras.py,sha256=QOJ-1U-os7uE7p6eUnn_P_APq-yQhx28be7c3Tq2EuA,210
|
| 133 |
+
huggingface_hub/inference/_providers/cohere.py,sha256=P9kbIuvQ2rXI1yNmgbw5VKFFTE0huLq2k-BCyDkDico,1226
|
| 134 |
+
huggingface_hub/inference/_providers/deepinfra.py,sha256=n8cI9Er-jMRuqBIlyoUQeVuWNJ5cBVNMQu7pwA0hVPA,6661
|
| 135 |
+
huggingface_hub/inference/_providers/fal_ai.py,sha256=XoH1I-3a3FEJF_IBa2FMAYTH4jv6JqRTgFRuo7HSH_Y,12124
|
| 136 |
+
huggingface_hub/inference/_providers/featherless_ai.py,sha256=C8OHdFpoFyA--pawLTekUmUSRq4sw_r0D-cSPekD4kE,1347
|
| 137 |
+
huggingface_hub/inference/_providers/fireworks_ai.py,sha256=go6XPum8u0-g768HJ_r0S4Gb445gZJxnuY_acktz-9c,1188
|
| 138 |
+
huggingface_hub/inference/_providers/groq.py,sha256=JTk2JV4ZOlaohho7zLAFQtk92kGVsPmLJ1hmzcwsqvQ,315
|
| 139 |
+
huggingface_hub/inference/_providers/hf_inference.py,sha256=r6igN2QqILikEm1rOYZLJib5VhKpzmgdMlo2VKctRVo,9328
|
| 140 |
+
huggingface_hub/inference/_providers/novita.py,sha256=ATEoSdPAPLMfx3JpBc0sOyLh4upJYP6xHBuo4YEDYvg,2470
|
| 141 |
+
huggingface_hub/inference/_providers/nscale.py,sha256=T1L2JLI9LqYT9_YEdW76YEtxfDNtdGkoFhH-p2LmSxg,1767
|
| 142 |
+
huggingface_hub/inference/_providers/openai.py,sha256=wwjaaQ55xLmDsDnHpZk52xbuLoGZfWzJkFsE8AdFVaI,1054
|
| 143 |
+
huggingface_hub/inference/_providers/ovhcloud.py,sha256=tdmymlkbddMJKV7NRZ-tH2wymbLPFDTqUSXpWJUXyDQ,314
|
| 144 |
+
huggingface_hub/inference/_providers/publicai.py,sha256=1I2W6rORloB5QHSvky4njZO2XKLTwA-kPdNoauoT5rg,210
|
| 145 |
+
huggingface_hub/inference/_providers/replicate.py,sha256=hte0ZB2RtGFwpAuLrFp2Gbgsn3EOlccCnJkWTDTW__A,6027
|
| 146 |
+
huggingface_hub/inference/_providers/scaleway.py,sha256=MfIc7ZND1sPr__rOmNHZVg0VpECQo0bVyksgIm_32xQ,1174
|
| 147 |
+
huggingface_hub/inference/_providers/together.py,sha256=lrymDZ86n5yoR_Zz7o3AzzSePyo0s7BOBU5digLxb5o,12220
|
| 148 |
+
huggingface_hub/inference/_providers/wavespeed.py,sha256=MGM7Y7r2nQiH_EH0t5UE1o1fT-o3sS7RaQlicS9WHsg,5028
|
| 149 |
+
huggingface_hub/inference/_providers/zai_org.py,sha256=gLJZOEmCPmUZvdM7VDn2nxm4ac3veHdoMgQNR63UeWE,4739
|
| 150 |
+
huggingface_hub/lfs.py,sha256=8ymYNHRXgvgUUM9w0EAnC-vkSOOq_1EFJEJNoevoeE8,16588
|
| 151 |
+
huggingface_hub/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 152 |
+
huggingface_hub/repocard.py,sha256=R6PyVw6D46Ywl04JPqFB4ealMYR0EfUqm8x8PTpBRzU,35657
|
| 153 |
+
huggingface_hub/repocard_data.py,sha256=txcJRf-dVg_h9LN0Lrx45-c9GV1s9q930PzrpJbFhs4,34476
|
| 154 |
+
huggingface_hub/serialization/__init__.py,sha256=jCiw_vVQYW52gwVfWiqgocf2Q19kGTQlRGVpf-4SLP8,963
|
| 155 |
+
huggingface_hub/serialization/_base.py,sha256=JWIAmCAjiINVvwszYKeaHXUCK4CsOW-_ELIH2Yuax3A,8397
|
| 156 |
+
huggingface_hub/serialization/_dduf.py,sha256=FmGRg5wkXI5sNCgZgCNJFmqb_nVrrQYOHf4Lqq0d64I,15385
|
| 157 |
+
huggingface_hub/serialization/_torch.py,sha256=q09EfkS8UW5FiFTj3u9gpnJKL9zmBwQyoNxHViLX2K4,55811
|
| 158 |
+
huggingface_hub/templates/datasetcard_template.md,sha256=W-EMqR6wndbrnZorkVv56URWPG49l7MATGeI015kTvs,5503
|
| 159 |
+
huggingface_hub/templates/modelcard_template.md,sha256=4AqArS3cqdtbit5Bo-DhjcnDFR-pza5hErLLTPM4Yuc,6870
|
| 160 |
+
huggingface_hub/utils/__init__.py,sha256=qQOiNOpD9UBbAzk43esrEgGECr1OAMMDZgBWDPxsCIY,13293
|
| 161 |
+
huggingface_hub/utils/_auth.py,sha256=j0P_kjWjtx4CF8bTQ1TSzpcZyq_OcS_5WeNXtbj6mCU,20355
|
| 162 |
+
huggingface_hub/utils/_cache_assets.py,sha256=nnzHRtQAR50dQeIK6qKddsmjjTW9v9HZ7b9bq7PJqss,5691
|
| 163 |
+
huggingface_hub/utils/_cache_manager.py,sha256=WjQ-GyqveTPSCSVfZI0eTlO40S-cxEomqI61ZTNP63o,42254
|
| 164 |
+
huggingface_hub/utils/_chunk_utils.py,sha256=mR0sYTfe1Fa1c-8jChIscheNW5vcwMULsP4AV3rTSqk,2127
|
| 165 |
+
huggingface_hub/utils/_datetime.py,sha256=tbNyI0Dkh27oScPUtLIT_8apqIIkXZYbigjOn9S3aMw,2755
|
| 166 |
+
huggingface_hub/utils/_deprecation.py,sha256=n4kNHbGipquSObJ-gxodcfd6lqoe_8s-VIsTuo3Oruk,4865
|
| 167 |
+
huggingface_hub/utils/_detect_agent.py,sha256=Iw2KW9BUZWfIypn9CtiTmEibHwKK9xx5Ar48z1cMU-Q,7337
|
| 168 |
+
huggingface_hub/utils/_dotenv.py,sha256=uy9Y6Y_C4-tHelJ_IwfOZ5jr7xvbgPP9g5kQ_Xd3Sck,3279
|
| 169 |
+
huggingface_hub/utils/_experimental.py,sha256=q9vUvc1JybVFRQ0GRREG-BLouZEJC_40MxcwbAlOud0,2464
|
| 170 |
+
huggingface_hub/utils/_fixes.py,sha256=jTK1VLmc0ZC9ROSXjKoL5F6kOZFByzirRWIdXxhBfWU,4124
|
| 171 |
+
huggingface_hub/utils/_git_credential.py,sha256=1BhjvIScCOAToDORLOKrR3Szs-m0E5AYHPmC0SD7Nrs,4548
|
| 172 |
+
huggingface_hub/utils/_headers.py,sha256=Q9bu9mvOpm-9rfv-YRlr_Ywy_aMZkmRcN3MbVEcJAJA,8234
|
| 173 |
+
huggingface_hub/utils/_hf_uris.py,sha256=6lQUCBmPa9vqSVXsWORY88CxLKjWReMOOoDvup02ZHM,27559
|
| 174 |
+
huggingface_hub/utils/_http.py,sha256=S9BjQeUjMpa7cPhWIY2Oy-AT84RdqgePzQEmjYDSpsk,49263
|
| 175 |
+
huggingface_hub/utils/_lfs.py,sha256=LwCh0cU0B1UpGMVzDL0QMR6v_u3H6gmCbVbnCO_j0UQ,3974
|
| 176 |
+
huggingface_hub/utils/_oauth_device.py,sha256=lnaqrfd-RiE5onwdcEowbmtPLjIYkGI_myt3G9jylhg,7988
|
| 177 |
+
huggingface_hub/utils/_pagination.py,sha256=6leRcDjWS_soxoT0acGir_bM_ojVLIFshgZ2NnCzWGo,2790
|
| 178 |
+
huggingface_hub/utils/_parsing.py,sha256=rV7ygUnWsTCukZ11Z2WHHD4Tgv2duk3wbY9V3VmoDuA,3664
|
| 179 |
+
huggingface_hub/utils/_paths.py,sha256=rhDTSYVRYuEzuMck1-isQ2VB5ZUHyuBcSOLNuAtc7EM,7375
|
| 180 |
+
huggingface_hub/utils/_runtime.py,sha256=vmatlg8IOfnAADS4ylrVSqhApgO7kfEE9tG5RHLKS7o,13778
|
| 181 |
+
huggingface_hub/utils/_safetensors.py,sha256=-8Ak60JNGEnEnepzQdZtGVTm6zJUQOJyhvXjSBqUphc,4438
|
| 182 |
+
huggingface_hub/utils/_shared_blobs.py,sha256=ACd76RULXEJop2dfb1rovyd8tQF09ooMI6cnZNukBV8,23954
|
| 183 |
+
huggingface_hub/utils/_subprocess.py,sha256=vhy03frJVXIinHe25JxCwE3FmruonX4TOJIJogk8Hls,4536
|
| 184 |
+
huggingface_hub/utils/_telemetry.py,sha256=Tpa3YmOLhK_MEnL2i2fRLQy8aqAEZWbj6MKC18Hs8BA,4824
|
| 185 |
+
huggingface_hub/utils/_terminal.py,sha256=snvsBJL_X1KfszkCFECyh69xdmlOLalZ8_ErWTUdXss,9252
|
| 186 |
+
huggingface_hub/utils/_typing.py,sha256=1LeE785YedppXSR9a1fQDu5rhTxX5v9kBYBaHrP65rA,3542
|
| 187 |
+
huggingface_hub/utils/_validators.py,sha256=vTtNeF5i2qJ_FLpJzi_xrcEdAJFgB9Jm-c3RuMFtmPM,8590
|
| 188 |
+
huggingface_hub/utils/_verification.py,sha256=Zhe2IjufSaX3YWTu59b_3iPd7NEUgppvGI64kqqlwx8,5799
|
| 189 |
+
huggingface_hub/utils/_xet.py,sha256=gKJMQ_hvTJBE9K_dHY9QUw_p0H9_wdzEWsuxVZqALmg,12486
|
| 190 |
+
huggingface_hub/utils/_xet_progress_reporting.py,sha256=6icC9DdyNFNkAyBghKa-7LWBGfR068lzNmEkib9pAb8,17761
|
| 191 |
+
huggingface_hub/utils/endpoint_helpers.py,sha256=9VtIAlxQ5H_4y30sjCAgbu7XCqAtNLC7aRYxaNn0hLI,2366
|
| 192 |
+
huggingface_hub/utils/insecure_hashlib.py,sha256=z3dVUFvdBZ8kQI_8Vzvvlr3ims-EBiY-SYPdnzIKOkw,1008
|
| 193 |
+
huggingface_hub/utils/logging.py,sha256=jiP1dcKOe3764BN4fql0YEL7PPpmehuKNlIg-slS2gM,4876
|
| 194 |
+
huggingface_hub/utils/sha.py,sha256=h8wxheZpcv671RhtiIFcFmQTDSrogN3kwQx3ZaNEUHg,2121
|
| 195 |
+
huggingface_hub/utils/tqdm.py,sha256=4HqSH1PinYmDutJXdBem8bNctsH_aIrAu7-A7RRDDGw,16725
|
.venv/lib/python3.12/site-packages/huggingface_hub-2.4.0.dist-info/REQUESTED
ADDED
|
File without changes
|
.venv/lib/python3.12/site-packages/huggingface_hub-2.4.0.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: setuptools (84.2.1)
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
| 5 |
+
|
.venv/lib/python3.12/site-packages/huggingface_hub-2.4.0.dist-info/entry_points.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[console_scripts]
|
| 2 |
+
hf = huggingface_hub.cli.hf:main
|
| 3 |
+
tiny-agents = huggingface_hub.inference._mcp.cli:app
|
| 4 |
+
|
| 5 |
+
[fsspec.specs]
|
| 6 |
+
hf = huggingface_hub.HfFileSystem
|
.venv/lib/python3.12/site-packages/huggingface_hub-2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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Apache License
|
| 2 |
+
Version 2.0, January 2004
|
| 3 |
+
http://www.apache.org/licenses/
|
| 4 |
+
|
| 5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 6 |
+
|
| 7 |
+
1. Definitions.
|
| 8 |
+
|
| 9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 11 |
+
|
| 12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 13 |
+
the copyright owner that is granting the License.
|
| 14 |
+
|
| 15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 16 |
+
other entities that control, are controlled by, or are under common
|
| 17 |
+
control with that entity. For the purposes of this definition,
|
| 18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 19 |
+
direction or management of such entity, whether by contract or
|
| 20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 22 |
+
|
| 23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 24 |
+
exercising permissions granted by this License.
|
| 25 |
+
|
| 26 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 27 |
+
including but not limited to software source code, documentation
|
| 28 |
+
source, and configuration files.
|
| 29 |
+
|
| 30 |
+
"Object" form shall mean any form resulting from mechanical
|
| 31 |
+
transformation or translation of a Source form, including but
|
| 32 |
+
not limited to compiled object code, generated documentation,
|
| 33 |
+
and conversions to other media types.
|
| 34 |
+
|
| 35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 36 |
+
Object form, made available under the License, as indicated by a
|
| 37 |
+
copyright notice that is included in or attached to the work
|
| 38 |
+
(an example is provided in the Appendix below).
|
| 39 |
+
|
| 40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 41 |
+
form, that is based on (or derived from) the Work and for which the
|
| 42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 44 |
+
of this License, Derivative Works shall not include works that remain
|
| 45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 46 |
+
the Work and Derivative Works thereof.
|
| 47 |
+
|
| 48 |
+
"Contribution" shall mean any work of authorship, including
|
| 49 |
+
the original version of the Work and any modifications or additions
|
| 50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 54 |
+
means any form of electronic, verbal, or written communication sent
|
| 55 |
+
to the Licensor or its representatives, including but not limited to
|
| 56 |
+
communication on electronic mailing lists, source code control systems,
|
| 57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 59 |
+
excluding communication that is conspicuously marked or otherwise
|
| 60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 61 |
+
|
| 62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 64 |
+
subsequently incorporated within the Work.
|
| 65 |
+
|
| 66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 71 |
+
Work and such Derivative Works in Source or Object form.
|
| 72 |
+
|
| 73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 76 |
+
(except as stated in this section) patent license to make, have made,
|
| 77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 78 |
+
where such license applies only to those patent claims licensable
|
| 79 |
+
by such Contributor that are necessarily infringed by their
|
| 80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 82 |
+
institute patent litigation against any entity (including a
|
| 83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 84 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 85 |
+
or contributory patent infringement, then any patent licenses
|
| 86 |
+
granted to You under this License for that Work shall terminate
|
| 87 |
+
as of the date such litigation is filed.
|
| 88 |
+
|
| 89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 90 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 91 |
+
modifications, and in Source or Object form, provided that You
|
| 92 |
+
meet the following conditions:
|
| 93 |
+
|
| 94 |
+
(a) You must give any other recipients of the Work or
|
| 95 |
+
Derivative Works a copy of this License; and
|
| 96 |
+
|
| 97 |
+
(b) You must cause any modified files to carry prominent notices
|
| 98 |
+
stating that You changed the files; and
|
| 99 |
+
|
| 100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 101 |
+
that You distribute, all copyright, patent, trademark, and
|
| 102 |
+
attribution notices from the Source form of the Work,
|
| 103 |
+
excluding those notices that do not pertain to any part of
|
| 104 |
+
the Derivative Works; and
|
| 105 |
+
|
| 106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 107 |
+
distribution, then any Derivative Works that You distribute must
|
| 108 |
+
include a readable copy of the attribution notices contained
|
| 109 |
+
within such NOTICE file, excluding those notices that do not
|
| 110 |
+
pertain to any part of the Derivative Works, in at least one
|
| 111 |
+
of the following places: within a NOTICE text file distributed
|
| 112 |
+
as part of the Derivative Works; within the Source form or
|
| 113 |
+
documentation, if provided along with the Derivative Works; or,
|
| 114 |
+
within a display generated by the Derivative Works, if and
|
| 115 |
+
wherever such third-party notices normally appear. The contents
|
| 116 |
+
of the NOTICE file are for informational purposes only and
|
| 117 |
+
do not modify the License. You may add Your own attribution
|
| 118 |
+
notices within Derivative Works that You distribute, alongside
|
| 119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 120 |
+
that such additional attribution notices cannot be construed
|
| 121 |
+
as modifying the License.
|
| 122 |
+
|
| 123 |
+
You may add Your own copyright statement to Your modifications and
|
| 124 |
+
may provide additional or different license terms and conditions
|
| 125 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 126 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 127 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 128 |
+
the conditions stated in this License.
|
| 129 |
+
|
| 130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 132 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 133 |
+
this License, without any additional terms or conditions.
|
| 134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 135 |
+
the terms of any separate license agreement you may have executed
|
| 136 |
+
with Licensor regarding such Contributions.
|
| 137 |
+
|
| 138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 140 |
+
except as required for reasonable and customary use in describing the
|
| 141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 142 |
+
|
| 143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 144 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 147 |
+
implied, including, without limitation, any warranties or conditions
|
| 148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 150 |
+
appropriateness of using or redistributing the Work and assume any
|
| 151 |
+
risks associated with Your exercise of permissions under this License.
|
| 152 |
+
|
| 153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 154 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 155 |
+
unless required by applicable law (such as deliberate and grossly
|
| 156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 157 |
+
liable to You for damages, including any direct, indirect, special,
|
| 158 |
+
incidental, or consequential damages of any character arising as a
|
| 159 |
+
result of this License or out of the use or inability to use the
|
| 160 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 161 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 162 |
+
other commercial damages or losses), even if such Contributor
|
| 163 |
+
has been advised of the possibility of such damages.
|
| 164 |
+
|
| 165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 168 |
+
or other liability obligations and/or rights consistent with this
|
| 169 |
+
License. However, in accepting such obligations, You may act only
|
| 170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 171 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 172 |
+
defend, and hold each Contributor harmless for any liability
|
| 173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 174 |
+
of your accepting any such warranty or additional liability.
|
| 175 |
+
|
| 176 |
+
END OF TERMS AND CONDITIONS
|
| 177 |
+
|
| 178 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 179 |
+
|
| 180 |
+
To apply the Apache License to your work, attach the following
|
| 181 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 182 |
+
replaced with your own identifying information. (Don't include
|
| 183 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 184 |
+
comment syntax for the file format. We also recommend that a
|
| 185 |
+
file or class name and description of purpose be included on the
|
| 186 |
+
same "printed page" as the copyright notice for easier
|
| 187 |
+
identification within third-party archives.
|
| 188 |
+
|
| 189 |
+
Copyright [yyyy] [name of copyright owner]
|
| 190 |
+
|
| 191 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 192 |
+
you may not use this file except in compliance with the License.
|
| 193 |
+
You may obtain a copy of the License at
|
| 194 |
+
|
| 195 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 196 |
+
|
| 197 |
+
Unless required by applicable law or agreed to in writing, software
|
| 198 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 199 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 200 |
+
See the License for the specific language governing permissions and
|
| 201 |
+
limitations under the License.
|
.venv/lib/python3.12/site-packages/huggingface_hub-2.4.0.dist-info/top_level.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
huggingface_hub
|
.venv/lib/python3.12/site-packages/huggingface_hub/__init__.py
ADDED
|
@@ -0,0 +1,1849 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# ***********
|
| 16 |
+
# `huggingface_hub` init has 2 modes:
|
| 17 |
+
# - Normal usage:
|
| 18 |
+
# If imported to use it, all modules and functions are lazy-loaded. This means
|
| 19 |
+
# they exist at top level in module but are imported only the first time they are
|
| 20 |
+
# used. This way, `from huggingface_hub import something` will import `something`
|
| 21 |
+
# quickly without the hassle of importing all the features from `huggingface_hub`.
|
| 22 |
+
# - Static check:
|
| 23 |
+
# If statically analyzed, all modules and functions are loaded normally. This way
|
| 24 |
+
# static typing check works properly as well as autocomplete in text editors and
|
| 25 |
+
# IDEs.
|
| 26 |
+
#
|
| 27 |
+
# The static model imports are done inside the `if TYPE_CHECKING:` statement at
|
| 28 |
+
# the bottom of this file. Since module/functions imports are duplicated, it is
|
| 29 |
+
# mandatory to make sure to add them twice when adding one. This is checked in the
|
| 30 |
+
# `make quality` command.
|
| 31 |
+
#
|
| 32 |
+
# To update the static imports, please run the following command and commit the changes.
|
| 33 |
+
# ```
|
| 34 |
+
# # Use script
|
| 35 |
+
# python utils/check_static_imports.py --update-file
|
| 36 |
+
#
|
| 37 |
+
# # Or run style on codebase
|
| 38 |
+
# make style
|
| 39 |
+
# ```
|
| 40 |
+
#
|
| 41 |
+
# ***********
|
| 42 |
+
# Lazy loader vendored from https://github.com/scientific-python/lazy_loader
|
| 43 |
+
import importlib
|
| 44 |
+
import os
|
| 45 |
+
import sys
|
| 46 |
+
from typing import TYPE_CHECKING
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
__version__ = "2.4.0"
|
| 50 |
+
|
| 51 |
+
# Alphabetical order of definitions is ensured in tests
|
| 52 |
+
# WARNING: any comment added in this dictionary definition will be lost when
|
| 53 |
+
# re-generating the file !
|
| 54 |
+
_SUBMOD_ATTRS = {
|
| 55 |
+
"_buckets": [
|
| 56 |
+
"BucketFile",
|
| 57 |
+
"BucketFileMetadata",
|
| 58 |
+
"BucketFolder",
|
| 59 |
+
"BucketInfo",
|
| 60 |
+
"BucketUrl",
|
| 61 |
+
"SyncOperation",
|
| 62 |
+
"SyncPlan",
|
| 63 |
+
],
|
| 64 |
+
"_commit_api": [
|
| 65 |
+
"CommitOperation",
|
| 66 |
+
"CommitOperationAdd",
|
| 67 |
+
"CommitOperationCopy",
|
| 68 |
+
"CommitOperationDelete",
|
| 69 |
+
],
|
| 70 |
+
"_commit_scheduler": [
|
| 71 |
+
"CommitScheduler",
|
| 72 |
+
],
|
| 73 |
+
"_eval_results": [
|
| 74 |
+
"EvalResultEntry",
|
| 75 |
+
"eval_result_entries_to_yaml",
|
| 76 |
+
"parse_eval_result_entries",
|
| 77 |
+
],
|
| 78 |
+
"_inference_endpoints": [
|
| 79 |
+
"InferenceCatalogModel",
|
| 80 |
+
"InferenceCatalogRecipe",
|
| 81 |
+
"InferenceEndpoint",
|
| 82 |
+
"InferenceEndpointError",
|
| 83 |
+
"InferenceEndpointHardware",
|
| 84 |
+
"InferenceEndpointStatus",
|
| 85 |
+
"InferenceEndpointTimeoutError",
|
| 86 |
+
"InferenceEndpointType",
|
| 87 |
+
],
|
| 88 |
+
"_jobs_api": [
|
| 89 |
+
"JobAccelerator",
|
| 90 |
+
"JobDurations",
|
| 91 |
+
"JobHardware",
|
| 92 |
+
"JobHardwareInfo",
|
| 93 |
+
"JobInfo",
|
| 94 |
+
"JobInitiator",
|
| 95 |
+
"JobNetwork",
|
| 96 |
+
"JobOwner",
|
| 97 |
+
"JobStage",
|
| 98 |
+
"JobStatus",
|
| 99 |
+
],
|
| 100 |
+
"_login": [
|
| 101 |
+
"auth_list",
|
| 102 |
+
"auth_switch",
|
| 103 |
+
"interpreter_login",
|
| 104 |
+
"login",
|
| 105 |
+
"logout",
|
| 106 |
+
"notebook_login",
|
| 107 |
+
],
|
| 108 |
+
"_oauth": [
|
| 109 |
+
"OAuthInfo",
|
| 110 |
+
"OAuthOrgInfo",
|
| 111 |
+
"OAuthUserInfo",
|
| 112 |
+
"attach_huggingface_oauth",
|
| 113 |
+
"parse_huggingface_oauth",
|
| 114 |
+
],
|
| 115 |
+
"_revision": [
|
| 116 |
+
"ResolvedRevision",
|
| 117 |
+
],
|
| 118 |
+
"_sandbox": [
|
| 119 |
+
"Sandbox",
|
| 120 |
+
"SandboxCommandResult",
|
| 121 |
+
"SandboxPool",
|
| 122 |
+
"SandboxProcess",
|
| 123 |
+
],
|
| 124 |
+
"_snapshot_download": [
|
| 125 |
+
"get_cached_repo_tree",
|
| 126 |
+
"snapshot_download",
|
| 127 |
+
],
|
| 128 |
+
"_space_api": [
|
| 129 |
+
"SpaceHardware",
|
| 130 |
+
"SpaceRuntime",
|
| 131 |
+
"SpaceSecret",
|
| 132 |
+
"SpaceStage",
|
| 133 |
+
"SpaceStorage",
|
| 134 |
+
"SpaceVariable",
|
| 135 |
+
"Volume",
|
| 136 |
+
"ZeroGpuQuota",
|
| 137 |
+
],
|
| 138 |
+
"_tensorboard_logger": [
|
| 139 |
+
"HFSummaryWriter",
|
| 140 |
+
],
|
| 141 |
+
"_webhooks_payload": [
|
| 142 |
+
"WebhookPayload",
|
| 143 |
+
"WebhookPayloadComment",
|
| 144 |
+
"WebhookPayloadDiscussion",
|
| 145 |
+
"WebhookPayloadDiscussionChanges",
|
| 146 |
+
"WebhookPayloadEvent",
|
| 147 |
+
"WebhookPayloadMovedTo",
|
| 148 |
+
"WebhookPayloadRepo",
|
| 149 |
+
"WebhookPayloadUrl",
|
| 150 |
+
"WebhookPayloadWebhook",
|
| 151 |
+
],
|
| 152 |
+
"_webhooks_server": [
|
| 153 |
+
"WebhooksServer",
|
| 154 |
+
"webhook_endpoint",
|
| 155 |
+
],
|
| 156 |
+
"cli._cli_utils": [
|
| 157 |
+
"check_cli_update",
|
| 158 |
+
"typer_factory",
|
| 159 |
+
],
|
| 160 |
+
"community": [
|
| 161 |
+
"Discussion",
|
| 162 |
+
"DiscussionComment",
|
| 163 |
+
"DiscussionCommit",
|
| 164 |
+
"DiscussionEvent",
|
| 165 |
+
"DiscussionStatusChange",
|
| 166 |
+
"DiscussionTitleChange",
|
| 167 |
+
"DiscussionWithDetails",
|
| 168 |
+
],
|
| 169 |
+
"constants": [
|
| 170 |
+
"CONFIG_NAME",
|
| 171 |
+
"FLAX_WEIGHTS_NAME",
|
| 172 |
+
"HUGGINGFACE_CO_URL_HOME",
|
| 173 |
+
"HUGGINGFACE_CO_URL_TEMPLATE",
|
| 174 |
+
"PYTORCH_WEIGHTS_NAME",
|
| 175 |
+
"REPO_TYPE_DATASET",
|
| 176 |
+
"REPO_TYPE_MODEL",
|
| 177 |
+
"REPO_TYPE_SPACE",
|
| 178 |
+
"TF2_WEIGHTS_NAME",
|
| 179 |
+
"TF_WEIGHTS_NAME",
|
| 180 |
+
"is_offline_mode",
|
| 181 |
+
],
|
| 182 |
+
"fastai_utils": [
|
| 183 |
+
"_save_pretrained_fastai",
|
| 184 |
+
"from_pretrained_fastai",
|
| 185 |
+
"push_to_hub_fastai",
|
| 186 |
+
],
|
| 187 |
+
"file_download": [
|
| 188 |
+
"DryRunFileInfo",
|
| 189 |
+
"HfFileMetadata",
|
| 190 |
+
"_CACHED_NO_EXIST",
|
| 191 |
+
"get_hf_file_metadata",
|
| 192 |
+
"hf_hub_download",
|
| 193 |
+
"hf_hub_url",
|
| 194 |
+
"try_to_load_from_cache",
|
| 195 |
+
],
|
| 196 |
+
"hf_api": [
|
| 197 |
+
"Collection",
|
| 198 |
+
"CollectionItem",
|
| 199 |
+
"CommitInfo",
|
| 200 |
+
"DatasetInfo",
|
| 201 |
+
"DatasetLeaderboardEntry",
|
| 202 |
+
"DuplicatedRepoUrl",
|
| 203 |
+
"GitCommitInfo",
|
| 204 |
+
"GitRefInfo",
|
| 205 |
+
"GitRefs",
|
| 206 |
+
"HfApi",
|
| 207 |
+
"KernelInfo",
|
| 208 |
+
"ModelInfo",
|
| 209 |
+
"Organization",
|
| 210 |
+
"RepoFile",
|
| 211 |
+
"RepoFolder",
|
| 212 |
+
"RepoStorageInfo",
|
| 213 |
+
"RepoUrl",
|
| 214 |
+
"SpaceInfo",
|
| 215 |
+
"SpaceSearchResult",
|
| 216 |
+
"SpaceTemplate",
|
| 217 |
+
"User",
|
| 218 |
+
"UserLikes",
|
| 219 |
+
"WebhookInfo",
|
| 220 |
+
"WebhookWatchedItem",
|
| 221 |
+
"accept_access_request",
|
| 222 |
+
"add_collection_item",
|
| 223 |
+
"add_space_secret",
|
| 224 |
+
"add_space_variable",
|
| 225 |
+
"auth_check",
|
| 226 |
+
"batch_bucket_files",
|
| 227 |
+
"bucket_info",
|
| 228 |
+
"cancel_access_request",
|
| 229 |
+
"cancel_job",
|
| 230 |
+
"change_discussion_status",
|
| 231 |
+
"comment_discussion",
|
| 232 |
+
"copy_files",
|
| 233 |
+
"create_branch",
|
| 234 |
+
"create_bucket",
|
| 235 |
+
"create_collection",
|
| 236 |
+
"create_commit",
|
| 237 |
+
"create_discussion",
|
| 238 |
+
"create_inference_endpoint",
|
| 239 |
+
"create_inference_endpoint_from_catalog",
|
| 240 |
+
"create_pull_request",
|
| 241 |
+
"create_repo",
|
| 242 |
+
"create_scheduled_job",
|
| 243 |
+
"create_scheduled_uv_job",
|
| 244 |
+
"create_tag",
|
| 245 |
+
"create_webhook",
|
| 246 |
+
"dataset_info",
|
| 247 |
+
"delete_branch",
|
| 248 |
+
"delete_bucket",
|
| 249 |
+
"delete_collection",
|
| 250 |
+
"delete_collection_item",
|
| 251 |
+
"delete_file",
|
| 252 |
+
"delete_folder",
|
| 253 |
+
"delete_inference_endpoint",
|
| 254 |
+
"delete_repo",
|
| 255 |
+
"delete_scheduled_job",
|
| 256 |
+
"delete_space_secret",
|
| 257 |
+
"delete_space_variable",
|
| 258 |
+
"delete_space_volumes",
|
| 259 |
+
"delete_tag",
|
| 260 |
+
"delete_webhook",
|
| 261 |
+
"disable_space_dev_mode",
|
| 262 |
+
"disable_webhook",
|
| 263 |
+
"download_bucket_files",
|
| 264 |
+
"duplicate_repo",
|
| 265 |
+
"edit_discussion_comment",
|
| 266 |
+
"enable_space_dev_mode",
|
| 267 |
+
"enable_webhook",
|
| 268 |
+
"fetch_job_logs",
|
| 269 |
+
"fetch_job_metrics",
|
| 270 |
+
"fetch_space_logs",
|
| 271 |
+
"file_exists",
|
| 272 |
+
"get_bucket_file_metadata",
|
| 273 |
+
"get_bucket_paths_info",
|
| 274 |
+
"get_collection",
|
| 275 |
+
"get_dataset_leaderboard",
|
| 276 |
+
"get_dataset_tags",
|
| 277 |
+
"get_discussion_details",
|
| 278 |
+
"get_full_repo_name",
|
| 279 |
+
"get_inference_endpoint",
|
| 280 |
+
"get_local_safetensors_metadata",
|
| 281 |
+
"get_model_tags",
|
| 282 |
+
"get_organization_overview",
|
| 283 |
+
"get_paths_info",
|
| 284 |
+
"get_repo_discussions",
|
| 285 |
+
"get_safetensors_metadata",
|
| 286 |
+
"get_sharded_safetensors_metadata",
|
| 287 |
+
"get_space_runtime",
|
| 288 |
+
"get_space_secrets",
|
| 289 |
+
"get_space_variables",
|
| 290 |
+
"get_user_overview",
|
| 291 |
+
"get_webhook",
|
| 292 |
+
"get_zero_gpu_quota",
|
| 293 |
+
"grant_access",
|
| 294 |
+
"inspect_job",
|
| 295 |
+
"inspect_scheduled_job",
|
| 296 |
+
"kernel_info",
|
| 297 |
+
"list_accepted_access_requests",
|
| 298 |
+
"list_bucket_tree",
|
| 299 |
+
"list_buckets",
|
| 300 |
+
"list_collections",
|
| 301 |
+
"list_daily_papers",
|
| 302 |
+
"list_dataset_parquet_files",
|
| 303 |
+
"list_datasets",
|
| 304 |
+
"list_inference_catalog",
|
| 305 |
+
"list_inference_endpoints",
|
| 306 |
+
"list_inference_endpoints_hardware",
|
| 307 |
+
"list_jobs",
|
| 308 |
+
"list_jobs_hardware",
|
| 309 |
+
"list_lfs_files",
|
| 310 |
+
"list_liked_repos",
|
| 311 |
+
"list_models",
|
| 312 |
+
"list_organization_followers",
|
| 313 |
+
"list_organization_members",
|
| 314 |
+
"list_papers",
|
| 315 |
+
"list_pending_access_requests",
|
| 316 |
+
"list_rejected_access_requests",
|
| 317 |
+
"list_repo_commits",
|
| 318 |
+
"list_repo_files",
|
| 319 |
+
"list_repo_likers",
|
| 320 |
+
"list_repo_refs",
|
| 321 |
+
"list_repo_tree",
|
| 322 |
+
"list_scheduled_jobs",
|
| 323 |
+
"list_space_templates",
|
| 324 |
+
"list_spaces",
|
| 325 |
+
"list_spaces_hardware",
|
| 326 |
+
"list_user_followers",
|
| 327 |
+
"list_user_following",
|
| 328 |
+
"list_user_repos",
|
| 329 |
+
"list_webhooks",
|
| 330 |
+
"merge_pull_request",
|
| 331 |
+
"model_info",
|
| 332 |
+
"move_bucket",
|
| 333 |
+
"move_repo",
|
| 334 |
+
"paper_info",
|
| 335 |
+
"parse_local_safetensors_file_metadata",
|
| 336 |
+
"parse_safetensors_file_metadata",
|
| 337 |
+
"pause_inference_endpoint",
|
| 338 |
+
"pause_space",
|
| 339 |
+
"permanently_delete_lfs_files",
|
| 340 |
+
"preupload_lfs_files",
|
| 341 |
+
"read_paper",
|
| 342 |
+
"reject_access_request",
|
| 343 |
+
"rename_discussion",
|
| 344 |
+
"repo_exists",
|
| 345 |
+
"repo_info",
|
| 346 |
+
"request_space_hardware",
|
| 347 |
+
"rerun_job",
|
| 348 |
+
"resolve_revision",
|
| 349 |
+
"restart_space",
|
| 350 |
+
"resume_inference_endpoint",
|
| 351 |
+
"resume_scheduled_job",
|
| 352 |
+
"revision_exists",
|
| 353 |
+
"run_as_future",
|
| 354 |
+
"run_job",
|
| 355 |
+
"run_uv_job",
|
| 356 |
+
"scale_to_zero_inference_endpoint",
|
| 357 |
+
"search_spaces",
|
| 358 |
+
"set_space_sleep_time",
|
| 359 |
+
"set_space_volumes",
|
| 360 |
+
"space_info",
|
| 361 |
+
"super_squash_history",
|
| 362 |
+
"suspend_scheduled_job",
|
| 363 |
+
"sync_bucket",
|
| 364 |
+
"sync_job_volume",
|
| 365 |
+
"trigger_scheduled_job",
|
| 366 |
+
"unlike",
|
| 367 |
+
"update_bucket_settings",
|
| 368 |
+
"update_collection_item",
|
| 369 |
+
"update_collection_metadata",
|
| 370 |
+
"update_collection_resource_group",
|
| 371 |
+
"update_inference_endpoint",
|
| 372 |
+
"update_job_expose",
|
| 373 |
+
"update_job_labels",
|
| 374 |
+
"update_repo_settings",
|
| 375 |
+
"update_scheduled_job_labels",
|
| 376 |
+
"update_scheduled_job_schedule",
|
| 377 |
+
"update_webhook",
|
| 378 |
+
"upload_attachment",
|
| 379 |
+
"upload_file",
|
| 380 |
+
"upload_folder",
|
| 381 |
+
"verify_repo_checksums",
|
| 382 |
+
"wait_for_job",
|
| 383 |
+
"wait_for_space",
|
| 384 |
+
"whoami",
|
| 385 |
+
],
|
| 386 |
+
"hf_file_system": [
|
| 387 |
+
"HfFileSystem",
|
| 388 |
+
"HfFileSystemFile",
|
| 389 |
+
"HfFileSystemResolvedPath",
|
| 390 |
+
"HfFileSystemStreamFile",
|
| 391 |
+
"hffs",
|
| 392 |
+
],
|
| 393 |
+
"hub_mixin": [
|
| 394 |
+
"ModelHubMixin",
|
| 395 |
+
"PyTorchModelHubMixin",
|
| 396 |
+
],
|
| 397 |
+
"inference._client": [
|
| 398 |
+
"InferenceClient",
|
| 399 |
+
"InferenceTimeoutError",
|
| 400 |
+
],
|
| 401 |
+
"inference._generated._async_client": [
|
| 402 |
+
"AsyncInferenceClient",
|
| 403 |
+
],
|
| 404 |
+
"inference._generated.types": [
|
| 405 |
+
"AudioClassificationInput",
|
| 406 |
+
"AudioClassificationOutputElement",
|
| 407 |
+
"AudioClassificationOutputTransform",
|
| 408 |
+
"AudioClassificationParameters",
|
| 409 |
+
"AudioToAudioInput",
|
| 410 |
+
"AudioToAudioOutputElement",
|
| 411 |
+
"AutomaticSpeechRecognitionEarlyStoppingEnum",
|
| 412 |
+
"AutomaticSpeechRecognitionGenerationParameters",
|
| 413 |
+
"AutomaticSpeechRecognitionInput",
|
| 414 |
+
"AutomaticSpeechRecognitionOutput",
|
| 415 |
+
"AutomaticSpeechRecognitionOutputChunk",
|
| 416 |
+
"AutomaticSpeechRecognitionParameters",
|
| 417 |
+
"ChatCompletionInput",
|
| 418 |
+
"ChatCompletionInputFunctionDefinition",
|
| 419 |
+
"ChatCompletionInputFunctionName",
|
| 420 |
+
"ChatCompletionInputGrammarType",
|
| 421 |
+
"ChatCompletionInputJSONSchema",
|
| 422 |
+
"ChatCompletionInputMessage",
|
| 423 |
+
"ChatCompletionInputMessageChunk",
|
| 424 |
+
"ChatCompletionInputMessageChunkType",
|
| 425 |
+
"ChatCompletionInputResponseFormatJSONObject",
|
| 426 |
+
"ChatCompletionInputResponseFormatJSONSchema",
|
| 427 |
+
"ChatCompletionInputResponseFormatText",
|
| 428 |
+
"ChatCompletionInputStreamOptions",
|
| 429 |
+
"ChatCompletionInputTool",
|
| 430 |
+
"ChatCompletionInputToolCall",
|
| 431 |
+
"ChatCompletionInputToolChoiceClass",
|
| 432 |
+
"ChatCompletionInputToolChoiceEnum",
|
| 433 |
+
"ChatCompletionInputURL",
|
| 434 |
+
"ChatCompletionOutput",
|
| 435 |
+
"ChatCompletionOutputComplete",
|
| 436 |
+
"ChatCompletionOutputFunctionDefinition",
|
| 437 |
+
"ChatCompletionOutputLogprob",
|
| 438 |
+
"ChatCompletionOutputLogprobs",
|
| 439 |
+
"ChatCompletionOutputMessage",
|
| 440 |
+
"ChatCompletionOutputToolCall",
|
| 441 |
+
"ChatCompletionOutputTopLogprob",
|
| 442 |
+
"ChatCompletionOutputUsage",
|
| 443 |
+
"ChatCompletionStreamOutput",
|
| 444 |
+
"ChatCompletionStreamOutputChoice",
|
| 445 |
+
"ChatCompletionStreamOutputDelta",
|
| 446 |
+
"ChatCompletionStreamOutputDeltaToolCall",
|
| 447 |
+
"ChatCompletionStreamOutputFunction",
|
| 448 |
+
"ChatCompletionStreamOutputLogprob",
|
| 449 |
+
"ChatCompletionStreamOutputLogprobs",
|
| 450 |
+
"ChatCompletionStreamOutputTopLogprob",
|
| 451 |
+
"ChatCompletionStreamOutputUsage",
|
| 452 |
+
"DepthEstimationInput",
|
| 453 |
+
"DepthEstimationOutput",
|
| 454 |
+
"DocumentQuestionAnsweringInput",
|
| 455 |
+
"DocumentQuestionAnsweringInputData",
|
| 456 |
+
"DocumentQuestionAnsweringOutputElement",
|
| 457 |
+
"DocumentQuestionAnsweringParameters",
|
| 458 |
+
"FeatureExtractionInput",
|
| 459 |
+
"FeatureExtractionInputTruncationDirection",
|
| 460 |
+
"FillMaskInput",
|
| 461 |
+
"FillMaskOutputElement",
|
| 462 |
+
"FillMaskParameters",
|
| 463 |
+
"ImageClassificationInput",
|
| 464 |
+
"ImageClassificationOutputElement",
|
| 465 |
+
"ImageClassificationOutputTransform",
|
| 466 |
+
"ImageClassificationParameters",
|
| 467 |
+
"ImageSegmentationInput",
|
| 468 |
+
"ImageSegmentationOutputElement",
|
| 469 |
+
"ImageSegmentationParameters",
|
| 470 |
+
"ImageSegmentationSubtask",
|
| 471 |
+
"ImageTextToImageInput",
|
| 472 |
+
"ImageTextToImageOutput",
|
| 473 |
+
"ImageTextToImageParameters",
|
| 474 |
+
"ImageTextToImageTargetSize",
|
| 475 |
+
"ImageTextToVideoInput",
|
| 476 |
+
"ImageTextToVideoOutput",
|
| 477 |
+
"ImageTextToVideoParameters",
|
| 478 |
+
"ImageTextToVideoTargetSize",
|
| 479 |
+
"ImageToImageInput",
|
| 480 |
+
"ImageToImageOutput",
|
| 481 |
+
"ImageToImageParameters",
|
| 482 |
+
"ImageToImageTargetSize",
|
| 483 |
+
"ImageToTextEarlyStoppingEnum",
|
| 484 |
+
"ImageToTextGenerationParameters",
|
| 485 |
+
"ImageToTextInput",
|
| 486 |
+
"ImageToTextOutput",
|
| 487 |
+
"ImageToTextParameters",
|
| 488 |
+
"ImageToVideoInput",
|
| 489 |
+
"ImageToVideoOutput",
|
| 490 |
+
"ImageToVideoParameters",
|
| 491 |
+
"ImageToVideoTargetSize",
|
| 492 |
+
"ObjectDetectionBoundingBox",
|
| 493 |
+
"ObjectDetectionInput",
|
| 494 |
+
"ObjectDetectionOutputElement",
|
| 495 |
+
"ObjectDetectionParameters",
|
| 496 |
+
"Padding",
|
| 497 |
+
"QuestionAnsweringInput",
|
| 498 |
+
"QuestionAnsweringInputData",
|
| 499 |
+
"QuestionAnsweringOutputElement",
|
| 500 |
+
"QuestionAnsweringParameters",
|
| 501 |
+
"SentenceSimilarityInput",
|
| 502 |
+
"SentenceSimilarityInputData",
|
| 503 |
+
"SummarizationInput",
|
| 504 |
+
"SummarizationOutput",
|
| 505 |
+
"SummarizationParameters",
|
| 506 |
+
"SummarizationTruncationStrategy",
|
| 507 |
+
"TableQuestionAnsweringInput",
|
| 508 |
+
"TableQuestionAnsweringInputData",
|
| 509 |
+
"TableQuestionAnsweringOutputElement",
|
| 510 |
+
"TableQuestionAnsweringParameters",
|
| 511 |
+
"Text2TextGenerationInput",
|
| 512 |
+
"Text2TextGenerationOutput",
|
| 513 |
+
"Text2TextGenerationParameters",
|
| 514 |
+
"Text2TextGenerationTruncationStrategy",
|
| 515 |
+
"TextClassificationInput",
|
| 516 |
+
"TextClassificationOutputElement",
|
| 517 |
+
"TextClassificationOutputTransform",
|
| 518 |
+
"TextClassificationParameters",
|
| 519 |
+
"TextGenerationInput",
|
| 520 |
+
"TextGenerationInputGenerateParameters",
|
| 521 |
+
"TextGenerationInputGrammarType",
|
| 522 |
+
"TextGenerationOutput",
|
| 523 |
+
"TextGenerationOutputBestOfSequence",
|
| 524 |
+
"TextGenerationOutputDetails",
|
| 525 |
+
"TextGenerationOutputFinishReason",
|
| 526 |
+
"TextGenerationOutputPrefillToken",
|
| 527 |
+
"TextGenerationOutputToken",
|
| 528 |
+
"TextGenerationStreamOutput",
|
| 529 |
+
"TextGenerationStreamOutputStreamDetails",
|
| 530 |
+
"TextGenerationStreamOutputToken",
|
| 531 |
+
"TextToAudioEarlyStoppingEnum",
|
| 532 |
+
"TextToAudioGenerationParameters",
|
| 533 |
+
"TextToAudioInput",
|
| 534 |
+
"TextToAudioOutput",
|
| 535 |
+
"TextToAudioParameters",
|
| 536 |
+
"TextToImageInput",
|
| 537 |
+
"TextToImageOutput",
|
| 538 |
+
"TextToImageParameters",
|
| 539 |
+
"TextToSpeechEarlyStoppingEnum",
|
| 540 |
+
"TextToSpeechGenerationParameters",
|
| 541 |
+
"TextToSpeechInput",
|
| 542 |
+
"TextToSpeechOutput",
|
| 543 |
+
"TextToSpeechParameters",
|
| 544 |
+
"TextToVideoInput",
|
| 545 |
+
"TextToVideoOutput",
|
| 546 |
+
"TextToVideoParameters",
|
| 547 |
+
"TokenClassificationAggregationStrategy",
|
| 548 |
+
"TokenClassificationInput",
|
| 549 |
+
"TokenClassificationOutputElement",
|
| 550 |
+
"TokenClassificationParameters",
|
| 551 |
+
"TranslationInput",
|
| 552 |
+
"TranslationOutput",
|
| 553 |
+
"TranslationParameters",
|
| 554 |
+
"TranslationTruncationStrategy",
|
| 555 |
+
"TypeEnum",
|
| 556 |
+
"VideoClassificationInput",
|
| 557 |
+
"VideoClassificationOutputElement",
|
| 558 |
+
"VideoClassificationOutputTransform",
|
| 559 |
+
"VideoClassificationParameters",
|
| 560 |
+
"VisualQuestionAnsweringInput",
|
| 561 |
+
"VisualQuestionAnsweringInputData",
|
| 562 |
+
"VisualQuestionAnsweringOutputElement",
|
| 563 |
+
"VisualQuestionAnsweringParameters",
|
| 564 |
+
"ZeroShotClassificationInput",
|
| 565 |
+
"ZeroShotClassificationOutputElement",
|
| 566 |
+
"ZeroShotClassificationParameters",
|
| 567 |
+
"ZeroShotImageClassificationInput",
|
| 568 |
+
"ZeroShotImageClassificationOutputElement",
|
| 569 |
+
"ZeroShotImageClassificationParameters",
|
| 570 |
+
"ZeroShotObjectDetectionBoundingBox",
|
| 571 |
+
"ZeroShotObjectDetectionInput",
|
| 572 |
+
"ZeroShotObjectDetectionOutputElement",
|
| 573 |
+
"ZeroShotObjectDetectionParameters",
|
| 574 |
+
],
|
| 575 |
+
"inference._mcp.agent": [
|
| 576 |
+
"Agent",
|
| 577 |
+
],
|
| 578 |
+
"inference._mcp.mcp_client": [
|
| 579 |
+
"MCPClient",
|
| 580 |
+
],
|
| 581 |
+
"repocard": [
|
| 582 |
+
"DatasetCard",
|
| 583 |
+
"ModelCard",
|
| 584 |
+
"RepoCard",
|
| 585 |
+
"SpaceCard",
|
| 586 |
+
"metadata_eval_result",
|
| 587 |
+
"metadata_load",
|
| 588 |
+
"metadata_save",
|
| 589 |
+
"metadata_update",
|
| 590 |
+
],
|
| 591 |
+
"repocard_data": [
|
| 592 |
+
"CardData",
|
| 593 |
+
"DatasetCardData",
|
| 594 |
+
"EvalResult",
|
| 595 |
+
"ModelCardData",
|
| 596 |
+
"SpaceCardData",
|
| 597 |
+
],
|
| 598 |
+
"serialization": [
|
| 599 |
+
"StateDictSplit",
|
| 600 |
+
"get_torch_storage_id",
|
| 601 |
+
"get_torch_storage_size",
|
| 602 |
+
"load_state_dict_from_file",
|
| 603 |
+
"load_torch_model",
|
| 604 |
+
"save_torch_model",
|
| 605 |
+
"save_torch_state_dict",
|
| 606 |
+
"split_state_dict_into_shards_factory",
|
| 607 |
+
"split_torch_state_dict_into_shards",
|
| 608 |
+
],
|
| 609 |
+
"serialization._dduf": [
|
| 610 |
+
"DDUFEntry",
|
| 611 |
+
"export_entries_as_dduf",
|
| 612 |
+
"export_folder_as_dduf",
|
| 613 |
+
"read_dduf_file",
|
| 614 |
+
],
|
| 615 |
+
"utils": [
|
| 616 |
+
"ASYNC_CLIENT_FACTORY_T",
|
| 617 |
+
"CLIENT_FACTORY_T",
|
| 618 |
+
"CacheNotFound",
|
| 619 |
+
"CachedFileInfo",
|
| 620 |
+
"CachedIncompleteFileInfo",
|
| 621 |
+
"CachedRepoInfo",
|
| 622 |
+
"CachedRevisionInfo",
|
| 623 |
+
"CorruptedCacheException",
|
| 624 |
+
"DeleteCacheStrategy",
|
| 625 |
+
"HFCacheInfo",
|
| 626 |
+
"HfUri",
|
| 627 |
+
"cached_assets_path",
|
| 628 |
+
"close_session",
|
| 629 |
+
"dump_environment_info",
|
| 630 |
+
"get_async_session",
|
| 631 |
+
"get_session",
|
| 632 |
+
"get_token",
|
| 633 |
+
"hf_raise_for_status",
|
| 634 |
+
"logging",
|
| 635 |
+
"parse_hf_uri",
|
| 636 |
+
"scan_cache_dir",
|
| 637 |
+
"set_async_client_factory",
|
| 638 |
+
"set_client_factory",
|
| 639 |
+
],
|
| 640 |
+
}
|
| 641 |
+
|
| 642 |
+
# WARNING: __all__ is generated automatically, Any manual edit will be lost when re-generating this file !
|
| 643 |
+
#
|
| 644 |
+
# To update the static imports, please run the following command and commit the changes.
|
| 645 |
+
# ```
|
| 646 |
+
# # Use script
|
| 647 |
+
# python utils/check_all_variable.py --update
|
| 648 |
+
#
|
| 649 |
+
# # Or run style on codebase
|
| 650 |
+
# make style
|
| 651 |
+
# ```
|
| 652 |
+
|
| 653 |
+
__all__ = [
|
| 654 |
+
"ASYNC_CLIENT_FACTORY_T",
|
| 655 |
+
"Agent",
|
| 656 |
+
"AsyncInferenceClient",
|
| 657 |
+
"AudioClassificationInput",
|
| 658 |
+
"AudioClassificationOutputElement",
|
| 659 |
+
"AudioClassificationOutputTransform",
|
| 660 |
+
"AudioClassificationParameters",
|
| 661 |
+
"AudioToAudioInput",
|
| 662 |
+
"AudioToAudioOutputElement",
|
| 663 |
+
"AutomaticSpeechRecognitionEarlyStoppingEnum",
|
| 664 |
+
"AutomaticSpeechRecognitionGenerationParameters",
|
| 665 |
+
"AutomaticSpeechRecognitionInput",
|
| 666 |
+
"AutomaticSpeechRecognitionOutput",
|
| 667 |
+
"AutomaticSpeechRecognitionOutputChunk",
|
| 668 |
+
"AutomaticSpeechRecognitionParameters",
|
| 669 |
+
"BucketFile",
|
| 670 |
+
"BucketFileMetadata",
|
| 671 |
+
"BucketFolder",
|
| 672 |
+
"BucketInfo",
|
| 673 |
+
"BucketUrl",
|
| 674 |
+
"CLIENT_FACTORY_T",
|
| 675 |
+
"CONFIG_NAME",
|
| 676 |
+
"CacheNotFound",
|
| 677 |
+
"CachedFileInfo",
|
| 678 |
+
"CachedIncompleteFileInfo",
|
| 679 |
+
"CachedRepoInfo",
|
| 680 |
+
"CachedRevisionInfo",
|
| 681 |
+
"CardData",
|
| 682 |
+
"ChatCompletionInput",
|
| 683 |
+
"ChatCompletionInputFunctionDefinition",
|
| 684 |
+
"ChatCompletionInputFunctionName",
|
| 685 |
+
"ChatCompletionInputGrammarType",
|
| 686 |
+
"ChatCompletionInputJSONSchema",
|
| 687 |
+
"ChatCompletionInputMessage",
|
| 688 |
+
"ChatCompletionInputMessageChunk",
|
| 689 |
+
"ChatCompletionInputMessageChunkType",
|
| 690 |
+
"ChatCompletionInputResponseFormatJSONObject",
|
| 691 |
+
"ChatCompletionInputResponseFormatJSONSchema",
|
| 692 |
+
"ChatCompletionInputResponseFormatText",
|
| 693 |
+
"ChatCompletionInputStreamOptions",
|
| 694 |
+
"ChatCompletionInputTool",
|
| 695 |
+
"ChatCompletionInputToolCall",
|
| 696 |
+
"ChatCompletionInputToolChoiceClass",
|
| 697 |
+
"ChatCompletionInputToolChoiceEnum",
|
| 698 |
+
"ChatCompletionInputURL",
|
| 699 |
+
"ChatCompletionOutput",
|
| 700 |
+
"ChatCompletionOutputComplete",
|
| 701 |
+
"ChatCompletionOutputFunctionDefinition",
|
| 702 |
+
"ChatCompletionOutputLogprob",
|
| 703 |
+
"ChatCompletionOutputLogprobs",
|
| 704 |
+
"ChatCompletionOutputMessage",
|
| 705 |
+
"ChatCompletionOutputToolCall",
|
| 706 |
+
"ChatCompletionOutputTopLogprob",
|
| 707 |
+
"ChatCompletionOutputUsage",
|
| 708 |
+
"ChatCompletionStreamOutput",
|
| 709 |
+
"ChatCompletionStreamOutputChoice",
|
| 710 |
+
"ChatCompletionStreamOutputDelta",
|
| 711 |
+
"ChatCompletionStreamOutputDeltaToolCall",
|
| 712 |
+
"ChatCompletionStreamOutputFunction",
|
| 713 |
+
"ChatCompletionStreamOutputLogprob",
|
| 714 |
+
"ChatCompletionStreamOutputLogprobs",
|
| 715 |
+
"ChatCompletionStreamOutputTopLogprob",
|
| 716 |
+
"ChatCompletionStreamOutputUsage",
|
| 717 |
+
"Collection",
|
| 718 |
+
"CollectionItem",
|
| 719 |
+
"CommitInfo",
|
| 720 |
+
"CommitOperation",
|
| 721 |
+
"CommitOperationAdd",
|
| 722 |
+
"CommitOperationCopy",
|
| 723 |
+
"CommitOperationDelete",
|
| 724 |
+
"CommitScheduler",
|
| 725 |
+
"CorruptedCacheException",
|
| 726 |
+
"DDUFEntry",
|
| 727 |
+
"DatasetCard",
|
| 728 |
+
"DatasetCardData",
|
| 729 |
+
"DatasetInfo",
|
| 730 |
+
"DatasetLeaderboardEntry",
|
| 731 |
+
"DeleteCacheStrategy",
|
| 732 |
+
"DepthEstimationInput",
|
| 733 |
+
"DepthEstimationOutput",
|
| 734 |
+
"Discussion",
|
| 735 |
+
"DiscussionComment",
|
| 736 |
+
"DiscussionCommit",
|
| 737 |
+
"DiscussionEvent",
|
| 738 |
+
"DiscussionStatusChange",
|
| 739 |
+
"DiscussionTitleChange",
|
| 740 |
+
"DiscussionWithDetails",
|
| 741 |
+
"DocumentQuestionAnsweringInput",
|
| 742 |
+
"DocumentQuestionAnsweringInputData",
|
| 743 |
+
"DocumentQuestionAnsweringOutputElement",
|
| 744 |
+
"DocumentQuestionAnsweringParameters",
|
| 745 |
+
"DryRunFileInfo",
|
| 746 |
+
"DuplicatedRepoUrl",
|
| 747 |
+
"EvalResult",
|
| 748 |
+
"EvalResultEntry",
|
| 749 |
+
"FLAX_WEIGHTS_NAME",
|
| 750 |
+
"FeatureExtractionInput",
|
| 751 |
+
"FeatureExtractionInputTruncationDirection",
|
| 752 |
+
"FillMaskInput",
|
| 753 |
+
"FillMaskOutputElement",
|
| 754 |
+
"FillMaskParameters",
|
| 755 |
+
"GitCommitInfo",
|
| 756 |
+
"GitRefInfo",
|
| 757 |
+
"GitRefs",
|
| 758 |
+
"HFCacheInfo",
|
| 759 |
+
"HFSummaryWriter",
|
| 760 |
+
"HUGGINGFACE_CO_URL_HOME",
|
| 761 |
+
"HUGGINGFACE_CO_URL_TEMPLATE",
|
| 762 |
+
"HfApi",
|
| 763 |
+
"HfFileMetadata",
|
| 764 |
+
"HfFileSystem",
|
| 765 |
+
"HfFileSystemFile",
|
| 766 |
+
"HfFileSystemResolvedPath",
|
| 767 |
+
"HfFileSystemStreamFile",
|
| 768 |
+
"HfUri",
|
| 769 |
+
"ImageClassificationInput",
|
| 770 |
+
"ImageClassificationOutputElement",
|
| 771 |
+
"ImageClassificationOutputTransform",
|
| 772 |
+
"ImageClassificationParameters",
|
| 773 |
+
"ImageSegmentationInput",
|
| 774 |
+
"ImageSegmentationOutputElement",
|
| 775 |
+
"ImageSegmentationParameters",
|
| 776 |
+
"ImageSegmentationSubtask",
|
| 777 |
+
"ImageTextToImageInput",
|
| 778 |
+
"ImageTextToImageOutput",
|
| 779 |
+
"ImageTextToImageParameters",
|
| 780 |
+
"ImageTextToImageTargetSize",
|
| 781 |
+
"ImageTextToVideoInput",
|
| 782 |
+
"ImageTextToVideoOutput",
|
| 783 |
+
"ImageTextToVideoParameters",
|
| 784 |
+
"ImageTextToVideoTargetSize",
|
| 785 |
+
"ImageToImageInput",
|
| 786 |
+
"ImageToImageOutput",
|
| 787 |
+
"ImageToImageParameters",
|
| 788 |
+
"ImageToImageTargetSize",
|
| 789 |
+
"ImageToTextEarlyStoppingEnum",
|
| 790 |
+
"ImageToTextGenerationParameters",
|
| 791 |
+
"ImageToTextInput",
|
| 792 |
+
"ImageToTextOutput",
|
| 793 |
+
"ImageToTextParameters",
|
| 794 |
+
"ImageToVideoInput",
|
| 795 |
+
"ImageToVideoOutput",
|
| 796 |
+
"ImageToVideoParameters",
|
| 797 |
+
"ImageToVideoTargetSize",
|
| 798 |
+
"InferenceCatalogModel",
|
| 799 |
+
"InferenceCatalogRecipe",
|
| 800 |
+
"InferenceClient",
|
| 801 |
+
"InferenceEndpoint",
|
| 802 |
+
"InferenceEndpointError",
|
| 803 |
+
"InferenceEndpointHardware",
|
| 804 |
+
"InferenceEndpointStatus",
|
| 805 |
+
"InferenceEndpointTimeoutError",
|
| 806 |
+
"InferenceEndpointType",
|
| 807 |
+
"InferenceTimeoutError",
|
| 808 |
+
"JobAccelerator",
|
| 809 |
+
"JobDurations",
|
| 810 |
+
"JobHardware",
|
| 811 |
+
"JobHardwareInfo",
|
| 812 |
+
"JobInfo",
|
| 813 |
+
"JobInitiator",
|
| 814 |
+
"JobNetwork",
|
| 815 |
+
"JobOwner",
|
| 816 |
+
"JobStage",
|
| 817 |
+
"JobStatus",
|
| 818 |
+
"KernelInfo",
|
| 819 |
+
"MCPClient",
|
| 820 |
+
"ModelCard",
|
| 821 |
+
"ModelCardData",
|
| 822 |
+
"ModelHubMixin",
|
| 823 |
+
"ModelInfo",
|
| 824 |
+
"OAuthInfo",
|
| 825 |
+
"OAuthOrgInfo",
|
| 826 |
+
"OAuthUserInfo",
|
| 827 |
+
"ObjectDetectionBoundingBox",
|
| 828 |
+
"ObjectDetectionInput",
|
| 829 |
+
"ObjectDetectionOutputElement",
|
| 830 |
+
"ObjectDetectionParameters",
|
| 831 |
+
"Organization",
|
| 832 |
+
"PYTORCH_WEIGHTS_NAME",
|
| 833 |
+
"Padding",
|
| 834 |
+
"PyTorchModelHubMixin",
|
| 835 |
+
"QuestionAnsweringInput",
|
| 836 |
+
"QuestionAnsweringInputData",
|
| 837 |
+
"QuestionAnsweringOutputElement",
|
| 838 |
+
"QuestionAnsweringParameters",
|
| 839 |
+
"REPO_TYPE_DATASET",
|
| 840 |
+
"REPO_TYPE_MODEL",
|
| 841 |
+
"REPO_TYPE_SPACE",
|
| 842 |
+
"RepoCard",
|
| 843 |
+
"RepoFile",
|
| 844 |
+
"RepoFolder",
|
| 845 |
+
"RepoStorageInfo",
|
| 846 |
+
"RepoUrl",
|
| 847 |
+
"ResolvedRevision",
|
| 848 |
+
"Sandbox",
|
| 849 |
+
"SandboxCommandResult",
|
| 850 |
+
"SandboxPool",
|
| 851 |
+
"SandboxProcess",
|
| 852 |
+
"SentenceSimilarityInput",
|
| 853 |
+
"SentenceSimilarityInputData",
|
| 854 |
+
"SpaceCard",
|
| 855 |
+
"SpaceCardData",
|
| 856 |
+
"SpaceHardware",
|
| 857 |
+
"SpaceInfo",
|
| 858 |
+
"SpaceRuntime",
|
| 859 |
+
"SpaceSearchResult",
|
| 860 |
+
"SpaceSecret",
|
| 861 |
+
"SpaceStage",
|
| 862 |
+
"SpaceStorage",
|
| 863 |
+
"SpaceTemplate",
|
| 864 |
+
"SpaceVariable",
|
| 865 |
+
"StateDictSplit",
|
| 866 |
+
"SummarizationInput",
|
| 867 |
+
"SummarizationOutput",
|
| 868 |
+
"SummarizationParameters",
|
| 869 |
+
"SummarizationTruncationStrategy",
|
| 870 |
+
"SyncOperation",
|
| 871 |
+
"SyncPlan",
|
| 872 |
+
"TF2_WEIGHTS_NAME",
|
| 873 |
+
"TF_WEIGHTS_NAME",
|
| 874 |
+
"TableQuestionAnsweringInput",
|
| 875 |
+
"TableQuestionAnsweringInputData",
|
| 876 |
+
"TableQuestionAnsweringOutputElement",
|
| 877 |
+
"TableQuestionAnsweringParameters",
|
| 878 |
+
"Text2TextGenerationInput",
|
| 879 |
+
"Text2TextGenerationOutput",
|
| 880 |
+
"Text2TextGenerationParameters",
|
| 881 |
+
"Text2TextGenerationTruncationStrategy",
|
| 882 |
+
"TextClassificationInput",
|
| 883 |
+
"TextClassificationOutputElement",
|
| 884 |
+
"TextClassificationOutputTransform",
|
| 885 |
+
"TextClassificationParameters",
|
| 886 |
+
"TextGenerationInput",
|
| 887 |
+
"TextGenerationInputGenerateParameters",
|
| 888 |
+
"TextGenerationInputGrammarType",
|
| 889 |
+
"TextGenerationOutput",
|
| 890 |
+
"TextGenerationOutputBestOfSequence",
|
| 891 |
+
"TextGenerationOutputDetails",
|
| 892 |
+
"TextGenerationOutputFinishReason",
|
| 893 |
+
"TextGenerationOutputPrefillToken",
|
| 894 |
+
"TextGenerationOutputToken",
|
| 895 |
+
"TextGenerationStreamOutput",
|
| 896 |
+
"TextGenerationStreamOutputStreamDetails",
|
| 897 |
+
"TextGenerationStreamOutputToken",
|
| 898 |
+
"TextToAudioEarlyStoppingEnum",
|
| 899 |
+
"TextToAudioGenerationParameters",
|
| 900 |
+
"TextToAudioInput",
|
| 901 |
+
"TextToAudioOutput",
|
| 902 |
+
"TextToAudioParameters",
|
| 903 |
+
"TextToImageInput",
|
| 904 |
+
"TextToImageOutput",
|
| 905 |
+
"TextToImageParameters",
|
| 906 |
+
"TextToSpeechEarlyStoppingEnum",
|
| 907 |
+
"TextToSpeechGenerationParameters",
|
| 908 |
+
"TextToSpeechInput",
|
| 909 |
+
"TextToSpeechOutput",
|
| 910 |
+
"TextToSpeechParameters",
|
| 911 |
+
"TextToVideoInput",
|
| 912 |
+
"TextToVideoOutput",
|
| 913 |
+
"TextToVideoParameters",
|
| 914 |
+
"TokenClassificationAggregationStrategy",
|
| 915 |
+
"TokenClassificationInput",
|
| 916 |
+
"TokenClassificationOutputElement",
|
| 917 |
+
"TokenClassificationParameters",
|
| 918 |
+
"TranslationInput",
|
| 919 |
+
"TranslationOutput",
|
| 920 |
+
"TranslationParameters",
|
| 921 |
+
"TranslationTruncationStrategy",
|
| 922 |
+
"TypeEnum",
|
| 923 |
+
"User",
|
| 924 |
+
"UserLikes",
|
| 925 |
+
"VideoClassificationInput",
|
| 926 |
+
"VideoClassificationOutputElement",
|
| 927 |
+
"VideoClassificationOutputTransform",
|
| 928 |
+
"VideoClassificationParameters",
|
| 929 |
+
"VisualQuestionAnsweringInput",
|
| 930 |
+
"VisualQuestionAnsweringInputData",
|
| 931 |
+
"VisualQuestionAnsweringOutputElement",
|
| 932 |
+
"VisualQuestionAnsweringParameters",
|
| 933 |
+
"Volume",
|
| 934 |
+
"WebhookInfo",
|
| 935 |
+
"WebhookPayload",
|
| 936 |
+
"WebhookPayloadComment",
|
| 937 |
+
"WebhookPayloadDiscussion",
|
| 938 |
+
"WebhookPayloadDiscussionChanges",
|
| 939 |
+
"WebhookPayloadEvent",
|
| 940 |
+
"WebhookPayloadMovedTo",
|
| 941 |
+
"WebhookPayloadRepo",
|
| 942 |
+
"WebhookPayloadUrl",
|
| 943 |
+
"WebhookPayloadWebhook",
|
| 944 |
+
"WebhookWatchedItem",
|
| 945 |
+
"WebhooksServer",
|
| 946 |
+
"ZeroGpuQuota",
|
| 947 |
+
"ZeroShotClassificationInput",
|
| 948 |
+
"ZeroShotClassificationOutputElement",
|
| 949 |
+
"ZeroShotClassificationParameters",
|
| 950 |
+
"ZeroShotImageClassificationInput",
|
| 951 |
+
"ZeroShotImageClassificationOutputElement",
|
| 952 |
+
"ZeroShotImageClassificationParameters",
|
| 953 |
+
"ZeroShotObjectDetectionBoundingBox",
|
| 954 |
+
"ZeroShotObjectDetectionInput",
|
| 955 |
+
"ZeroShotObjectDetectionOutputElement",
|
| 956 |
+
"ZeroShotObjectDetectionParameters",
|
| 957 |
+
"_CACHED_NO_EXIST",
|
| 958 |
+
"_save_pretrained_fastai",
|
| 959 |
+
"accept_access_request",
|
| 960 |
+
"add_collection_item",
|
| 961 |
+
"add_space_secret",
|
| 962 |
+
"add_space_variable",
|
| 963 |
+
"attach_huggingface_oauth",
|
| 964 |
+
"auth_check",
|
| 965 |
+
"auth_list",
|
| 966 |
+
"auth_switch",
|
| 967 |
+
"batch_bucket_files",
|
| 968 |
+
"bucket_info",
|
| 969 |
+
"cached_assets_path",
|
| 970 |
+
"cancel_access_request",
|
| 971 |
+
"cancel_job",
|
| 972 |
+
"change_discussion_status",
|
| 973 |
+
"check_cli_update",
|
| 974 |
+
"close_session",
|
| 975 |
+
"comment_discussion",
|
| 976 |
+
"copy_files",
|
| 977 |
+
"create_branch",
|
| 978 |
+
"create_bucket",
|
| 979 |
+
"create_collection",
|
| 980 |
+
"create_commit",
|
| 981 |
+
"create_discussion",
|
| 982 |
+
"create_inference_endpoint",
|
| 983 |
+
"create_inference_endpoint_from_catalog",
|
| 984 |
+
"create_pull_request",
|
| 985 |
+
"create_repo",
|
| 986 |
+
"create_scheduled_job",
|
| 987 |
+
"create_scheduled_uv_job",
|
| 988 |
+
"create_tag",
|
| 989 |
+
"create_webhook",
|
| 990 |
+
"dataset_info",
|
| 991 |
+
"delete_branch",
|
| 992 |
+
"delete_bucket",
|
| 993 |
+
"delete_collection",
|
| 994 |
+
"delete_collection_item",
|
| 995 |
+
"delete_file",
|
| 996 |
+
"delete_folder",
|
| 997 |
+
"delete_inference_endpoint",
|
| 998 |
+
"delete_repo",
|
| 999 |
+
"delete_scheduled_job",
|
| 1000 |
+
"delete_space_secret",
|
| 1001 |
+
"delete_space_variable",
|
| 1002 |
+
"delete_space_volumes",
|
| 1003 |
+
"delete_tag",
|
| 1004 |
+
"delete_webhook",
|
| 1005 |
+
"disable_space_dev_mode",
|
| 1006 |
+
"disable_webhook",
|
| 1007 |
+
"download_bucket_files",
|
| 1008 |
+
"dump_environment_info",
|
| 1009 |
+
"duplicate_repo",
|
| 1010 |
+
"edit_discussion_comment",
|
| 1011 |
+
"enable_space_dev_mode",
|
| 1012 |
+
"enable_webhook",
|
| 1013 |
+
"eval_result_entries_to_yaml",
|
| 1014 |
+
"export_entries_as_dduf",
|
| 1015 |
+
"export_folder_as_dduf",
|
| 1016 |
+
"fetch_job_logs",
|
| 1017 |
+
"fetch_job_metrics",
|
| 1018 |
+
"fetch_space_logs",
|
| 1019 |
+
"file_exists",
|
| 1020 |
+
"from_pretrained_fastai",
|
| 1021 |
+
"get_async_session",
|
| 1022 |
+
"get_bucket_file_metadata",
|
| 1023 |
+
"get_bucket_paths_info",
|
| 1024 |
+
"get_cached_repo_tree",
|
| 1025 |
+
"get_collection",
|
| 1026 |
+
"get_dataset_leaderboard",
|
| 1027 |
+
"get_dataset_tags",
|
| 1028 |
+
"get_discussion_details",
|
| 1029 |
+
"get_full_repo_name",
|
| 1030 |
+
"get_hf_file_metadata",
|
| 1031 |
+
"get_inference_endpoint",
|
| 1032 |
+
"get_local_safetensors_metadata",
|
| 1033 |
+
"get_model_tags",
|
| 1034 |
+
"get_organization_overview",
|
| 1035 |
+
"get_paths_info",
|
| 1036 |
+
"get_repo_discussions",
|
| 1037 |
+
"get_safetensors_metadata",
|
| 1038 |
+
"get_session",
|
| 1039 |
+
"get_sharded_safetensors_metadata",
|
| 1040 |
+
"get_space_runtime",
|
| 1041 |
+
"get_space_secrets",
|
| 1042 |
+
"get_space_variables",
|
| 1043 |
+
"get_token",
|
| 1044 |
+
"get_torch_storage_id",
|
| 1045 |
+
"get_torch_storage_size",
|
| 1046 |
+
"get_user_overview",
|
| 1047 |
+
"get_webhook",
|
| 1048 |
+
"get_zero_gpu_quota",
|
| 1049 |
+
"grant_access",
|
| 1050 |
+
"hf_hub_download",
|
| 1051 |
+
"hf_hub_url",
|
| 1052 |
+
"hf_raise_for_status",
|
| 1053 |
+
"hffs",
|
| 1054 |
+
"inspect_job",
|
| 1055 |
+
"inspect_scheduled_job",
|
| 1056 |
+
"interpreter_login",
|
| 1057 |
+
"is_offline_mode",
|
| 1058 |
+
"kernel_info",
|
| 1059 |
+
"list_accepted_access_requests",
|
| 1060 |
+
"list_bucket_tree",
|
| 1061 |
+
"list_buckets",
|
| 1062 |
+
"list_collections",
|
| 1063 |
+
"list_daily_papers",
|
| 1064 |
+
"list_dataset_parquet_files",
|
| 1065 |
+
"list_datasets",
|
| 1066 |
+
"list_inference_catalog",
|
| 1067 |
+
"list_inference_endpoints",
|
| 1068 |
+
"list_inference_endpoints_hardware",
|
| 1069 |
+
"list_jobs",
|
| 1070 |
+
"list_jobs_hardware",
|
| 1071 |
+
"list_lfs_files",
|
| 1072 |
+
"list_liked_repos",
|
| 1073 |
+
"list_models",
|
| 1074 |
+
"list_organization_followers",
|
| 1075 |
+
"list_organization_members",
|
| 1076 |
+
"list_papers",
|
| 1077 |
+
"list_pending_access_requests",
|
| 1078 |
+
"list_rejected_access_requests",
|
| 1079 |
+
"list_repo_commits",
|
| 1080 |
+
"list_repo_files",
|
| 1081 |
+
"list_repo_likers",
|
| 1082 |
+
"list_repo_refs",
|
| 1083 |
+
"list_repo_tree",
|
| 1084 |
+
"list_scheduled_jobs",
|
| 1085 |
+
"list_space_templates",
|
| 1086 |
+
"list_spaces",
|
| 1087 |
+
"list_spaces_hardware",
|
| 1088 |
+
"list_user_followers",
|
| 1089 |
+
"list_user_following",
|
| 1090 |
+
"list_user_repos",
|
| 1091 |
+
"list_webhooks",
|
| 1092 |
+
"load_state_dict_from_file",
|
| 1093 |
+
"load_torch_model",
|
| 1094 |
+
"logging",
|
| 1095 |
+
"login",
|
| 1096 |
+
"logout",
|
| 1097 |
+
"merge_pull_request",
|
| 1098 |
+
"metadata_eval_result",
|
| 1099 |
+
"metadata_load",
|
| 1100 |
+
"metadata_save",
|
| 1101 |
+
"metadata_update",
|
| 1102 |
+
"model_info",
|
| 1103 |
+
"move_bucket",
|
| 1104 |
+
"move_repo",
|
| 1105 |
+
"notebook_login",
|
| 1106 |
+
"paper_info",
|
| 1107 |
+
"parse_eval_result_entries",
|
| 1108 |
+
"parse_hf_uri",
|
| 1109 |
+
"parse_huggingface_oauth",
|
| 1110 |
+
"parse_local_safetensors_file_metadata",
|
| 1111 |
+
"parse_safetensors_file_metadata",
|
| 1112 |
+
"pause_inference_endpoint",
|
| 1113 |
+
"pause_space",
|
| 1114 |
+
"permanently_delete_lfs_files",
|
| 1115 |
+
"preupload_lfs_files",
|
| 1116 |
+
"push_to_hub_fastai",
|
| 1117 |
+
"read_dduf_file",
|
| 1118 |
+
"read_paper",
|
| 1119 |
+
"reject_access_request",
|
| 1120 |
+
"rename_discussion",
|
| 1121 |
+
"repo_exists",
|
| 1122 |
+
"repo_info",
|
| 1123 |
+
"request_space_hardware",
|
| 1124 |
+
"rerun_job",
|
| 1125 |
+
"resolve_revision",
|
| 1126 |
+
"restart_space",
|
| 1127 |
+
"resume_inference_endpoint",
|
| 1128 |
+
"resume_scheduled_job",
|
| 1129 |
+
"revision_exists",
|
| 1130 |
+
"run_as_future",
|
| 1131 |
+
"run_job",
|
| 1132 |
+
"run_uv_job",
|
| 1133 |
+
"save_torch_model",
|
| 1134 |
+
"save_torch_state_dict",
|
| 1135 |
+
"scale_to_zero_inference_endpoint",
|
| 1136 |
+
"scan_cache_dir",
|
| 1137 |
+
"search_spaces",
|
| 1138 |
+
"set_async_client_factory",
|
| 1139 |
+
"set_client_factory",
|
| 1140 |
+
"set_space_sleep_time",
|
| 1141 |
+
"set_space_volumes",
|
| 1142 |
+
"snapshot_download",
|
| 1143 |
+
"space_info",
|
| 1144 |
+
"split_state_dict_into_shards_factory",
|
| 1145 |
+
"split_torch_state_dict_into_shards",
|
| 1146 |
+
"super_squash_history",
|
| 1147 |
+
"suspend_scheduled_job",
|
| 1148 |
+
"sync_bucket",
|
| 1149 |
+
"sync_job_volume",
|
| 1150 |
+
"trigger_scheduled_job",
|
| 1151 |
+
"try_to_load_from_cache",
|
| 1152 |
+
"typer_factory",
|
| 1153 |
+
"unlike",
|
| 1154 |
+
"update_bucket_settings",
|
| 1155 |
+
"update_collection_item",
|
| 1156 |
+
"update_collection_metadata",
|
| 1157 |
+
"update_collection_resource_group",
|
| 1158 |
+
"update_inference_endpoint",
|
| 1159 |
+
"update_job_expose",
|
| 1160 |
+
"update_job_labels",
|
| 1161 |
+
"update_repo_settings",
|
| 1162 |
+
"update_scheduled_job_labels",
|
| 1163 |
+
"update_scheduled_job_schedule",
|
| 1164 |
+
"update_webhook",
|
| 1165 |
+
"upload_attachment",
|
| 1166 |
+
"upload_file",
|
| 1167 |
+
"upload_folder",
|
| 1168 |
+
"verify_repo_checksums",
|
| 1169 |
+
"wait_for_job",
|
| 1170 |
+
"wait_for_space",
|
| 1171 |
+
"webhook_endpoint",
|
| 1172 |
+
"whoami",
|
| 1173 |
+
]
|
| 1174 |
+
|
| 1175 |
+
|
| 1176 |
+
def _attach(package_name, submodules=None, submod_attrs=None):
|
| 1177 |
+
"""Attach lazily loaded submodules, functions, or other attributes.
|
| 1178 |
+
|
| 1179 |
+
Typically, modules import submodules and attributes as follows:
|
| 1180 |
+
|
| 1181 |
+
```py
|
| 1182 |
+
import mysubmodule
|
| 1183 |
+
import anothersubmodule
|
| 1184 |
+
|
| 1185 |
+
from .foo import someattr
|
| 1186 |
+
```
|
| 1187 |
+
|
| 1188 |
+
The idea is to replace a package's `__getattr__`, `__dir__`, such that all imports
|
| 1189 |
+
work exactly the way they would with normal imports, except that the import occurs
|
| 1190 |
+
upon first use.
|
| 1191 |
+
|
| 1192 |
+
The typical way to call this function, replacing the above imports, is:
|
| 1193 |
+
|
| 1194 |
+
```python
|
| 1195 |
+
__getattr__, __dir__ = lazy.attach(
|
| 1196 |
+
__name__,
|
| 1197 |
+
['mysubmodule', 'anothersubmodule'],
|
| 1198 |
+
{'foo': ['someattr']}
|
| 1199 |
+
)
|
| 1200 |
+
```
|
| 1201 |
+
This functionality requires Python 3.7 or higher.
|
| 1202 |
+
|
| 1203 |
+
Args:
|
| 1204 |
+
package_name (`str`):
|
| 1205 |
+
Typically use `__name__`.
|
| 1206 |
+
submodules (`set`):
|
| 1207 |
+
List of submodules to attach.
|
| 1208 |
+
submod_attrs (`dict`):
|
| 1209 |
+
Dictionary of submodule -> list of attributes / functions.
|
| 1210 |
+
These attributes are imported as they are used.
|
| 1211 |
+
|
| 1212 |
+
Returns:
|
| 1213 |
+
__getattr__, __dir__, __all__
|
| 1214 |
+
|
| 1215 |
+
"""
|
| 1216 |
+
if submod_attrs is None:
|
| 1217 |
+
submod_attrs = {}
|
| 1218 |
+
|
| 1219 |
+
if submodules is None:
|
| 1220 |
+
submodules = set()
|
| 1221 |
+
else:
|
| 1222 |
+
submodules = set(submodules)
|
| 1223 |
+
|
| 1224 |
+
attr_to_modules = {attr: mod for mod, attrs in submod_attrs.items() for attr in attrs}
|
| 1225 |
+
|
| 1226 |
+
def __getattr__(name):
|
| 1227 |
+
if name in submodules:
|
| 1228 |
+
try:
|
| 1229 |
+
return importlib.import_module(f"{package_name}.{name}")
|
| 1230 |
+
except Exception as e:
|
| 1231 |
+
print(f"Error importing {package_name}.{name}: {e}")
|
| 1232 |
+
raise
|
| 1233 |
+
elif name in attr_to_modules:
|
| 1234 |
+
submod_path = f"{package_name}.{attr_to_modules[name]}"
|
| 1235 |
+
try:
|
| 1236 |
+
submod = importlib.import_module(submod_path)
|
| 1237 |
+
except Exception as e:
|
| 1238 |
+
print(f"Error importing {submod_path}: {e}")
|
| 1239 |
+
raise
|
| 1240 |
+
attr = getattr(submod, name)
|
| 1241 |
+
|
| 1242 |
+
# If the attribute lives in a file (module) with the same
|
| 1243 |
+
# name as the attribute, ensure that the attribute and *not*
|
| 1244 |
+
# the module is accessible on the package.
|
| 1245 |
+
if name == attr_to_modules[name]:
|
| 1246 |
+
pkg = sys.modules[package_name]
|
| 1247 |
+
pkg.__dict__[name] = attr
|
| 1248 |
+
|
| 1249 |
+
return attr
|
| 1250 |
+
else:
|
| 1251 |
+
raise AttributeError(f"No {package_name} attribute {name}")
|
| 1252 |
+
|
| 1253 |
+
def __dir__():
|
| 1254 |
+
return __all__
|
| 1255 |
+
|
| 1256 |
+
return __getattr__, __dir__
|
| 1257 |
+
|
| 1258 |
+
|
| 1259 |
+
__getattr__, __dir__ = _attach(__name__, submodules=[], submod_attrs=_SUBMOD_ATTRS)
|
| 1260 |
+
|
| 1261 |
+
if os.environ.get("EAGER_IMPORT", ""):
|
| 1262 |
+
for attr in __all__:
|
| 1263 |
+
__getattr__(attr)
|
| 1264 |
+
|
| 1265 |
+
# WARNING: any content below this statement is generated automatically. Any manual edit
|
| 1266 |
+
# will be lost when re-generating this file !
|
| 1267 |
+
#
|
| 1268 |
+
# To update the static imports, please run the following command and commit the changes.
|
| 1269 |
+
# ```
|
| 1270 |
+
# # Use script
|
| 1271 |
+
# python utils/check_static_imports.py --update
|
| 1272 |
+
#
|
| 1273 |
+
# # Or run style on codebase
|
| 1274 |
+
# make style
|
| 1275 |
+
# ```
|
| 1276 |
+
if TYPE_CHECKING: # pragma: no cover
|
| 1277 |
+
from ._buckets import (
|
| 1278 |
+
BucketFile, # noqa: F401
|
| 1279 |
+
BucketFileMetadata, # noqa: F401
|
| 1280 |
+
BucketFolder, # noqa: F401
|
| 1281 |
+
BucketInfo, # noqa: F401
|
| 1282 |
+
BucketUrl, # noqa: F401
|
| 1283 |
+
SyncOperation, # noqa: F401
|
| 1284 |
+
SyncPlan, # noqa: F401
|
| 1285 |
+
)
|
| 1286 |
+
from ._commit_api import (
|
| 1287 |
+
CommitOperation, # noqa: F401
|
| 1288 |
+
CommitOperationAdd, # noqa: F401
|
| 1289 |
+
CommitOperationCopy, # noqa: F401
|
| 1290 |
+
CommitOperationDelete, # noqa: F401
|
| 1291 |
+
)
|
| 1292 |
+
from ._commit_scheduler import CommitScheduler # noqa: F401
|
| 1293 |
+
from ._eval_results import (
|
| 1294 |
+
EvalResultEntry, # noqa: F401
|
| 1295 |
+
eval_result_entries_to_yaml, # noqa: F401
|
| 1296 |
+
parse_eval_result_entries, # noqa: F401
|
| 1297 |
+
)
|
| 1298 |
+
from ._inference_endpoints import (
|
| 1299 |
+
InferenceCatalogModel, # noqa: F401
|
| 1300 |
+
InferenceCatalogRecipe, # noqa: F401
|
| 1301 |
+
InferenceEndpoint, # noqa: F401
|
| 1302 |
+
InferenceEndpointError, # noqa: F401
|
| 1303 |
+
InferenceEndpointHardware, # noqa: F401
|
| 1304 |
+
InferenceEndpointStatus, # noqa: F401
|
| 1305 |
+
InferenceEndpointTimeoutError, # noqa: F401
|
| 1306 |
+
InferenceEndpointType, # noqa: F401
|
| 1307 |
+
)
|
| 1308 |
+
from ._jobs_api import (
|
| 1309 |
+
JobAccelerator, # noqa: F401
|
| 1310 |
+
JobDurations, # noqa: F401
|
| 1311 |
+
JobHardware, # noqa: F401
|
| 1312 |
+
JobHardwareInfo, # noqa: F401
|
| 1313 |
+
JobInfo, # noqa: F401
|
| 1314 |
+
JobInitiator, # noqa: F401
|
| 1315 |
+
JobNetwork, # noqa: F401
|
| 1316 |
+
JobOwner, # noqa: F401
|
| 1317 |
+
JobStage, # noqa: F401
|
| 1318 |
+
JobStatus, # noqa: F401
|
| 1319 |
+
)
|
| 1320 |
+
from ._login import (
|
| 1321 |
+
auth_list, # noqa: F401
|
| 1322 |
+
auth_switch, # noqa: F401
|
| 1323 |
+
interpreter_login, # noqa: F401
|
| 1324 |
+
login, # noqa: F401
|
| 1325 |
+
logout, # noqa: F401
|
| 1326 |
+
notebook_login, # noqa: F401
|
| 1327 |
+
)
|
| 1328 |
+
from ._oauth import (
|
| 1329 |
+
OAuthInfo, # noqa: F401
|
| 1330 |
+
OAuthOrgInfo, # noqa: F401
|
| 1331 |
+
OAuthUserInfo, # noqa: F401
|
| 1332 |
+
attach_huggingface_oauth, # noqa: F401
|
| 1333 |
+
parse_huggingface_oauth, # noqa: F401
|
| 1334 |
+
)
|
| 1335 |
+
from ._revision import ResolvedRevision # noqa: F401
|
| 1336 |
+
from ._sandbox import (
|
| 1337 |
+
Sandbox, # noqa: F401
|
| 1338 |
+
SandboxCommandResult, # noqa: F401
|
| 1339 |
+
SandboxPool, # noqa: F401
|
| 1340 |
+
SandboxProcess, # noqa: F401
|
| 1341 |
+
)
|
| 1342 |
+
from ._snapshot_download import (
|
| 1343 |
+
get_cached_repo_tree, # noqa: F401
|
| 1344 |
+
snapshot_download, # noqa: F401
|
| 1345 |
+
)
|
| 1346 |
+
from ._space_api import (
|
| 1347 |
+
SpaceHardware, # noqa: F401
|
| 1348 |
+
SpaceRuntime, # noqa: F401
|
| 1349 |
+
SpaceSecret, # noqa: F401
|
| 1350 |
+
SpaceStage, # noqa: F401
|
| 1351 |
+
SpaceStorage, # noqa: F401
|
| 1352 |
+
SpaceVariable, # noqa: F401
|
| 1353 |
+
Volume, # noqa: F401
|
| 1354 |
+
ZeroGpuQuota, # noqa: F401
|
| 1355 |
+
)
|
| 1356 |
+
from ._tensorboard_logger import HFSummaryWriter # noqa: F401
|
| 1357 |
+
from ._webhooks_payload import (
|
| 1358 |
+
WebhookPayload, # noqa: F401
|
| 1359 |
+
WebhookPayloadComment, # noqa: F401
|
| 1360 |
+
WebhookPayloadDiscussion, # noqa: F401
|
| 1361 |
+
WebhookPayloadDiscussionChanges, # noqa: F401
|
| 1362 |
+
WebhookPayloadEvent, # noqa: F401
|
| 1363 |
+
WebhookPayloadMovedTo, # noqa: F401
|
| 1364 |
+
WebhookPayloadRepo, # noqa: F401
|
| 1365 |
+
WebhookPayloadUrl, # noqa: F401
|
| 1366 |
+
WebhookPayloadWebhook, # noqa: F401
|
| 1367 |
+
)
|
| 1368 |
+
from ._webhooks_server import (
|
| 1369 |
+
WebhooksServer, # noqa: F401
|
| 1370 |
+
webhook_endpoint, # noqa: F401
|
| 1371 |
+
)
|
| 1372 |
+
from .cli._cli_utils import (
|
| 1373 |
+
check_cli_update, # noqa: F401
|
| 1374 |
+
typer_factory, # noqa: F401
|
| 1375 |
+
)
|
| 1376 |
+
from .community import (
|
| 1377 |
+
Discussion, # noqa: F401
|
| 1378 |
+
DiscussionComment, # noqa: F401
|
| 1379 |
+
DiscussionCommit, # noqa: F401
|
| 1380 |
+
DiscussionEvent, # noqa: F401
|
| 1381 |
+
DiscussionStatusChange, # noqa: F401
|
| 1382 |
+
DiscussionTitleChange, # noqa: F401
|
| 1383 |
+
DiscussionWithDetails, # noqa: F401
|
| 1384 |
+
)
|
| 1385 |
+
from .constants import (
|
| 1386 |
+
CONFIG_NAME, # noqa: F401
|
| 1387 |
+
FLAX_WEIGHTS_NAME, # noqa: F401
|
| 1388 |
+
HUGGINGFACE_CO_URL_HOME, # noqa: F401
|
| 1389 |
+
HUGGINGFACE_CO_URL_TEMPLATE, # noqa: F401
|
| 1390 |
+
PYTORCH_WEIGHTS_NAME, # noqa: F401
|
| 1391 |
+
REPO_TYPE_DATASET, # noqa: F401
|
| 1392 |
+
REPO_TYPE_MODEL, # noqa: F401
|
| 1393 |
+
REPO_TYPE_SPACE, # noqa: F401
|
| 1394 |
+
TF2_WEIGHTS_NAME, # noqa: F401
|
| 1395 |
+
TF_WEIGHTS_NAME, # noqa: F401
|
| 1396 |
+
is_offline_mode, # noqa: F401
|
| 1397 |
+
)
|
| 1398 |
+
from .fastai_utils import (
|
| 1399 |
+
_save_pretrained_fastai, # noqa: F401
|
| 1400 |
+
from_pretrained_fastai, # noqa: F401
|
| 1401 |
+
push_to_hub_fastai, # noqa: F401
|
| 1402 |
+
)
|
| 1403 |
+
from .file_download import (
|
| 1404 |
+
_CACHED_NO_EXIST, # noqa: F401
|
| 1405 |
+
DryRunFileInfo, # noqa: F401
|
| 1406 |
+
HfFileMetadata, # noqa: F401
|
| 1407 |
+
get_hf_file_metadata, # noqa: F401
|
| 1408 |
+
hf_hub_download, # noqa: F401
|
| 1409 |
+
hf_hub_url, # noqa: F401
|
| 1410 |
+
try_to_load_from_cache, # noqa: F401
|
| 1411 |
+
)
|
| 1412 |
+
from .hf_api import (
|
| 1413 |
+
Collection, # noqa: F401
|
| 1414 |
+
CollectionItem, # noqa: F401
|
| 1415 |
+
CommitInfo, # noqa: F401
|
| 1416 |
+
DatasetInfo, # noqa: F401
|
| 1417 |
+
DatasetLeaderboardEntry, # noqa: F401
|
| 1418 |
+
DuplicatedRepoUrl, # noqa: F401
|
| 1419 |
+
GitCommitInfo, # noqa: F401
|
| 1420 |
+
GitRefInfo, # noqa: F401
|
| 1421 |
+
GitRefs, # noqa: F401
|
| 1422 |
+
HfApi, # noqa: F401
|
| 1423 |
+
KernelInfo, # noqa: F401
|
| 1424 |
+
ModelInfo, # noqa: F401
|
| 1425 |
+
Organization, # noqa: F401
|
| 1426 |
+
RepoFile, # noqa: F401
|
| 1427 |
+
RepoFolder, # noqa: F401
|
| 1428 |
+
RepoStorageInfo, # noqa: F401
|
| 1429 |
+
RepoUrl, # noqa: F401
|
| 1430 |
+
SpaceInfo, # noqa: F401
|
| 1431 |
+
SpaceSearchResult, # noqa: F401
|
| 1432 |
+
SpaceTemplate, # noqa: F401
|
| 1433 |
+
User, # noqa: F401
|
| 1434 |
+
UserLikes, # noqa: F401
|
| 1435 |
+
WebhookInfo, # noqa: F401
|
| 1436 |
+
WebhookWatchedItem, # noqa: F401
|
| 1437 |
+
accept_access_request, # noqa: F401
|
| 1438 |
+
add_collection_item, # noqa: F401
|
| 1439 |
+
add_space_secret, # noqa: F401
|
| 1440 |
+
add_space_variable, # noqa: F401
|
| 1441 |
+
auth_check, # noqa: F401
|
| 1442 |
+
batch_bucket_files, # noqa: F401
|
| 1443 |
+
bucket_info, # noqa: F401
|
| 1444 |
+
cancel_access_request, # noqa: F401
|
| 1445 |
+
cancel_job, # noqa: F401
|
| 1446 |
+
change_discussion_status, # noqa: F401
|
| 1447 |
+
comment_discussion, # noqa: F401
|
| 1448 |
+
copy_files, # noqa: F401
|
| 1449 |
+
create_branch, # noqa: F401
|
| 1450 |
+
create_bucket, # noqa: F401
|
| 1451 |
+
create_collection, # noqa: F401
|
| 1452 |
+
create_commit, # noqa: F401
|
| 1453 |
+
create_discussion, # noqa: F401
|
| 1454 |
+
create_inference_endpoint, # noqa: F401
|
| 1455 |
+
create_inference_endpoint_from_catalog, # noqa: F401
|
| 1456 |
+
create_pull_request, # noqa: F401
|
| 1457 |
+
create_repo, # noqa: F401
|
| 1458 |
+
create_scheduled_job, # noqa: F401
|
| 1459 |
+
create_scheduled_uv_job, # noqa: F401
|
| 1460 |
+
create_tag, # noqa: F401
|
| 1461 |
+
create_webhook, # noqa: F401
|
| 1462 |
+
dataset_info, # noqa: F401
|
| 1463 |
+
delete_branch, # noqa: F401
|
| 1464 |
+
delete_bucket, # noqa: F401
|
| 1465 |
+
delete_collection, # noqa: F401
|
| 1466 |
+
delete_collection_item, # noqa: F401
|
| 1467 |
+
delete_file, # noqa: F401
|
| 1468 |
+
delete_folder, # noqa: F401
|
| 1469 |
+
delete_inference_endpoint, # noqa: F401
|
| 1470 |
+
delete_repo, # noqa: F401
|
| 1471 |
+
delete_scheduled_job, # noqa: F401
|
| 1472 |
+
delete_space_secret, # noqa: F401
|
| 1473 |
+
delete_space_variable, # noqa: F401
|
| 1474 |
+
delete_space_volumes, # noqa: F401
|
| 1475 |
+
delete_tag, # noqa: F401
|
| 1476 |
+
delete_webhook, # noqa: F401
|
| 1477 |
+
disable_space_dev_mode, # noqa: F401
|
| 1478 |
+
disable_webhook, # noqa: F401
|
| 1479 |
+
download_bucket_files, # noqa: F401
|
| 1480 |
+
duplicate_repo, # noqa: F401
|
| 1481 |
+
edit_discussion_comment, # noqa: F401
|
| 1482 |
+
enable_space_dev_mode, # noqa: F401
|
| 1483 |
+
enable_webhook, # noqa: F401
|
| 1484 |
+
fetch_job_logs, # noqa: F401
|
| 1485 |
+
fetch_job_metrics, # noqa: F401
|
| 1486 |
+
fetch_space_logs, # noqa: F401
|
| 1487 |
+
file_exists, # noqa: F401
|
| 1488 |
+
get_bucket_file_metadata, # noqa: F401
|
| 1489 |
+
get_bucket_paths_info, # noqa: F401
|
| 1490 |
+
get_collection, # noqa: F401
|
| 1491 |
+
get_dataset_leaderboard, # noqa: F401
|
| 1492 |
+
get_dataset_tags, # noqa: F401
|
| 1493 |
+
get_discussion_details, # noqa: F401
|
| 1494 |
+
get_full_repo_name, # noqa: F401
|
| 1495 |
+
get_inference_endpoint, # noqa: F401
|
| 1496 |
+
get_local_safetensors_metadata, # noqa: F401
|
| 1497 |
+
get_model_tags, # noqa: F401
|
| 1498 |
+
get_organization_overview, # noqa: F401
|
| 1499 |
+
get_paths_info, # noqa: F401
|
| 1500 |
+
get_repo_discussions, # noqa: F401
|
| 1501 |
+
get_safetensors_metadata, # noqa: F401
|
| 1502 |
+
get_sharded_safetensors_metadata, # noqa: F401
|
| 1503 |
+
get_space_runtime, # noqa: F401
|
| 1504 |
+
get_space_secrets, # noqa: F401
|
| 1505 |
+
get_space_variables, # noqa: F401
|
| 1506 |
+
get_user_overview, # noqa: F401
|
| 1507 |
+
get_webhook, # noqa: F401
|
| 1508 |
+
get_zero_gpu_quota, # noqa: F401
|
| 1509 |
+
grant_access, # noqa: F401
|
| 1510 |
+
inspect_job, # noqa: F401
|
| 1511 |
+
inspect_scheduled_job, # noqa: F401
|
| 1512 |
+
kernel_info, # noqa: F401
|
| 1513 |
+
list_accepted_access_requests, # noqa: F401
|
| 1514 |
+
list_bucket_tree, # noqa: F401
|
| 1515 |
+
list_buckets, # noqa: F401
|
| 1516 |
+
list_collections, # noqa: F401
|
| 1517 |
+
list_daily_papers, # noqa: F401
|
| 1518 |
+
list_dataset_parquet_files, # noqa: F401
|
| 1519 |
+
list_datasets, # noqa: F401
|
| 1520 |
+
list_inference_catalog, # noqa: F401
|
| 1521 |
+
list_inference_endpoints, # noqa: F401
|
| 1522 |
+
list_inference_endpoints_hardware, # noqa: F401
|
| 1523 |
+
list_jobs, # noqa: F401
|
| 1524 |
+
list_jobs_hardware, # noqa: F401
|
| 1525 |
+
list_lfs_files, # noqa: F401
|
| 1526 |
+
list_liked_repos, # noqa: F401
|
| 1527 |
+
list_models, # noqa: F401
|
| 1528 |
+
list_organization_followers, # noqa: F401
|
| 1529 |
+
list_organization_members, # noqa: F401
|
| 1530 |
+
list_papers, # noqa: F401
|
| 1531 |
+
list_pending_access_requests, # noqa: F401
|
| 1532 |
+
list_rejected_access_requests, # noqa: F401
|
| 1533 |
+
list_repo_commits, # noqa: F401
|
| 1534 |
+
list_repo_files, # noqa: F401
|
| 1535 |
+
list_repo_likers, # noqa: F401
|
| 1536 |
+
list_repo_refs, # noqa: F401
|
| 1537 |
+
list_repo_tree, # noqa: F401
|
| 1538 |
+
list_scheduled_jobs, # noqa: F401
|
| 1539 |
+
list_space_templates, # noqa: F401
|
| 1540 |
+
list_spaces, # noqa: F401
|
| 1541 |
+
list_spaces_hardware, # noqa: F401
|
| 1542 |
+
list_user_followers, # noqa: F401
|
| 1543 |
+
list_user_following, # noqa: F401
|
| 1544 |
+
list_user_repos, # noqa: F401
|
| 1545 |
+
list_webhooks, # noqa: F401
|
| 1546 |
+
merge_pull_request, # noqa: F401
|
| 1547 |
+
model_info, # noqa: F401
|
| 1548 |
+
move_bucket, # noqa: F401
|
| 1549 |
+
move_repo, # noqa: F401
|
| 1550 |
+
paper_info, # noqa: F401
|
| 1551 |
+
parse_local_safetensors_file_metadata, # noqa: F401
|
| 1552 |
+
parse_safetensors_file_metadata, # noqa: F401
|
| 1553 |
+
pause_inference_endpoint, # noqa: F401
|
| 1554 |
+
pause_space, # noqa: F401
|
| 1555 |
+
permanently_delete_lfs_files, # noqa: F401
|
| 1556 |
+
preupload_lfs_files, # noqa: F401
|
| 1557 |
+
read_paper, # noqa: F401
|
| 1558 |
+
reject_access_request, # noqa: F401
|
| 1559 |
+
rename_discussion, # noqa: F401
|
| 1560 |
+
repo_exists, # noqa: F401
|
| 1561 |
+
repo_info, # noqa: F401
|
| 1562 |
+
request_space_hardware, # noqa: F401
|
| 1563 |
+
rerun_job, # noqa: F401
|
| 1564 |
+
resolve_revision, # noqa: F401
|
| 1565 |
+
restart_space, # noqa: F401
|
| 1566 |
+
resume_inference_endpoint, # noqa: F401
|
| 1567 |
+
resume_scheduled_job, # noqa: F401
|
| 1568 |
+
revision_exists, # noqa: F401
|
| 1569 |
+
run_as_future, # noqa: F401
|
| 1570 |
+
run_job, # noqa: F401
|
| 1571 |
+
run_uv_job, # noqa: F401
|
| 1572 |
+
scale_to_zero_inference_endpoint, # noqa: F401
|
| 1573 |
+
search_spaces, # noqa: F401
|
| 1574 |
+
set_space_sleep_time, # noqa: F401
|
| 1575 |
+
set_space_volumes, # noqa: F401
|
| 1576 |
+
space_info, # noqa: F401
|
| 1577 |
+
super_squash_history, # noqa: F401
|
| 1578 |
+
suspend_scheduled_job, # noqa: F401
|
| 1579 |
+
sync_bucket, # noqa: F401
|
| 1580 |
+
sync_job_volume, # noqa: F401
|
| 1581 |
+
trigger_scheduled_job, # noqa: F401
|
| 1582 |
+
unlike, # noqa: F401
|
| 1583 |
+
update_bucket_settings, # noqa: F401
|
| 1584 |
+
update_collection_item, # noqa: F401
|
| 1585 |
+
update_collection_metadata, # noqa: F401
|
| 1586 |
+
update_collection_resource_group, # noqa: F401
|
| 1587 |
+
update_inference_endpoint, # noqa: F401
|
| 1588 |
+
update_job_expose, # noqa: F401
|
| 1589 |
+
update_job_labels, # noqa: F401
|
| 1590 |
+
update_repo_settings, # noqa: F401
|
| 1591 |
+
update_scheduled_job_labels, # noqa: F401
|
| 1592 |
+
update_scheduled_job_schedule, # noqa: F401
|
| 1593 |
+
update_webhook, # noqa: F401
|
| 1594 |
+
upload_attachment, # noqa: F401
|
| 1595 |
+
upload_file, # noqa: F401
|
| 1596 |
+
upload_folder, # noqa: F401
|
| 1597 |
+
verify_repo_checksums, # noqa: F401
|
| 1598 |
+
wait_for_job, # noqa: F401
|
| 1599 |
+
wait_for_space, # noqa: F401
|
| 1600 |
+
whoami, # noqa: F401
|
| 1601 |
+
)
|
| 1602 |
+
from .hf_file_system import (
|
| 1603 |
+
HfFileSystem, # noqa: F401
|
| 1604 |
+
HfFileSystemFile, # noqa: F401
|
| 1605 |
+
HfFileSystemResolvedPath, # noqa: F401
|
| 1606 |
+
HfFileSystemStreamFile, # noqa: F401
|
| 1607 |
+
hffs, # noqa: F401
|
| 1608 |
+
)
|
| 1609 |
+
from .hub_mixin import (
|
| 1610 |
+
ModelHubMixin, # noqa: F401
|
| 1611 |
+
PyTorchModelHubMixin, # noqa: F401
|
| 1612 |
+
)
|
| 1613 |
+
from .inference._client import (
|
| 1614 |
+
InferenceClient, # noqa: F401
|
| 1615 |
+
InferenceTimeoutError, # noqa: F401
|
| 1616 |
+
)
|
| 1617 |
+
from .inference._generated._async_client import AsyncInferenceClient # noqa: F401
|
| 1618 |
+
from .inference._generated.types import (
|
| 1619 |
+
AudioClassificationInput, # noqa: F401
|
| 1620 |
+
AudioClassificationOutputElement, # noqa: F401
|
| 1621 |
+
AudioClassificationOutputTransform, # noqa: F401
|
| 1622 |
+
AudioClassificationParameters, # noqa: F401
|
| 1623 |
+
AudioToAudioInput, # noqa: F401
|
| 1624 |
+
AudioToAudioOutputElement, # noqa: F401
|
| 1625 |
+
AutomaticSpeechRecognitionEarlyStoppingEnum, # noqa: F401
|
| 1626 |
+
AutomaticSpeechRecognitionGenerationParameters, # noqa: F401
|
| 1627 |
+
AutomaticSpeechRecognitionInput, # noqa: F401
|
| 1628 |
+
AutomaticSpeechRecognitionOutput, # noqa: F401
|
| 1629 |
+
AutomaticSpeechRecognitionOutputChunk, # noqa: F401
|
| 1630 |
+
AutomaticSpeechRecognitionParameters, # noqa: F401
|
| 1631 |
+
ChatCompletionInput, # noqa: F401
|
| 1632 |
+
ChatCompletionInputFunctionDefinition, # noqa: F401
|
| 1633 |
+
ChatCompletionInputFunctionName, # noqa: F401
|
| 1634 |
+
ChatCompletionInputGrammarType, # noqa: F401
|
| 1635 |
+
ChatCompletionInputJSONSchema, # noqa: F401
|
| 1636 |
+
ChatCompletionInputMessage, # noqa: F401
|
| 1637 |
+
ChatCompletionInputMessageChunk, # noqa: F401
|
| 1638 |
+
ChatCompletionInputMessageChunkType, # noqa: F401
|
| 1639 |
+
ChatCompletionInputResponseFormatJSONObject, # noqa: F401
|
| 1640 |
+
ChatCompletionInputResponseFormatJSONSchema, # noqa: F401
|
| 1641 |
+
ChatCompletionInputResponseFormatText, # noqa: F401
|
| 1642 |
+
ChatCompletionInputStreamOptions, # noqa: F401
|
| 1643 |
+
ChatCompletionInputTool, # noqa: F401
|
| 1644 |
+
ChatCompletionInputToolCall, # noqa: F401
|
| 1645 |
+
ChatCompletionInputToolChoiceClass, # noqa: F401
|
| 1646 |
+
ChatCompletionInputToolChoiceEnum, # noqa: F401
|
| 1647 |
+
ChatCompletionInputURL, # noqa: F401
|
| 1648 |
+
ChatCompletionOutput, # noqa: F401
|
| 1649 |
+
ChatCompletionOutputComplete, # noqa: F401
|
| 1650 |
+
ChatCompletionOutputFunctionDefinition, # noqa: F401
|
| 1651 |
+
ChatCompletionOutputLogprob, # noqa: F401
|
| 1652 |
+
ChatCompletionOutputLogprobs, # noqa: F401
|
| 1653 |
+
ChatCompletionOutputMessage, # noqa: F401
|
| 1654 |
+
ChatCompletionOutputToolCall, # noqa: F401
|
| 1655 |
+
ChatCompletionOutputTopLogprob, # noqa: F401
|
| 1656 |
+
ChatCompletionOutputUsage, # noqa: F401
|
| 1657 |
+
ChatCompletionStreamOutput, # noqa: F401
|
| 1658 |
+
ChatCompletionStreamOutputChoice, # noqa: F401
|
| 1659 |
+
ChatCompletionStreamOutputDelta, # noqa: F401
|
| 1660 |
+
ChatCompletionStreamOutputDeltaToolCall, # noqa: F401
|
| 1661 |
+
ChatCompletionStreamOutputFunction, # noqa: F401
|
| 1662 |
+
ChatCompletionStreamOutputLogprob, # noqa: F401
|
| 1663 |
+
ChatCompletionStreamOutputLogprobs, # noqa: F401
|
| 1664 |
+
ChatCompletionStreamOutputTopLogprob, # noqa: F401
|
| 1665 |
+
ChatCompletionStreamOutputUsage, # noqa: F401
|
| 1666 |
+
DepthEstimationInput, # noqa: F401
|
| 1667 |
+
DepthEstimationOutput, # noqa: F401
|
| 1668 |
+
DocumentQuestionAnsweringInput, # noqa: F401
|
| 1669 |
+
DocumentQuestionAnsweringInputData, # noqa: F401
|
| 1670 |
+
DocumentQuestionAnsweringOutputElement, # noqa: F401
|
| 1671 |
+
DocumentQuestionAnsweringParameters, # noqa: F401
|
| 1672 |
+
FeatureExtractionInput, # noqa: F401
|
| 1673 |
+
FeatureExtractionInputTruncationDirection, # noqa: F401
|
| 1674 |
+
FillMaskInput, # noqa: F401
|
| 1675 |
+
FillMaskOutputElement, # noqa: F401
|
| 1676 |
+
FillMaskParameters, # noqa: F401
|
| 1677 |
+
ImageClassificationInput, # noqa: F401
|
| 1678 |
+
ImageClassificationOutputElement, # noqa: F401
|
| 1679 |
+
ImageClassificationOutputTransform, # noqa: F401
|
| 1680 |
+
ImageClassificationParameters, # noqa: F401
|
| 1681 |
+
ImageSegmentationInput, # noqa: F401
|
| 1682 |
+
ImageSegmentationOutputElement, # noqa: F401
|
| 1683 |
+
ImageSegmentationParameters, # noqa: F401
|
| 1684 |
+
ImageSegmentationSubtask, # noqa: F401
|
| 1685 |
+
ImageTextToImageInput, # noqa: F401
|
| 1686 |
+
ImageTextToImageOutput, # noqa: F401
|
| 1687 |
+
ImageTextToImageParameters, # noqa: F401
|
| 1688 |
+
ImageTextToImageTargetSize, # noqa: F401
|
| 1689 |
+
ImageTextToVideoInput, # noqa: F401
|
| 1690 |
+
ImageTextToVideoOutput, # noqa: F401
|
| 1691 |
+
ImageTextToVideoParameters, # noqa: F401
|
| 1692 |
+
ImageTextToVideoTargetSize, # noqa: F401
|
| 1693 |
+
ImageToImageInput, # noqa: F401
|
| 1694 |
+
ImageToImageOutput, # noqa: F401
|
| 1695 |
+
ImageToImageParameters, # noqa: F401
|
| 1696 |
+
ImageToImageTargetSize, # noqa: F401
|
| 1697 |
+
ImageToTextEarlyStoppingEnum, # noqa: F401
|
| 1698 |
+
ImageToTextGenerationParameters, # noqa: F401
|
| 1699 |
+
ImageToTextInput, # noqa: F401
|
| 1700 |
+
ImageToTextOutput, # noqa: F401
|
| 1701 |
+
ImageToTextParameters, # noqa: F401
|
| 1702 |
+
ImageToVideoInput, # noqa: F401
|
| 1703 |
+
ImageToVideoOutput, # noqa: F401
|
| 1704 |
+
ImageToVideoParameters, # noqa: F401
|
| 1705 |
+
ImageToVideoTargetSize, # noqa: F401
|
| 1706 |
+
ObjectDetectionBoundingBox, # noqa: F401
|
| 1707 |
+
ObjectDetectionInput, # noqa: F401
|
| 1708 |
+
ObjectDetectionOutputElement, # noqa: F401
|
| 1709 |
+
ObjectDetectionParameters, # noqa: F401
|
| 1710 |
+
Padding, # noqa: F401
|
| 1711 |
+
QuestionAnsweringInput, # noqa: F401
|
| 1712 |
+
QuestionAnsweringInputData, # noqa: F401
|
| 1713 |
+
QuestionAnsweringOutputElement, # noqa: F401
|
| 1714 |
+
QuestionAnsweringParameters, # noqa: F401
|
| 1715 |
+
SentenceSimilarityInput, # noqa: F401
|
| 1716 |
+
SentenceSimilarityInputData, # noqa: F401
|
| 1717 |
+
SummarizationInput, # noqa: F401
|
| 1718 |
+
SummarizationOutput, # noqa: F401
|
| 1719 |
+
SummarizationParameters, # noqa: F401
|
| 1720 |
+
SummarizationTruncationStrategy, # noqa: F401
|
| 1721 |
+
TableQuestionAnsweringInput, # noqa: F401
|
| 1722 |
+
TableQuestionAnsweringInputData, # noqa: F401
|
| 1723 |
+
TableQuestionAnsweringOutputElement, # noqa: F401
|
| 1724 |
+
TableQuestionAnsweringParameters, # noqa: F401
|
| 1725 |
+
Text2TextGenerationInput, # noqa: F401
|
| 1726 |
+
Text2TextGenerationOutput, # noqa: F401
|
| 1727 |
+
Text2TextGenerationParameters, # noqa: F401
|
| 1728 |
+
Text2TextGenerationTruncationStrategy, # noqa: F401
|
| 1729 |
+
TextClassificationInput, # noqa: F401
|
| 1730 |
+
TextClassificationOutputElement, # noqa: F401
|
| 1731 |
+
TextClassificationOutputTransform, # noqa: F401
|
| 1732 |
+
TextClassificationParameters, # noqa: F401
|
| 1733 |
+
TextGenerationInput, # noqa: F401
|
| 1734 |
+
TextGenerationInputGenerateParameters, # noqa: F401
|
| 1735 |
+
TextGenerationInputGrammarType, # noqa: F401
|
| 1736 |
+
TextGenerationOutput, # noqa: F401
|
| 1737 |
+
TextGenerationOutputBestOfSequence, # noqa: F401
|
| 1738 |
+
TextGenerationOutputDetails, # noqa: F401
|
| 1739 |
+
TextGenerationOutputFinishReason, # noqa: F401
|
| 1740 |
+
TextGenerationOutputPrefillToken, # noqa: F401
|
| 1741 |
+
TextGenerationOutputToken, # noqa: F401
|
| 1742 |
+
TextGenerationStreamOutput, # noqa: F401
|
| 1743 |
+
TextGenerationStreamOutputStreamDetails, # noqa: F401
|
| 1744 |
+
TextGenerationStreamOutputToken, # noqa: F401
|
| 1745 |
+
TextToAudioEarlyStoppingEnum, # noqa: F401
|
| 1746 |
+
TextToAudioGenerationParameters, # noqa: F401
|
| 1747 |
+
TextToAudioInput, # noqa: F401
|
| 1748 |
+
TextToAudioOutput, # noqa: F401
|
| 1749 |
+
TextToAudioParameters, # noqa: F401
|
| 1750 |
+
TextToImageInput, # noqa: F401
|
| 1751 |
+
TextToImageOutput, # noqa: F401
|
| 1752 |
+
TextToImageParameters, # noqa: F401
|
| 1753 |
+
TextToSpeechEarlyStoppingEnum, # noqa: F401
|
| 1754 |
+
TextToSpeechGenerationParameters, # noqa: F401
|
| 1755 |
+
TextToSpeechInput, # noqa: F401
|
| 1756 |
+
TextToSpeechOutput, # noqa: F401
|
| 1757 |
+
TextToSpeechParameters, # noqa: F401
|
| 1758 |
+
TextToVideoInput, # noqa: F401
|
| 1759 |
+
TextToVideoOutput, # noqa: F401
|
| 1760 |
+
TextToVideoParameters, # noqa: F401
|
| 1761 |
+
TokenClassificationAggregationStrategy, # noqa: F401
|
| 1762 |
+
TokenClassificationInput, # noqa: F401
|
| 1763 |
+
TokenClassificationOutputElement, # noqa: F401
|
| 1764 |
+
TokenClassificationParameters, # noqa: F401
|
| 1765 |
+
TranslationInput, # noqa: F401
|
| 1766 |
+
TranslationOutput, # noqa: F401
|
| 1767 |
+
TranslationParameters, # noqa: F401
|
| 1768 |
+
TranslationTruncationStrategy, # noqa: F401
|
| 1769 |
+
TypeEnum, # noqa: F401
|
| 1770 |
+
VideoClassificationInput, # noqa: F401
|
| 1771 |
+
VideoClassificationOutputElement, # noqa: F401
|
| 1772 |
+
VideoClassificationOutputTransform, # noqa: F401
|
| 1773 |
+
VideoClassificationParameters, # noqa: F401
|
| 1774 |
+
VisualQuestionAnsweringInput, # noqa: F401
|
| 1775 |
+
VisualQuestionAnsweringInputData, # noqa: F401
|
| 1776 |
+
VisualQuestionAnsweringOutputElement, # noqa: F401
|
| 1777 |
+
VisualQuestionAnsweringParameters, # noqa: F401
|
| 1778 |
+
ZeroShotClassificationInput, # noqa: F401
|
| 1779 |
+
ZeroShotClassificationOutputElement, # noqa: F401
|
| 1780 |
+
ZeroShotClassificationParameters, # noqa: F401
|
| 1781 |
+
ZeroShotImageClassificationInput, # noqa: F401
|
| 1782 |
+
ZeroShotImageClassificationOutputElement, # noqa: F401
|
| 1783 |
+
ZeroShotImageClassificationParameters, # noqa: F401
|
| 1784 |
+
ZeroShotObjectDetectionBoundingBox, # noqa: F401
|
| 1785 |
+
ZeroShotObjectDetectionInput, # noqa: F401
|
| 1786 |
+
ZeroShotObjectDetectionOutputElement, # noqa: F401
|
| 1787 |
+
ZeroShotObjectDetectionParameters, # noqa: F401
|
| 1788 |
+
)
|
| 1789 |
+
from .inference._mcp.agent import Agent # noqa: F401
|
| 1790 |
+
from .inference._mcp.mcp_client import MCPClient # noqa: F401
|
| 1791 |
+
from .repocard import (
|
| 1792 |
+
DatasetCard, # noqa: F401
|
| 1793 |
+
ModelCard, # noqa: F401
|
| 1794 |
+
RepoCard, # noqa: F401
|
| 1795 |
+
SpaceCard, # noqa: F401
|
| 1796 |
+
metadata_eval_result, # noqa: F401
|
| 1797 |
+
metadata_load, # noqa: F401
|
| 1798 |
+
metadata_save, # noqa: F401
|
| 1799 |
+
metadata_update, # noqa: F401
|
| 1800 |
+
)
|
| 1801 |
+
from .repocard_data import (
|
| 1802 |
+
CardData, # noqa: F401
|
| 1803 |
+
DatasetCardData, # noqa: F401
|
| 1804 |
+
EvalResult, # noqa: F401
|
| 1805 |
+
ModelCardData, # noqa: F401
|
| 1806 |
+
SpaceCardData, # noqa: F401
|
| 1807 |
+
)
|
| 1808 |
+
from .serialization import (
|
| 1809 |
+
StateDictSplit, # noqa: F401
|
| 1810 |
+
get_torch_storage_id, # noqa: F401
|
| 1811 |
+
get_torch_storage_size, # noqa: F401
|
| 1812 |
+
load_state_dict_from_file, # noqa: F401
|
| 1813 |
+
load_torch_model, # noqa: F401
|
| 1814 |
+
save_torch_model, # noqa: F401
|
| 1815 |
+
save_torch_state_dict, # noqa: F401
|
| 1816 |
+
split_state_dict_into_shards_factory, # noqa: F401
|
| 1817 |
+
split_torch_state_dict_into_shards, # noqa: F401
|
| 1818 |
+
)
|
| 1819 |
+
from .serialization._dduf import (
|
| 1820 |
+
DDUFEntry, # noqa: F401
|
| 1821 |
+
export_entries_as_dduf, # noqa: F401
|
| 1822 |
+
export_folder_as_dduf, # noqa: F401
|
| 1823 |
+
read_dduf_file, # noqa: F401
|
| 1824 |
+
)
|
| 1825 |
+
from .utils import (
|
| 1826 |
+
ASYNC_CLIENT_FACTORY_T, # noqa: F401
|
| 1827 |
+
CLIENT_FACTORY_T, # noqa: F401
|
| 1828 |
+
CachedFileInfo, # noqa: F401
|
| 1829 |
+
CachedIncompleteFileInfo, # noqa: F401
|
| 1830 |
+
CachedRepoInfo, # noqa: F401
|
| 1831 |
+
CachedRevisionInfo, # noqa: F401
|
| 1832 |
+
CacheNotFound, # noqa: F401
|
| 1833 |
+
CorruptedCacheException, # noqa: F401
|
| 1834 |
+
DeleteCacheStrategy, # noqa: F401
|
| 1835 |
+
HFCacheInfo, # noqa: F401
|
| 1836 |
+
HfUri, # noqa: F401
|
| 1837 |
+
cached_assets_path, # noqa: F401
|
| 1838 |
+
close_session, # noqa: F401
|
| 1839 |
+
dump_environment_info, # noqa: F401
|
| 1840 |
+
get_async_session, # noqa: F401
|
| 1841 |
+
get_session, # noqa: F401
|
| 1842 |
+
get_token, # noqa: F401
|
| 1843 |
+
hf_raise_for_status, # noqa: F401
|
| 1844 |
+
logging, # noqa: F401
|
| 1845 |
+
parse_hf_uri, # noqa: F401
|
| 1846 |
+
scan_cache_dir, # noqa: F401
|
| 1847 |
+
set_async_client_factory, # noqa: F401
|
| 1848 |
+
set_client_factory, # noqa: F401
|
| 1849 |
+
)
|
.venv/lib/python3.12/site-packages/huggingface_hub/_bucket_live_follow.py
ADDED
|
@@ -0,0 +1,459 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Live-following of file changes in a bucket.
|
| 15 |
+
|
| 16 |
+
The Hub exposes a server-sent events feed of per-file changes for buckets:
|
| 17 |
+
|
| 18 |
+
```
|
| 19 |
+
GET /api/buckets/{bucket_id}/events?cursor=<opaque> | ?since=<ISO8601>
|
| 20 |
+
Accept: text/event-stream
|
| 21 |
+
```
|
| 22 |
+
|
| 23 |
+
A consumer can keep its view of a bucket fresh by applying the batches as they happen instead of re-listing
|
| 24 |
+
directories. This module implements the client side of that feed:
|
| 25 |
+
|
| 26 |
+
- [`parse_follow_event`] turns a raw SSE event into a typed event. Unknown or malformed events are dropped so
|
| 27 |
+
the Hub can add event types without breaking older clients.
|
| 28 |
+
- [`BucketFollower`] is a daemon thread owning one (re)connecting stream for one bucket. It maintains the
|
| 29 |
+
resume point, reconnects with exponential backoff, and hands the batches over to callbacks provided by the
|
| 30 |
+
caller (see [`HfFileSystem`]).
|
| 31 |
+
|
| 32 |
+
The feed is best-effort by design: when it cannot be followed (deployment where live-follow is disabled, token
|
| 33 |
+
without access to the bucket), the follower stops and the consumer is left with its default behavior.
|
| 34 |
+
|
| 35 |
+
Event vocabulary:
|
| 36 |
+
|
| 37 |
+
| event | payload | meaning |
|
| 38 |
+
| ----------- | -------------------------------------- | --------------------------------------------------------------------- |
|
| 39 |
+
| `ready` | `{cursor?}` | replay is done, the stream now follows live changes |
|
| 40 |
+
| `changes` | `{cursor, changes: [{path, op, ...}]}` | batch of per-file changes; `cursor` resumes strictly after the batch |
|
| 41 |
+
| `reset` | `{reason}` | resume point older than the replay buffer: reconcile and re-subscribe |
|
| 42 |
+
| `reconnect` | `{cursor?}` | server-directed end of stream (pod rotation, shutdown,...) |
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
import json
|
| 46 |
+
import threading
|
| 47 |
+
import weakref
|
| 48 |
+
from collections.abc import Callable, Iterator
|
| 49 |
+
from dataclasses import dataclass, field
|
| 50 |
+
from datetime import datetime
|
| 51 |
+
from typing import Any, Literal, Union
|
| 52 |
+
|
| 53 |
+
import httpx2
|
| 54 |
+
|
| 55 |
+
from . import logging
|
| 56 |
+
from ._hot_reload.sse_client import SSEClient
|
| 57 |
+
from .utils import build_hf_headers, get_session, hf_raise_for_status, parse_datetime
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
logger = logging.get_logger(__name__)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
STREAM_READ_TIMEOUT = 90.0
|
| 64 |
+
"""Seconds without a single byte (the server pings every ~30s) before a stream is considered dead."""
|
| 65 |
+
|
| 66 |
+
CONNECT_TIMEOUT = 10.0
|
| 67 |
+
RETRY_BASE_DELAY = 10.0
|
| 68 |
+
RETRY_MAX_DELAY = 80.0
|
| 69 |
+
RECONNECT_MIN_DELAY = 1.0
|
| 70 |
+
MAX_SESSIONS_WITHOUT_READY = 3
|
| 71 |
+
|
| 72 |
+
# Statuses meaning the feed cannot be followed for this bucket, as opposed to "retry later": not served by
|
| 73 |
+
# this deployment (404, 501) or refused for this token (401, 403).
|
| 74 |
+
_UNFOLLOWABLE_STATUS_CODES = (401, 403, 404, 501)
|
| 75 |
+
|
| 76 |
+
# Live-follow threads and the consumers they notify, keyed by (endpoint, token, bucket_id). Shared because
|
| 77 |
+
# `HfFileSystem` creates (and keeps) one instance per thread.
|
| 78 |
+
BUCKET_FOLLOWERS: dict[tuple[str, bool | str | None, str], tuple["BucketFollower", weakref.WeakValueDictionary]] = {}
|
| 79 |
+
BUCKET_FOLLOWERS_LOCK = threading.Lock()
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class BucketEventsUnavailable(Exception):
|
| 83 |
+
"""The live-follow feed cannot be followed for this bucket: do not retry."""
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
@dataclass
|
| 87 |
+
class BucketFileChange:
|
| 88 |
+
"""
|
| 89 |
+
A single file change reported by the live-follow feed of a bucket.
|
| 90 |
+
|
| 91 |
+
Only `path` and `op` are always set: an `update` carries only the fields that changed, so a field left to
|
| 92 |
+
`None` means "unchanged" (or, for `xet_hash`, possibly "not readable with this token") and never "cleared".
|
| 93 |
+
|
| 94 |
+
Args:
|
| 95 |
+
path (`str`):
|
| 96 |
+
Path of the file in the bucket.
|
| 97 |
+
op (`Literal["add", "update", "delete"]`):
|
| 98 |
+
What happened to the file.
|
| 99 |
+
size (`int`, *optional*):
|
| 100 |
+
Size of the file in bytes, when reported.
|
| 101 |
+
xet_hash (`str`, *optional*):
|
| 102 |
+
Xet hash of the file, when reported.
|
| 103 |
+
uploaded_at (`datetime`, *optional*):
|
| 104 |
+
Upload instant, set on every add and re-upload.
|
| 105 |
+
mtime (`datetime`, *optional*):
|
| 106 |
+
Client-provided modification time, when reported.
|
| 107 |
+
"""
|
| 108 |
+
|
| 109 |
+
path: str
|
| 110 |
+
op: Literal["add", "update", "delete"]
|
| 111 |
+
size: int | None = None
|
| 112 |
+
xet_hash: str | None = None
|
| 113 |
+
uploaded_at: datetime | None = None
|
| 114 |
+
mtime: datetime | None = None
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
@dataclass
|
| 118 |
+
class _Ready:
|
| 119 |
+
cursor: str | None
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
@dataclass
|
| 123 |
+
class _Changes:
|
| 124 |
+
cursor: str
|
| 125 |
+
changes: list[BucketFileChange] = field(default_factory=list)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
@dataclass
|
| 129 |
+
class _Reset:
|
| 130 |
+
pass
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
@dataclass
|
| 134 |
+
class _Reconnect:
|
| 135 |
+
cursor: str | None
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
_FollowEvent = Union[_Ready, _Changes, _Reset, _Reconnect]
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def _parse_datetime(value: Any) -> datetime | None:
|
| 142 |
+
return parse_datetime(value) if isinstance(value, str) and value else None
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def parse_follow_event(name: str, data: str) -> _FollowEvent | None:
|
| 146 |
+
"""
|
| 147 |
+
Parse a raw live-follow event into a typed event.
|
| 148 |
+
|
| 149 |
+
Args:
|
| 150 |
+
name (`str`):
|
| 151 |
+
Value of the `event:` field: `ready`, `changes`, `reset` or `reconnect`.
|
| 152 |
+
data (`str`):
|
| 153 |
+
JSON payload of the `data:` field (may be empty).
|
| 154 |
+
|
| 155 |
+
Returns:
|
| 156 |
+
`Any` | `None`: The parsed event, or `None` when it must be ignored (unknown event name or malformed
|
| 157 |
+
payload).
|
| 158 |
+
"""
|
| 159 |
+
try:
|
| 160 |
+
payload = json.loads(data) if data.strip() else {}
|
| 161 |
+
except json.JSONDecodeError:
|
| 162 |
+
logger.debug("live-follow: ignoring malformed %r payload: %s", name, data[:200])
|
| 163 |
+
return None
|
| 164 |
+
if not isinstance(payload, dict):
|
| 165 |
+
logger.debug("live-follow: ignoring %r payload that is not an object: %s", name, data[:200])
|
| 166 |
+
return None
|
| 167 |
+
|
| 168 |
+
match name:
|
| 169 |
+
case "ready":
|
| 170 |
+
cursor = payload.get("cursor")
|
| 171 |
+
return _Ready(cursor=cursor if isinstance(cursor, str) else None)
|
| 172 |
+
|
| 173 |
+
case "changes":
|
| 174 |
+
cursor, raw_changes = payload.get("cursor"), payload.get("changes")
|
| 175 |
+
if not isinstance(cursor, str) or not isinstance(raw_changes, list):
|
| 176 |
+
logger.debug("live-follow: ignoring 'changes' event without cursor/changes: %s", data[:200])
|
| 177 |
+
return None
|
| 178 |
+
changes = []
|
| 179 |
+
for item in raw_changes:
|
| 180 |
+
if not isinstance(item, dict) or item.get("op") not in ("add", "update", "delete"):
|
| 181 |
+
continue
|
| 182 |
+
changes.append(
|
| 183 |
+
BucketFileChange(
|
| 184 |
+
path=item.get("path", ""),
|
| 185 |
+
op=item["op"],
|
| 186 |
+
size=item.get("size"),
|
| 187 |
+
xet_hash=item.get("xetHash"),
|
| 188 |
+
uploaded_at=_parse_datetime(item.get("uploadedAt")),
|
| 189 |
+
mtime=_parse_datetime(item.get("mtime")),
|
| 190 |
+
)
|
| 191 |
+
)
|
| 192 |
+
return _Changes(cursor=cursor, changes=changes)
|
| 193 |
+
|
| 194 |
+
case "reset":
|
| 195 |
+
return _Reset()
|
| 196 |
+
|
| 197 |
+
case "reconnect":
|
| 198 |
+
cursor = payload.get("cursor")
|
| 199 |
+
return _Reconnect(cursor=cursor if isinstance(cursor, str) else None)
|
| 200 |
+
|
| 201 |
+
case _:
|
| 202 |
+
logger.debug("live-follow: ignoring unknown event type %r", name)
|
| 203 |
+
return None
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
# A resume point is either absent (reconcile then probe a fresh one), a cursor to resume strictly after, an
|
| 207 |
+
# ISO8601 instant to replay changes from, or "live" (only the changes coming next, with no replay at all).
|
| 208 |
+
# The three forms are also the steps to fall back through when the server refuses a request (HTTP 400).
|
| 209 |
+
ResumePoint = tuple[Literal["cursor", "since", "live"], str]
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def _resume_params(resume: ResumePoint | None) -> dict[str, str]:
|
| 213 |
+
match resume:
|
| 214 |
+
case ("cursor", cursor):
|
| 215 |
+
return {"cursor": cursor}
|
| 216 |
+
case ("since", since) if since:
|
| 217 |
+
return {"since": since}
|
| 218 |
+
case _:
|
| 219 |
+
return {}
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def _iter_until(chunks: Iterator[bytes], should_stop: Callable[[], bool]) -> Iterator[bytes]:
|
| 223 |
+
"""
|
| 224 |
+
Pass response chunks through until `should_stop` returns true.
|
| 225 |
+
|
| 226 |
+
The check runs when a chunk arrives, so a stream carrying nothing to parse is abandoned at its next
|
| 227 |
+
keep-alive comment instead of being read until the server ends it.
|
| 228 |
+
"""
|
| 229 |
+
for chunk in chunks:
|
| 230 |
+
if should_stop():
|
| 231 |
+
return
|
| 232 |
+
yield chunk
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def _follow_events(
|
| 236 |
+
endpoint: str,
|
| 237 |
+
bucket_id: str,
|
| 238 |
+
token: bool | str | None,
|
| 239 |
+
resume: ResumePoint | None,
|
| 240 |
+
should_stop: Callable[[], bool],
|
| 241 |
+
) -> Iterator[_FollowEvent]:
|
| 242 |
+
"""
|
| 243 |
+
Open a single live-follow session and yield the parsed events until the stream ends.
|
| 244 |
+
|
| 245 |
+
Ends silently on EOF, on read timeout and when `should_stop` returns true. Raises
|
| 246 |
+
[`BucketEventsUnavailable`] if the feed cannot be followed and [`~utils.HfHubHTTPError`] for anything else
|
| 247 |
+
the caller must decide about.
|
| 248 |
+
"""
|
| 249 |
+
timeout = httpx2.Timeout(connect=CONNECT_TIMEOUT, read=STREAM_READ_TIMEOUT, write=CONNECT_TIMEOUT, pool=10.0)
|
| 250 |
+
with get_session().stream(
|
| 251 |
+
"GET",
|
| 252 |
+
f"{endpoint}/api/buckets/{bucket_id}/events",
|
| 253 |
+
headers={**build_hf_headers(token=token), "accept": "text/event-stream"},
|
| 254 |
+
params=_resume_params(resume),
|
| 255 |
+
timeout=timeout,
|
| 256 |
+
) as response:
|
| 257 |
+
if response.status_code in _UNFOLLOWABLE_STATUS_CODES:
|
| 258 |
+
raise BucketEventsUnavailable(f"status {response.status_code} on {response.url}")
|
| 259 |
+
if not (response.headers.get("content-type") or "").startswith("text/event-stream"):
|
| 260 |
+
# Raises for error statuses (400, 401,...), otherwise this is not an event stream at all.
|
| 261 |
+
hf_raise_for_status(response)
|
| 262 |
+
raise BucketEventsUnavailable(f"unexpected content-type on {response.url}")
|
| 263 |
+
hf_raise_for_status(response)
|
| 264 |
+
|
| 265 |
+
# The vendored SSE client handles chunk-split lines, CRLF endings, the keep-alive comment lines and
|
| 266 |
+
# several events per chunk. It only dispatches events carrying a `data:` field, which the feed always
|
| 267 |
+
# sends (an empty payload comes as `data: {}`).
|
| 268 |
+
try:
|
| 269 |
+
for event in SSEClient(_iter_until(response.iter_bytes(), should_stop)).events():
|
| 270 |
+
parsed = parse_follow_event(event.event, event.data)
|
| 271 |
+
if parsed is not None:
|
| 272 |
+
yield parsed
|
| 273 |
+
except httpx2.HTTPError as e:
|
| 274 |
+
# Read timeout, connection reset,... indistinguishable from a server-side end of stream.
|
| 275 |
+
logger.debug("live-follow: stream error on bucket %s (%s)", bucket_id, e)
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
class _Backoff:
|
| 279 |
+
"""Exponential backoff, capped, reset by the first healthy session."""
|
| 280 |
+
|
| 281 |
+
def __init__(self, base: float, max_delay: float) -> None:
|
| 282 |
+
self._base = base
|
| 283 |
+
self.max_delay = max_delay
|
| 284 |
+
self._attempt = 0
|
| 285 |
+
|
| 286 |
+
def next(self) -> float:
|
| 287 |
+
delay = min(self._base * 2**self._attempt, self.max_delay)
|
| 288 |
+
self._attempt += 1
|
| 289 |
+
return delay
|
| 290 |
+
|
| 291 |
+
def reset(self) -> None:
|
| 292 |
+
self._attempt = 0
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def _retry_after(e: Exception) -> float | None:
|
| 296 |
+
"""The server `Retry-After` hint (rate limiting,...) if it sent one."""
|
| 297 |
+
response = getattr(e, "response", None)
|
| 298 |
+
hint = response.headers.get("retry-after") if response is not None else None
|
| 299 |
+
try:
|
| 300 |
+
return float(hint) if hint is not None else None
|
| 301 |
+
except ValueError:
|
| 302 |
+
return None
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
def _status_code(e: Exception) -> int | None:
|
| 306 |
+
response = getattr(e, "response", None)
|
| 307 |
+
return response.status_code if response is not None else None
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
class BucketFollower(threading.Thread):
|
| 311 |
+
"""
|
| 312 |
+
Daemon thread keeping one bucket's event stream alive and reporting the changes it carries.
|
| 313 |
+
|
| 314 |
+
One instance owns exactly one stream, for one bucket. Batches are handed over to `on_changes`. Whenever no
|
| 315 |
+
usable resume point is known (first session, or the server cannot replay that far back), `on_reconcile` is
|
| 316 |
+
called first: the consumer is expected to drop what it holds for that bucket, so that the replay that
|
| 317 |
+
follows starts from a fresh state. The thread ends on its own when `is_alive` turns false, when the feed is
|
| 318 |
+
not served, or after too many sessions ending before they were even ready. It keeps no strong reference to
|
| 319 |
+
its consumer, which can therefore be garbage collected while the thread is running.
|
| 320 |
+
|
| 321 |
+
Args:
|
| 322 |
+
endpoint (`str`):
|
| 323 |
+
Endpoint of the Hub.
|
| 324 |
+
bucket_id (`str`):
|
| 325 |
+
ID of the bucket to follow (e.g. `"username/my-bucket"`).
|
| 326 |
+
token (`bool` or `str`, *optional*):
|
| 327 |
+
Token used to consume the feed, resolved again at every (re)connect.
|
| 328 |
+
on_changes (`Callable[[list[BucketFileChange]], None]`):
|
| 329 |
+
Called with each batch of changes received from the feed.
|
| 330 |
+
on_reconcile (`Callable[[], None]`):
|
| 331 |
+
Called before (re)subscribing without a usable cursor.
|
| 332 |
+
is_alive (`Callable[[], bool]`):
|
| 333 |
+
Whether the consumer still cares about the updates. Checked before every session and whenever the
|
| 334 |
+
stream sends anything, so a stream carrying no change is abandoned within one keep-alive.
|
| 335 |
+
"""
|
| 336 |
+
|
| 337 |
+
def __init__(
|
| 338 |
+
self,
|
| 339 |
+
*,
|
| 340 |
+
endpoint: str,
|
| 341 |
+
bucket_id: str,
|
| 342 |
+
token: bool | str | None = None,
|
| 343 |
+
on_changes: Callable[[list[BucketFileChange]], None],
|
| 344 |
+
on_reconcile: Callable[[], None],
|
| 345 |
+
is_alive: Callable[[], bool],
|
| 346 |
+
) -> None:
|
| 347 |
+
super().__init__(daemon=True, name=f"hf-bucket-live-follow-{bucket_id}")
|
| 348 |
+
self.bucket_id = bucket_id
|
| 349 |
+
# Whether at least one session reached the `ready` state, i.e. the feed is actually being followed.
|
| 350 |
+
self.subscribed = False
|
| 351 |
+
self._endpoint = endpoint
|
| 352 |
+
self._token = token
|
| 353 |
+
self._on_changes = on_changes
|
| 354 |
+
self._on_reconcile = on_reconcile
|
| 355 |
+
self._is_alive = is_alive
|
| 356 |
+
self._stop_event = threading.Event()
|
| 357 |
+
self._resume: ResumePoint | None = None
|
| 358 |
+
|
| 359 |
+
def stop(self) -> None:
|
| 360 |
+
"""Ask the follower to stop. Returns before the thread ends: it stops once the stream yields or times out."""
|
| 361 |
+
self._stop_event.set()
|
| 362 |
+
|
| 363 |
+
def _should_stop(self) -> bool:
|
| 364 |
+
"""Whether to give up: explicitly asked to, or the consumer holding this follower is gone."""
|
| 365 |
+
return self._stop_event.is_set() or not self._is_alive()
|
| 366 |
+
|
| 367 |
+
def run(self) -> None:
|
| 368 |
+
backoff = _Backoff(RETRY_BASE_DELAY, RETRY_MAX_DELAY)
|
| 369 |
+
sessions_without_ready = 0
|
| 370 |
+
while not self._should_stop():
|
| 371 |
+
if self._resume is None:
|
| 372 |
+
# No usable resume point: let the consumer drop its view of the bucket, then resume from its
|
| 373 |
+
# `updatedAt` so any change landing after that instant is replayed by the server.
|
| 374 |
+
self._resume = ("since", self._fetch_updated_at())
|
| 375 |
+
self._on_reconcile()
|
| 376 |
+
try:
|
| 377 |
+
healthy = self._follow_once()
|
| 378 |
+
except BucketEventsUnavailable as e:
|
| 379 |
+
logger.warning(f"Cannot live-follow bucket '{self.bucket_id}' ({e}): its listings won't be refreshed.")
|
| 380 |
+
return
|
| 381 |
+
except Exception as e:
|
| 382 |
+
if _status_code(e) == 400:
|
| 383 |
+
# The server refused the request itself. Step the resume point back one notch (cheaper
|
| 384 |
+
# than a full reconcile) and give up once even a bare, live-only request is refused.
|
| 385 |
+
match self._resume:
|
| 386 |
+
case ("cursor", _):
|
| 387 |
+
self._resume = ("since", self._fetch_updated_at())
|
| 388 |
+
case ("since", _):
|
| 389 |
+
self._resume = ("live", "")
|
| 390 |
+
case _:
|
| 391 |
+
logger.debug("live-follow: giving up on bucket %s (%s)", self.bucket_id, e)
|
| 392 |
+
return
|
| 393 |
+
delay = _retry_after(e)
|
| 394 |
+
self._sleep(min(delay, backoff.max_delay) if delay is not None else backoff.next())
|
| 395 |
+
continue
|
| 396 |
+
|
| 397 |
+
if healthy:
|
| 398 |
+
backoff.reset()
|
| 399 |
+
sessions_without_ready = 0
|
| 400 |
+
self._sleep(RECONNECT_MIN_DELAY)
|
| 401 |
+
else:
|
| 402 |
+
sessions_without_ready += 1
|
| 403 |
+
if sessions_without_ready >= MAX_SESSIONS_WITHOUT_READY:
|
| 404 |
+
logger.debug(
|
| 405 |
+
"live-follow: %s sessions for bucket %s ended before 'ready'; not following it",
|
| 406 |
+
sessions_without_ready,
|
| 407 |
+
self.bucket_id,
|
| 408 |
+
)
|
| 409 |
+
return
|
| 410 |
+
self._sleep(backoff.next())
|
| 411 |
+
|
| 412 |
+
def _follow_once(self) -> bool:
|
| 413 |
+
"""
|
| 414 |
+
Consume a single stream. Returns whether the session was healthy, i.e. whether it reached the `ready`
|
| 415 |
+
state (a server-directed `reconnect` or `reset` counts as healthy).
|
| 416 |
+
"""
|
| 417 |
+
ready = False
|
| 418 |
+
for event in _follow_events(self._endpoint, self.bucket_id, self._token, self._resume, self._should_stop):
|
| 419 |
+
match event:
|
| 420 |
+
case _Ready(cursor=cursor):
|
| 421 |
+
# An absent cursor means the feed has seen no change yet: keep the current resume point.
|
| 422 |
+
if cursor is not None:
|
| 423 |
+
self._resume = ("cursor", cursor)
|
| 424 |
+
ready = True
|
| 425 |
+
self.subscribed = True
|
| 426 |
+
case _Changes(cursor=cursor, changes=changes):
|
| 427 |
+
# On replay, `changes` batches arrive *before* the `ready` event.
|
| 428 |
+
if changes:
|
| 429 |
+
self._on_changes(changes)
|
| 430 |
+
self._resume = ("cursor", cursor)
|
| 431 |
+
case _Reset():
|
| 432 |
+
# Resume point older than the server's replay buffer: reconcile and resume from `since=`.
|
| 433 |
+
self._resume = None
|
| 434 |
+
return True
|
| 435 |
+
case _Reconnect(cursor=cursor):
|
| 436 |
+
if cursor is not None:
|
| 437 |
+
self._resume = ("cursor", cursor)
|
| 438 |
+
return True
|
| 439 |
+
if self._should_stop():
|
| 440 |
+
return ready
|
| 441 |
+
return ready
|
| 442 |
+
|
| 443 |
+
def _fetch_updated_at(self) -> str:
|
| 444 |
+
"""Get the instant (ISO8601) to resume from. Empty string if it cannot be probed."""
|
| 445 |
+
try:
|
| 446 |
+
response = get_session().get(
|
| 447 |
+
f"{self._endpoint}/api/buckets/{self.bucket_id}",
|
| 448 |
+
headers=build_hf_headers(token=self._token),
|
| 449 |
+
timeout=CONNECT_TIMEOUT,
|
| 450 |
+
)
|
| 451 |
+
hf_raise_for_status(response)
|
| 452 |
+
updated_at = response.json().get("updatedAt")
|
| 453 |
+
return updated_at if isinstance(updated_at, str) else ""
|
| 454 |
+
except Exception as e:
|
| 455 |
+
logger.debug("live-follow: cannot probe updatedAt for bucket %s (%s)", self.bucket_id, e)
|
| 456 |
+
return ""
|
| 457 |
+
|
| 458 |
+
def _sleep(self, delay: float) -> None:
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026-present, the HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Shared logic for bucket operations.
|
| 15 |
+
|
| 16 |
+
This module contains the core buckets logic used by both the CLI and the Python API.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import fnmatch
|
| 20 |
+
import json
|
| 21 |
+
import mimetypes
|
| 22 |
+
import os
|
| 23 |
+
import stat
|
| 24 |
+
import sys
|
| 25 |
+
import time
|
| 26 |
+
from collections.abc import Iterator
|
| 27 |
+
from dataclasses import dataclass, field
|
| 28 |
+
from datetime import datetime, timezone
|
| 29 |
+
from pathlib import Path
|
| 30 |
+
from typing import TYPE_CHECKING, Any, Literal
|
| 31 |
+
|
| 32 |
+
from . import constants, logging
|
| 33 |
+
from ._local_folder import _validate_relative_filename
|
| 34 |
+
from .errors import BucketNotFoundError
|
| 35 |
+
from .utils import (
|
| 36 |
+
HfUri,
|
| 37 |
+
StatusLine,
|
| 38 |
+
XetFileData,
|
| 39 |
+
disable_progress_bars,
|
| 40 |
+
enable_progress_bars,
|
| 41 |
+
parse_datetime,
|
| 42 |
+
parse_hf_uri,
|
| 43 |
+
)
|
| 44 |
+
from .utils._hf_uris import _looks_like_hf_url
|
| 45 |
+
from .utils._paths import _normalize_separators
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
if TYPE_CHECKING:
|
| 49 |
+
from .hf_api import HfApi
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
logger = logging.get_logger(__name__)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
BUCKET_PREFIX = "hf://buckets/"
|
| 56 |
+
_SYNC_TIME_WINDOW_MS = 1000 # 1s safety-window for file modification time comparisons
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
# =============================================================================
|
| 60 |
+
# Bucket data structures
|
| 61 |
+
# =============================================================================
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
@dataclass
|
| 65 |
+
class BucketInfo:
|
| 66 |
+
"""
|
| 67 |
+
Contains information about a bucket on the Hub. This object is returned by [`bucket_info`] and [`list_buckets`].
|
| 68 |
+
|
| 69 |
+
Attributes:
|
| 70 |
+
id (`str`):
|
| 71 |
+
ID of the bucket.
|
| 72 |
+
private (`bool`):
|
| 73 |
+
Is the bucket private.
|
| 74 |
+
created_at (`datetime`):
|
| 75 |
+
Date of creation of the bucket on the Hub.
|
| 76 |
+
size (`int`):
|
| 77 |
+
Size of the bucket in bytes.
|
| 78 |
+
total_files (`int`):
|
| 79 |
+
Total number of files in the bucket.
|
| 80 |
+
"""
|
| 81 |
+
|
| 82 |
+
id: str
|
| 83 |
+
private: bool
|
| 84 |
+
created_at: datetime
|
| 85 |
+
size: int
|
| 86 |
+
total_files: int
|
| 87 |
+
|
| 88 |
+
def __init__(self, **kwargs):
|
| 89 |
+
self.id = kwargs.pop("id")
|
| 90 |
+
self.private = kwargs.pop("private")
|
| 91 |
+
self.created_at = parse_datetime(kwargs.pop("createdAt"))
|
| 92 |
+
self.size = kwargs.pop("size")
|
| 93 |
+
self.total_files = kwargs.pop("totalFiles")
|
| 94 |
+
self.__dict__.update(**kwargs)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
@dataclass
|
| 98 |
+
class _BucketAddFile:
|
| 99 |
+
source: str | Path | bytes
|
| 100 |
+
destination: str
|
| 101 |
+
|
| 102 |
+
xet_hash: str | None = field(default=None)
|
| 103 |
+
size: int | None = field(default=None)
|
| 104 |
+
mtime: int = field(init=False)
|
| 105 |
+
content_type: str | None = field(init=False)
|
| 106 |
+
|
| 107 |
+
def __post_init__(self) -> None:
|
| 108 |
+
self.content_type = None
|
| 109 |
+
if isinstance(self.source, (str, Path)): # guess content type from source path
|
| 110 |
+
self.content_type = mimetypes.guess_type(self.source)[0]
|
| 111 |
+
if self.content_type is None: # or default to destination path content type
|
| 112 |
+
self.content_type = mimetypes.guess_type(self.destination)[0]
|
| 113 |
+
|
| 114 |
+
self.mtime = int(
|
| 115 |
+
os.path.getmtime(self.source) * 1000 if not isinstance(self.source, bytes) else time.time() * 1000
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
@dataclass
|
| 120 |
+
class _BucketCopyFile:
|
| 121 |
+
destination: str
|
| 122 |
+
xet_hash: str
|
| 123 |
+
source_repo_type: str # "model", "dataset", "space", "bucket"
|
| 124 |
+
source_repo_id: str
|
| 125 |
+
size: int | None = field(default=None)
|
| 126 |
+
mtime: int = field(init=False)
|
| 127 |
+
content_type: str | None = field(init=False)
|
| 128 |
+
|
| 129 |
+
def __post_init__(self) -> None:
|
| 130 |
+
self.content_type = mimetypes.guess_type(self.destination)[0]
|
| 131 |
+
self.mtime = int(time.time() * 1000)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
@dataclass
|
| 135 |
+
class _BucketDeleteFile:
|
| 136 |
+
path: str
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
@dataclass(frozen=True)
|
| 140 |
+
class BucketFileMetadata:
|
| 141 |
+
"""Data structure containing information about a file in a bucket.
|
| 142 |
+
|
| 143 |
+
Returned by [`get_bucket_file_metadata`].
|
| 144 |
+
|
| 145 |
+
Args:
|
| 146 |
+
size (`int`):
|
| 147 |
+
Size of the file in bytes.
|
| 148 |
+
xet_file_data (`XetFileData`):
|
| 149 |
+
Xet information for the file (hash and refresh route).
|
| 150 |
+
"""
|
| 151 |
+
|
| 152 |
+
size: int
|
| 153 |
+
xet_file_data: XetFileData
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
@dataclass
|
| 157 |
+
class BucketUrl:
|
| 158 |
+
"""Describes a bucket URL on the Hub.
|
| 159 |
+
|
| 160 |
+
`BucketUrl` is returned by [`create_bucket`]. At initialization, the URL is parsed to populate properties:
|
| 161 |
+
- endpoint (`str`)
|
| 162 |
+
- namespace (`str`)
|
| 163 |
+
- bucket_id (`str`)
|
| 164 |
+
- url (`str`)
|
| 165 |
+
- uri (`HfUri`)
|
| 166 |
+
|
| 167 |
+
Args:
|
| 168 |
+
url (`str`):
|
| 169 |
+
String value of the bucket url.
|
| 170 |
+
endpoint (`str`, *optional*):
|
| 171 |
+
Endpoint of the Hub. Defaults to <https://huggingface.co>.
|
| 172 |
+
"""
|
| 173 |
+
|
| 174 |
+
url: str
|
| 175 |
+
endpoint: str = ""
|
| 176 |
+
namespace: str = field(init=False)
|
| 177 |
+
bucket_id: str = field(init=False)
|
| 178 |
+
uri: HfUri = field(init=False)
|
| 179 |
+
|
| 180 |
+
def __post_init__(self) -> None:
|
| 181 |
+
self.endpoint = self.endpoint or constants.ENDPOINT
|
| 182 |
+
|
| 183 |
+
# Parse URL: expected format is `{endpoint}/buckets/{namespace}/{bucket_name}`
|
| 184 |
+
url_path = self.url.replace(self.endpoint, "").strip("/")
|
| 185 |
+
# Remove leading "buckets/" prefix
|
| 186 |
+
if url_path.startswith("buckets/"):
|
| 187 |
+
url_path = url_path[len("buckets/") :]
|
| 188 |
+
parsed = _parse_bucket_uri(url_path)
|
| 189 |
+
if parsed.path_in_repo:
|
| 190 |
+
raise ValueError(f"Unable to parse bucket URL: {self.url}")
|
| 191 |
+
self.namespace = parsed.id.split("/")[0]
|
| 192 |
+
self.bucket_id = parsed.id
|
| 193 |
+
self.uri = parsed
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
@dataclass
|
| 197 |
+
class BucketFile:
|
| 198 |
+
"""
|
| 199 |
+
Contains information about a file in a bucket on the Hub. This object is returned by [`list_bucket_tree`].
|
| 200 |
+
|
| 201 |
+
Similar to [`RepoFile`] but for files in buckets.
|
| 202 |
+
"""
|
| 203 |
+
|
| 204 |
+
type: Literal["file"]
|
| 205 |
+
path: str
|
| 206 |
+
size: int
|
| 207 |
+
xet_hash: str
|
| 208 |
+
mtime: datetime | None
|
| 209 |
+
uploaded_at: datetime | None
|
| 210 |
+
|
| 211 |
+
def __init__(self, **kwargs):
|
| 212 |
+
self.type = kwargs.pop("type")
|
| 213 |
+
self.path = kwargs.pop("path")
|
| 214 |
+
self.size = kwargs.pop("size")
|
| 215 |
+
self.xet_hash = kwargs.pop("xetHash")
|
| 216 |
+
mtime = kwargs.pop("mtime", None)
|
| 217 |
+
self.mtime = parse_datetime(mtime) if mtime else None
|
| 218 |
+
uploaded_at = kwargs.pop("uploadedAt", None)
|
| 219 |
+
self.uploaded_at = parse_datetime(uploaded_at) if uploaded_at else None
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
@dataclass
|
| 223 |
+
class BucketFolder:
|
| 224 |
+
"""
|
| 225 |
+
Contains information about a directory in a bucket on the Hub. This object is returned by [`list_bucket_tree`].
|
| 226 |
+
|
| 227 |
+
Similar to [`RepoFolder`] but for directories in buckets.
|
| 228 |
+
"""
|
| 229 |
+
|
| 230 |
+
type: Literal["directory"]
|
| 231 |
+
path: str
|
| 232 |
+
uploaded_at: datetime | None
|
| 233 |
+
|
| 234 |
+
def __init__(self, **kwargs):
|
| 235 |
+
self.type = kwargs.pop("type")
|
| 236 |
+
self.path = kwargs.pop("path")
|
| 237 |
+
uploaded_at = kwargs.pop("uploadedAt", None) or kwargs.pop("uploaded_at", None)
|
| 238 |
+
self.uploaded_at = (
|
| 239 |
+
(uploaded_at if isinstance(uploaded_at, datetime) else parse_datetime(uploaded_at))
|
| 240 |
+
if uploaded_at
|
| 241 |
+
else None
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
# =============================================================================
|
| 246 |
+
# Bucket path parsing
|
| 247 |
+
# =============================================================================
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def _parse_bucket_uri(path: str) -> HfUri:
|
| 251 |
+
"""Parse a bucket path into a HfUri.
|
| 252 |
+
|
| 253 |
+
Accepts:
|
| 254 |
+
- `hf://buckets/namespace/name(/path/in/repo)` URIs,
|
| 255 |
+
- Hugging Face web URLs such as `https://huggingface.co/buckets/namespace/name(/tree/path)`,
|
| 256 |
+
- plain `namespace/name(/path/in/repo)` paths.
|
| 257 |
+
"""
|
| 258 |
+
if path.startswith(constants.HF_PROTOCOL) or _looks_like_hf_url(path):
|
| 259 |
+
# Don't use 'if is_hf_uri(...)' here as we prefer 'parse_hf_uri(...)' to raise the exact error message.
|
| 260 |
+
parsed = parse_hf_uri(path)
|
| 261 |
+
if not parsed.is_bucket:
|
| 262 |
+
raise ValueError(f"Invalid bucket path: {path}. Must be a bucket URI (hf://buckets/...).")
|
| 263 |
+
return parsed
|
| 264 |
+
parts = path.split("/", 2)
|
| 265 |
+
if len(parts) < 2 or not parts[0] or not parts[1]:
|
| 266 |
+
raise ValueError(f"Invalid bucket path: '{path}'. Expected format: namespace/bucket_name")
|
| 267 |
+
bucket_id = f"{parts[0]}/{parts[1]}"
|
| 268 |
+
prefix = "/".join(parts[2:])
|
| 269 |
+
return HfUri(type="bucket", id=bucket_id, path_in_repo=prefix)
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def _is_bucket_path(path: str) -> bool:
|
| 273 |
+
"""Check if a path is a bucket path.
|
| 274 |
+
|
| 275 |
+
Do not raise if the path is not a hf:// URI.
|
| 276 |
+
Raise if the path is a hf:// URI but with an incorrect format.
|
| 277 |
+
"""
|
| 278 |
+
if not path.startswith(constants.HF_PROTOCOL):
|
| 279 |
+
return False
|
| 280 |
+
return parse_hf_uri(path).is_bucket
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
# =============================================================================
|
| 284 |
+
# Sync data structures
|
| 285 |
+
# =============================================================================
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
@dataclass
|
| 289 |
+
class SyncOperation:
|
| 290 |
+
"""Represents a sync operation to be performed."""
|
| 291 |
+
|
| 292 |
+
action: Literal["upload", "download", "delete", "skip"]
|
| 293 |
+
path: str
|
| 294 |
+
size: int | None = None
|
| 295 |
+
reason: str = ""
|
| 296 |
+
local_mtime: str | None = None
|
| 297 |
+
remote_mtime: str | None = None
|
| 298 |
+
bucket_file: BucketFile | None = None # BucketFile when available (not serialized to plan file)
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
@dataclass
|
| 302 |
+
class SyncPlan:
|
| 303 |
+
"""Represents a complete sync plan."""
|
| 304 |
+
|
| 305 |
+
source: str
|
| 306 |
+
dest: str
|
| 307 |
+
timestamp: str
|
| 308 |
+
operations: list[SyncOperation] = field(default_factory=list)
|
| 309 |
+
|
| 310 |
+
def summary(self) -> dict[str, int | str]:
|
| 311 |
+
uploads = sum(1 for op in self.operations if op.action == "upload")
|
| 312 |
+
downloads = sum(1 for op in self.operations if op.action == "download")
|
| 313 |
+
deletes = sum(1 for op in self.operations if op.action == "delete")
|
| 314 |
+
skips = sum(1 for op in self.operations if op.action == "skip")
|
| 315 |
+
total_size = sum(op.size or 0 for op in self.operations if op.action in ("upload", "download"))
|
| 316 |
+
return {
|
| 317 |
+
"uploads": uploads,
|
| 318 |
+
"downloads": downloads,
|
| 319 |
+
"deletes": deletes,
|
| 320 |
+
"skips": skips,
|
| 321 |
+
"total_size": total_size,
|
| 322 |
+
}
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
# =============================================================================
|
| 326 |
+
# Filter matching
|
| 327 |
+
# =============================================================================
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
class FilterMatcher:
|
| 331 |
+
"""Matches file paths against include/exclude patterns.
|
| 332 |
+
|
| 333 |
+
Matching is case-sensitive on every platform, like bucket paths. Backslashes in patterns are treated as path
|
| 334 |
+
separators, since bucket paths and local relative paths always use `/`.
|
| 335 |
+
"""
|
| 336 |
+
|
| 337 |
+
def __init__(
|
| 338 |
+
self,
|
| 339 |
+
include_patterns: list[str] | None = None,
|
| 340 |
+
exclude_patterns: list[str] | None = None,
|
| 341 |
+
filter_rules: list[tuple[str, str]] | None = None,
|
| 342 |
+
):
|
| 343 |
+
"""Initialize the filter matcher.
|
| 344 |
+
|
| 345 |
+
Args:
|
| 346 |
+
include_patterns: Patterns to include (from --include)
|
| 347 |
+
exclude_patterns: Patterns to exclude (from --exclude)
|
| 348 |
+
filter_rules: Rules from filter file as list of ("+"/"-", pattern) tuples
|
| 349 |
+
"""
|
| 350 |
+
self.include_patterns = [_normalize_separators(p) for p in include_patterns or []]
|
| 351 |
+
self.exclude_patterns = [_normalize_separators(p) for p in exclude_patterns or []]
|
| 352 |
+
self.filter_rules = [(sign, _normalize_separators(p)) for sign, p in filter_rules or []]
|
| 353 |
+
|
| 354 |
+
def matches(self, path: str) -> bool:
|
| 355 |
+
"""Check if a path should be included based on the filter rules.
|
| 356 |
+
|
| 357 |
+
Filtering rules:
|
| 358 |
+
- Filters are evaluated in order, first matching rule decides
|
| 359 |
+
- If no rules match, include by default (unless include patterns are specified)
|
| 360 |
+
"""
|
| 361 |
+
# First check filter rules from file (in order)
|
| 362 |
+
for sign, pattern in self.filter_rules:
|
| 363 |
+
if fnmatch.fnmatchcase(path, pattern):
|
| 364 |
+
return sign == "+"
|
| 365 |
+
|
| 366 |
+
# Then check CLI patterns
|
| 367 |
+
for pattern in self.exclude_patterns:
|
| 368 |
+
if fnmatch.fnmatchcase(path, pattern):
|
| 369 |
+
return False
|
| 370 |
+
|
| 371 |
+
for pattern in self.include_patterns:
|
| 372 |
+
if fnmatch.fnmatchcase(path, pattern):
|
| 373 |
+
return True
|
| 374 |
+
|
| 375 |
+
# If include patterns were specified but none matched, exclude
|
| 376 |
+
if self.include_patterns:
|
| 377 |
+
return False
|
| 378 |
+
|
| 379 |
+
# Default: include
|
| 380 |
+
return True
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
def _parse_filter_file(filter_file: str) -> list[tuple[str, str]]:
|
| 384 |
+
"""Parse a filter file and return a list of (sign, pattern) tuples.
|
| 385 |
+
|
| 386 |
+
Filter file format:
|
| 387 |
+
- Lines starting with "+" are include patterns
|
| 388 |
+
- Lines starting with "-" are exclude patterns
|
| 389 |
+
- Empty lines and lines starting with "#" are ignored
|
| 390 |
+
"""
|
| 391 |
+
rules = []
|
| 392 |
+
with open(filter_file) as f:
|
| 393 |
+
for line in f:
|
| 394 |
+
line = line.strip()
|
| 395 |
+
if not line or line.startswith("#"):
|
| 396 |
+
continue
|
| 397 |
+
if line.startswith("+"):
|
| 398 |
+
rules.append(("+", line[1:].strip()))
|
| 399 |
+
elif line.startswith("-"):
|
| 400 |
+
rules.append(("-", line[1:].strip()))
|
| 401 |
+
else:
|
| 402 |
+
# Default to include if no prefix
|
| 403 |
+
rules.append(("+", line))
|
| 404 |
+
return rules
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
# =============================================================================
|
| 408 |
+
# File listing
|
| 409 |
+
# =============================================================================
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
def _stat_local(path: str) -> tuple[int, float] | None:
|
| 413 |
+
"""Stat a local file and return (size, mtime_ms).
|
| 414 |
+
|
| 415 |
+
Returns None if the path is missing or is a directory. Uses a single
|
| 416 |
+
``os.stat`` call so callers don't pay for multiple syscalls per file.
|
| 417 |
+
"""
|
| 418 |
+
try:
|
| 419 |
+
st = os.stat(path)
|
| 420 |
+
except OSError:
|
| 421 |
+
return None
|
| 422 |
+
if stat.S_ISDIR(st.st_mode):
|
| 423 |
+
return None
|
| 424 |
+
return st.st_size, st.st_mtime * 1000
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
def _list_local_files(local_path: str) -> Iterator[tuple[str, int, float]]:
|
| 428 |
+
"""List all files in a local directory.
|
| 429 |
+
|
| 430 |
+
Yields:
|
| 431 |
+
tuple: (relative_path, size, mtime_ms) for each file
|
| 432 |
+
"""
|
| 433 |
+
local_path = os.path.abspath(local_path)
|
| 434 |
+
if not os.path.isdir(local_path):
|
| 435 |
+
raise ValueError(f"Local path must be a directory: {local_path}")
|
| 436 |
+
|
| 437 |
+
for root, _, files in os.walk(local_path):
|
| 438 |
+
for filename in files:
|
| 439 |
+
full_path = os.path.join(root, filename)
|
| 440 |
+
stat_info = _stat_local(full_path)
|
| 441 |
+
if stat_info is None:
|
| 442 |
+
continue
|
| 443 |
+
rel_path = os.path.relpath(full_path, local_path)
|
| 444 |
+
# Normalize to forward slashes for consistency
|
| 445 |
+
rel_path = rel_path.replace(os.sep, "/")
|
| 446 |
+
yield rel_path, stat_info[0], stat_info[1]
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
def _list_remote_files(api: "HfApi", bucket_id: str, prefix: str) -> Iterator[tuple[str, int, float, Any]]:
|
| 450 |
+
"""List all files in a bucket with a given prefix.
|
| 451 |
+
|
| 452 |
+
Yields:
|
| 453 |
+
tuple: (relative_path, size, mtime_ms, bucket_file) for each file.
|
| 454 |
+
bucket_file is the BucketFile object from list_bucket_tree.
|
| 455 |
+
"""
|
| 456 |
+
for item in api.list_bucket_tree(bucket_id, prefix=prefix or None, recursive=True):
|
| 457 |
+
if isinstance(item, BucketFolder):
|
| 458 |
+
continue
|
| 459 |
+
path = item.path
|
| 460 |
+
# Remove prefix from path to get relative path
|
| 461 |
+
# Only strip prefix if it's followed by "/" (directory boundary) or is exact match
|
| 462 |
+
if prefix:
|
| 463 |
+
if path.startswith(prefix + "/"):
|
| 464 |
+
rel_path = path[len(prefix) + 1 :]
|
| 465 |
+
elif path == prefix:
|
| 466 |
+
# Exact match: the file IS the prefix (e.g., single file download)
|
| 467 |
+
rel_path = path.rsplit("/", 1)[-1] if "/" in path else path
|
| 468 |
+
else:
|
| 469 |
+
# Path doesn't match prefix pattern (e.g., "submarine.txt" for prefix "sub")
|
| 470 |
+
# Skip this file - it was returned by the API but doesn't belong to this prefix
|
| 471 |
+
continue
|
| 472 |
+
else:
|
| 473 |
+
rel_path = path
|
| 474 |
+
# Reject server keys that would escape the local dir when joined onto it (see PR #4540).
|
| 475 |
+
_validate_relative_filename(rel_path)
|
| 476 |
+
mtime_ms = item.mtime.timestamp() * 1000 if item.mtime else 0
|
| 477 |
+
yield rel_path, item.size, mtime_ms, item
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
# =============================================================================
|
| 481 |
+
# Sync plan computation
|
| 482 |
+
# =============================================================================
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
def _mtime_to_iso(mtime_ms: float) -> str:
|
| 486 |
+
"""Convert mtime in milliseconds to ISO format string."""
|
| 487 |
+
return datetime.fromtimestamp(mtime_ms / 1000, tz=timezone.utc).isoformat()
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
def _compare_files_for_sync(
|
| 491 |
+
*,
|
| 492 |
+
path: str,
|
| 493 |
+
action: Literal["upload", "download"],
|
| 494 |
+
source_size: int,
|
| 495 |
+
source_mtime: float,
|
| 496 |
+
dest_size: int,
|
| 497 |
+
dest_mtime: float,
|
| 498 |
+
source_newer_label: str,
|
| 499 |
+
dest_newer_label: str,
|
| 500 |
+
ignore_sizes: bool,
|
| 501 |
+
ignore_times: bool,
|
| 502 |
+
ignore_existing: bool,
|
| 503 |
+
bucket_file: Any | None = None,
|
| 504 |
+
) -> SyncOperation:
|
| 505 |
+
"""Compare source and dest files and return the appropriate sync operation.
|
| 506 |
+
|
| 507 |
+
This is a unified helper for both upload and download directions.
|
| 508 |
+
|
| 509 |
+
Args:
|
| 510 |
+
path: Relative file path
|
| 511 |
+
action: "upload" or "download"
|
| 512 |
+
source_size: Size of the source file (bytes)
|
| 513 |
+
source_mtime: Mtime of the source file (milliseconds)
|
| 514 |
+
dest_size: Size of the destination file (bytes)
|
| 515 |
+
dest_mtime: Mtime of the destination file (milliseconds)
|
| 516 |
+
source_newer_label: Label when source is newer (e.g., "local newer" or "remote newer")
|
| 517 |
+
dest_newer_label: Label when dest is newer (e.g., "remote newer" or "local newer")
|
| 518 |
+
ignore_sizes: Only compare mtime
|
| 519 |
+
ignore_times: Only compare size
|
| 520 |
+
ignore_existing: Skip files that exist on receiver
|
| 521 |
+
bucket_file: BucketFile object (for downloads only)
|
| 522 |
+
|
| 523 |
+
Returns:
|
| 524 |
+
SyncOperation describing the action to take
|
| 525 |
+
"""
|
| 526 |
+
local_mtime_iso = _mtime_to_iso(source_mtime if action == "upload" else dest_mtime)
|
| 527 |
+
remote_mtime_iso = _mtime_to_iso(dest_mtime if action == "upload" else source_mtime)
|
| 528 |
+
|
| 529 |
+
base_kwargs: dict[str, Any] = {
|
| 530 |
+
"path": path,
|
| 531 |
+
"size": source_size,
|
| 532 |
+
"local_mtime": local_mtime_iso,
|
| 533 |
+
"remote_mtime": remote_mtime_iso,
|
| 534 |
+
}
|
| 535 |
+
|
| 536 |
+
if ignore_existing:
|
| 537 |
+
return SyncOperation(action="skip", reason="exists on receiver (--ignore-existing)", **base_kwargs)
|
| 538 |
+
|
| 539 |
+
size_differs = source_size != dest_size
|
| 540 |
+
source_newer = (source_mtime - dest_mtime) > _SYNC_TIME_WINDOW_MS
|
| 541 |
+
|
| 542 |
+
if ignore_sizes:
|
| 543 |
+
if source_newer:
|
| 544 |
+
return SyncOperation(action=action, reason=source_newer_label, bucket_file=bucket_file, **base_kwargs)
|
| 545 |
+
else:
|
| 546 |
+
dest_newer = (dest_mtime - source_mtime) > _SYNC_TIME_WINDOW_MS
|
| 547 |
+
skip_reason = dest_newer_label if dest_newer else "same mtime"
|
| 548 |
+
return SyncOperation(action="skip", reason=skip_reason, **base_kwargs)
|
| 549 |
+
elif ignore_times:
|
| 550 |
+
if size_differs:
|
| 551 |
+
return SyncOperation(action=action, reason="size differs", bucket_file=bucket_file, **base_kwargs)
|
| 552 |
+
else:
|
| 553 |
+
return SyncOperation(action="skip", reason="same size", **base_kwargs)
|
| 554 |
+
else:
|
| 555 |
+
if size_differs or source_newer:
|
| 556 |
+
reason = "size differs" if size_differs else source_newer_label
|
| 557 |
+
return SyncOperation(action=action, reason=reason, bucket_file=bucket_file, **base_kwargs)
|
| 558 |
+
else:
|
| 559 |
+
return SyncOperation(action="skip", reason="identical", **base_kwargs)
|
| 560 |
+
|
| 561 |
+
|
| 562 |
+
def _compute_sync_plan(
|
| 563 |
+
source: str,
|
| 564 |
+
dest: str,
|
| 565 |
+
api: "HfApi",
|
| 566 |
+
delete: bool = False,
|
| 567 |
+
ignore_times: bool = False,
|
| 568 |
+
ignore_sizes: bool = False,
|
| 569 |
+
existing: bool = False,
|
| 570 |
+
ignore_existing: bool = False,
|
| 571 |
+
filter_matcher: FilterMatcher | None = None,
|
| 572 |
+
status: Any | None = None,
|
| 573 |
+
) -> SyncPlan:
|
| 574 |
+
"""Compute the sync plan by comparing source and destination.
|
| 575 |
+
|
| 576 |
+
Returns:
|
| 577 |
+
SyncPlan with all operations to be performed
|
| 578 |
+
"""
|
| 579 |
+
filter_matcher = filter_matcher or FilterMatcher()
|
| 580 |
+
is_upload = not _is_bucket_path(source) and _is_bucket_path(dest)
|
| 581 |
+
is_download = _is_bucket_path(source) and not _is_bucket_path(dest)
|
| 582 |
+
|
| 583 |
+
if not is_upload and not is_download:
|
| 584 |
+
raise ValueError("One of source or dest must be a bucket path (hf://buckets/...) and the other must be local.")
|
| 585 |
+
|
| 586 |
+
plan = SyncPlan(
|
| 587 |
+
source=source,
|
| 588 |
+
dest=dest,
|
| 589 |
+
timestamp=datetime.now(timezone.utc).isoformat(),
|
| 590 |
+
)
|
| 591 |
+
|
| 592 |
+
remote_total: int | None = None
|
| 593 |
+
if is_upload:
|
| 594 |
+
# Local -> Remote
|
| 595 |
+
local_path = os.path.abspath(source)
|
| 596 |
+
parsed = _parse_bucket_uri(dest)
|
| 597 |
+
bucket_id, prefix = parsed.id, parsed.path_in_repo
|
| 598 |
+
|
| 599 |
+
if not os.path.isdir(local_path):
|
| 600 |
+
raise ValueError(f"Source must be a directory: {local_path}")
|
| 601 |
+
|
| 602 |
+
# Get local and remote file lists
|
| 603 |
+
local_files = {}
|
| 604 |
+
for rel_path, size, mtime_ms in _list_local_files(local_path):
|
| 605 |
+
if filter_matcher.matches(rel_path):
|
| 606 |
+
local_files[rel_path] = (size, mtime_ms)
|
| 607 |
+
if status:
|
| 608 |
+
status.update(f"Scanning local directory ({len(local_files)} files)")
|
| 609 |
+
if status:
|
| 610 |
+
status.done(f"Scanning local directory ({len(local_files)} files)")
|
| 611 |
+
|
| 612 |
+
remote_files = {}
|
| 613 |
+
if status:
|
| 614 |
+
try:
|
| 615 |
+
remote_total = api.bucket_info(bucket_id).total_files
|
| 616 |
+
except Exception:
|
| 617 |
+
pass
|
| 618 |
+
try:
|
| 619 |
+
for rel_path, size, mtime_ms, _ in _list_remote_files(api, bucket_id, prefix):
|
| 620 |
+
if filter_matcher.matches(rel_path):
|
| 621 |
+
remote_files[rel_path] = (size, mtime_ms)
|
| 622 |
+
if status:
|
| 623 |
+
total_str = f"/{remote_total}" if remote_total is not None else ""
|
| 624 |
+
status.update(f"Scanning remote bucket ({len(remote_files)}{total_str} files)")
|
| 625 |
+
except BucketNotFoundError:
|
| 626 |
+
# Bucket doesn't exist yet - this is expected for new uploads
|
| 627 |
+
logger.debug(f"Bucket '{bucket_id}' not found, treating as empty.")
|
| 628 |
+
if status:
|
| 629 |
+
status.done(f"Scanning remote bucket ({len(remote_files)} files)")
|
| 630 |
+
|
| 631 |
+
# Compare files
|
| 632 |
+
all_paths = set(local_files.keys()) | set(remote_files.keys())
|
| 633 |
+
if status:
|
| 634 |
+
status.done(f"Comparing files ({len(all_paths)} paths)")
|
| 635 |
+
for path in sorted(all_paths):
|
| 636 |
+
local_info = local_files.get(path)
|
| 637 |
+
remote_info = remote_files.get(path)
|
| 638 |
+
|
| 639 |
+
if local_info and not remote_info:
|
| 640 |
+
# New file
|
| 641 |
+
if existing:
|
| 642 |
+
# --existing: skip new files
|
| 643 |
+
plan.operations.append(
|
| 644 |
+
SyncOperation(
|
| 645 |
+
action="skip",
|
| 646 |
+
path=path,
|
| 647 |
+
size=local_info[0],
|
| 648 |
+
reason="new file (--existing)",
|
| 649 |
+
local_mtime=_mtime_to_iso(local_info[1]),
|
| 650 |
+
)
|
| 651 |
+
)
|
| 652 |
+
else:
|
| 653 |
+
plan.operations.append(
|
| 654 |
+
SyncOperation(
|
| 655 |
+
action="upload",
|
| 656 |
+
path=path,
|
| 657 |
+
size=local_info[0],
|
| 658 |
+
reason="new file",
|
| 659 |
+
local_mtime=_mtime_to_iso(local_info[1]),
|
| 660 |
+
)
|
| 661 |
+
)
|
| 662 |
+
elif local_info and remote_info:
|
| 663 |
+
# File exists in both - use helper to determine action
|
| 664 |
+
local_size, local_mtime = local_info
|
| 665 |
+
remote_size, remote_mtime = remote_info
|
| 666 |
+
plan.operations.append(
|
| 667 |
+
_compare_files_for_sync(
|
| 668 |
+
path=path,
|
| 669 |
+
action="upload",
|
| 670 |
+
source_size=local_size,
|
| 671 |
+
source_mtime=local_mtime,
|
| 672 |
+
dest_size=remote_size,
|
| 673 |
+
dest_mtime=remote_mtime,
|
| 674 |
+
source_newer_label="local newer",
|
| 675 |
+
dest_newer_label="remote newer",
|
| 676 |
+
ignore_sizes=ignore_sizes,
|
| 677 |
+
ignore_times=ignore_times,
|
| 678 |
+
ignore_existing=ignore_existing,
|
| 679 |
+
)
|
| 680 |
+
)
|
| 681 |
+
elif not local_info and remote_info and delete:
|
| 682 |
+
# File only in remote and --delete mode
|
| 683 |
+
plan.operations.append(
|
| 684 |
+
SyncOperation(
|
| 685 |
+
action="delete",
|
| 686 |
+
path=path,
|
| 687 |
+
size=remote_info[0],
|
| 688 |
+
reason="not in source (--delete)",
|
| 689 |
+
remote_mtime=_mtime_to_iso(remote_info[1]),
|
| 690 |
+
)
|
| 691 |
+
)
|
| 692 |
+
|
| 693 |
+
else:
|
| 694 |
+
# Remote -> Local (download)
|
| 695 |
+
parsed = _parse_bucket_uri(source)
|
| 696 |
+
bucket_id, prefix = parsed.id, parsed.path_in_repo
|
| 697 |
+
local_path = os.path.abspath(dest)
|
| 698 |
+
|
| 699 |
+
# Get remote and local file lists
|
| 700 |
+
remote_files = {}
|
| 701 |
+
bucket_file_map: dict[str, Any] = {}
|
| 702 |
+
if status:
|
| 703 |
+
try:
|
| 704 |
+
remote_total = api.bucket_info(bucket_id).total_files
|
| 705 |
+
except Exception:
|
| 706 |
+
pass
|
| 707 |
+
for rel_path, size, mtime_ms, bucket_file in _list_remote_files(api, bucket_id, prefix):
|
| 708 |
+
if filter_matcher.matches(rel_path):
|
| 709 |
+
remote_files[rel_path] = (size, mtime_ms)
|
| 710 |
+
bucket_file_map[rel_path] = bucket_file
|
| 711 |
+
if status:
|
| 712 |
+
total_str = f"/{remote_total}" if remote_total is not None else ""
|
| 713 |
+
status.update(f"Scanning remote bucket ({len(remote_files)}{total_str} files)")
|
| 714 |
+
if status:
|
| 715 |
+
status.done(f"Scanning remote bucket ({len(remote_files)} files)")
|
| 716 |
+
|
| 717 |
+
local_files = {}
|
| 718 |
+
if os.path.isdir(local_path):
|
| 719 |
+
if delete:
|
| 720 |
+
# Full walk needed to discover local-only files for deletion.
|
| 721 |
+
for rel_path, size, mtime_ms in _list_local_files(local_path):
|
| 722 |
+
if filter_matcher.matches(rel_path):
|
| 723 |
+
local_files[rel_path] = (size, mtime_ms)
|
| 724 |
+
if status:
|
| 725 |
+
status.update(f"Scanning local directory ({len(local_files)} files)")
|
| 726 |
+
else:
|
| 727 |
+
# Without --delete, the plan only depends on paths that exist
|
| 728 |
+
# remotely. Stat just those instead of walking the whole tree,
|
| 729 |
+
# which can take minutes when dest sits in a large directory
|
| 730 |
+
# like ~/.cache/huggingface/.
|
| 731 |
+
for rel_path in remote_files:
|
| 732 |
+
local_file = os.path.join(local_path, rel_path)
|
| 733 |
+
stat_info = _stat_local(local_file)
|
| 734 |
+
if stat_info is None:
|
| 735 |
+
continue
|
| 736 |
+
local_files[rel_path] = stat_info
|
| 737 |
+
if status:
|
| 738 |
+
status.update(f"Scanning local directory ({len(local_files)} files)")
|
| 739 |
+
if status:
|
| 740 |
+
status.done(f"Scanning local directory ({len(local_files)} files)")
|
| 741 |
+
|
| 742 |
+
# Compare files
|
| 743 |
+
all_paths = set(remote_files.keys()) | set(local_files.keys())
|
| 744 |
+
if status:
|
| 745 |
+
status.done(f"Comparing files ({len(all_paths)} paths)")
|
| 746 |
+
for path in sorted(all_paths):
|
| 747 |
+
remote_info = remote_files.get(path)
|
| 748 |
+
local_info = local_files.get(path)
|
| 749 |
+
|
| 750 |
+
if remote_info and not local_info:
|
| 751 |
+
# New file
|
| 752 |
+
if existing:
|
| 753 |
+
# --existing: skip new files
|
| 754 |
+
plan.operations.append(
|
| 755 |
+
SyncOperation(
|
| 756 |
+
action="skip",
|
| 757 |
+
path=path,
|
| 758 |
+
size=remote_info[0],
|
| 759 |
+
reason="new file (--existing)",
|
| 760 |
+
remote_mtime=_mtime_to_iso(remote_info[1]),
|
| 761 |
+
)
|
| 762 |
+
)
|
| 763 |
+
else:
|
| 764 |
+
plan.operations.append(
|
| 765 |
+
SyncOperation(
|
| 766 |
+
action="download",
|
| 767 |
+
path=path,
|
| 768 |
+
size=remote_info[0],
|
| 769 |
+
reason="new file",
|
| 770 |
+
remote_mtime=_mtime_to_iso(remote_info[1]),
|
| 771 |
+
bucket_file=bucket_file_map.get(path),
|
| 772 |
+
)
|
| 773 |
+
)
|
| 774 |
+
elif remote_info and local_info:
|
| 775 |
+
# File exists in both - use helper to determine action
|
| 776 |
+
remote_size, remote_mtime = remote_info
|
| 777 |
+
local_size, local_mtime = local_info
|
| 778 |
+
plan.operations.append(
|
| 779 |
+
_compare_files_for_sync(
|
| 780 |
+
path=path,
|
| 781 |
+
action="download",
|
| 782 |
+
source_size=remote_size,
|
| 783 |
+
source_mtime=remote_mtime,
|
| 784 |
+
dest_size=local_size,
|
| 785 |
+
dest_mtime=local_mtime,
|
| 786 |
+
source_newer_label="remote newer",
|
| 787 |
+
dest_newer_label="local newer",
|
| 788 |
+
ignore_sizes=ignore_sizes,
|
| 789 |
+
ignore_times=ignore_times,
|
| 790 |
+
ignore_existing=ignore_existing,
|
| 791 |
+
bucket_file=bucket_file_map.get(path),
|
| 792 |
+
)
|
| 793 |
+
)
|
| 794 |
+
elif not remote_info and local_info and delete:
|
| 795 |
+
# File only in local and --delete mode
|
| 796 |
+
plan.operations.append(
|
| 797 |
+
SyncOperation(
|
| 798 |
+
action="delete",
|
| 799 |
+
path=path,
|
| 800 |
+
size=local_info[0],
|
| 801 |
+
reason="not in source (--delete)",
|
| 802 |
+
local_mtime=_mtime_to_iso(local_info[1]),
|
| 803 |
+
)
|
| 804 |
+
)
|
| 805 |
+
|
| 806 |
+
return plan
|
| 807 |
+
|
| 808 |
+
|
| 809 |
+
# =============================================================================
|
| 810 |
+
# Plan serialization
|
| 811 |
+
# =============================================================================
|
| 812 |
+
|
| 813 |
+
|
| 814 |
+
def _write_plan(plan: SyncPlan, f) -> None:
|
| 815 |
+
"""Write a sync plan as JSONL to a file-like object."""
|
| 816 |
+
# Write header
|
| 817 |
+
header = {
|
| 818 |
+
"type": "header",
|
| 819 |
+
"source": plan.source,
|
| 820 |
+
"dest": plan.dest,
|
| 821 |
+
"timestamp": plan.timestamp,
|
| 822 |
+
"summary": plan.summary(),
|
| 823 |
+
}
|
| 824 |
+
f.write(json.dumps(header) + "\n")
|
| 825 |
+
|
| 826 |
+
# Write operations
|
| 827 |
+
for op in plan.operations:
|
| 828 |
+
op_dict: dict[str, Any] = {
|
| 829 |
+
"type": "operation",
|
| 830 |
+
"action": op.action,
|
| 831 |
+
"path": op.path,
|
| 832 |
+
"reason": op.reason,
|
| 833 |
+
}
|
| 834 |
+
if op.size is not None:
|
| 835 |
+
op_dict["size"] = op.size
|
| 836 |
+
if op.local_mtime is not None:
|
| 837 |
+
op_dict["local_mtime"] = op.local_mtime
|
| 838 |
+
if op.remote_mtime is not None:
|
| 839 |
+
op_dict["remote_mtime"] = op.remote_mtime
|
| 840 |
+
f.write(json.dumps(op_dict) + "\n")
|
| 841 |
+
|
| 842 |
+
|
| 843 |
+
def _save_plan(plan: SyncPlan, plan_file: str) -> None:
|
| 844 |
+
"""Save a sync plan to a JSONL file."""
|
| 845 |
+
with open(plan_file, "w") as f:
|
| 846 |
+
_write_plan(plan, f)
|
| 847 |
+
|
| 848 |
+
|
| 849 |
+
def _load_plan(plan_file: str) -> SyncPlan:
|
| 850 |
+
"""Load a sync plan from a JSONL file."""
|
| 851 |
+
with open(plan_file) as f:
|
| 852 |
+
lines = f.readlines()
|
| 853 |
+
|
| 854 |
+
if not lines:
|
| 855 |
+
raise ValueError(f"Empty plan file: {plan_file}")
|
| 856 |
+
|
| 857 |
+
# Parse header
|
| 858 |
+
header = json.loads(lines[0])
|
| 859 |
+
if header.get("type") != "header":
|
| 860 |
+
raise ValueError("Invalid plan file: expected header as first line")
|
| 861 |
+
|
| 862 |
+
plan = SyncPlan(
|
| 863 |
+
source=header["source"],
|
| 864 |
+
dest=header["dest"],
|
| 865 |
+
timestamp=header["timestamp"],
|
| 866 |
+
)
|
| 867 |
+
|
| 868 |
+
# Parse operations
|
| 869 |
+
for line in lines[1:]:
|
| 870 |
+
op_dict = json.loads(line)
|
| 871 |
+
if op_dict.get("type") != "operation":
|
| 872 |
+
continue
|
| 873 |
+
plan.operations.append(
|
| 874 |
+
SyncOperation(
|
| 875 |
+
action=op_dict["action"],
|
| 876 |
+
path=op_dict["path"],
|
| 877 |
+
size=op_dict.get("size"),
|
| 878 |
+
reason=op_dict.get("reason", ""),
|
| 879 |
+
local_mtime=op_dict.get("local_mtime"),
|
| 880 |
+
remote_mtime=op_dict.get("remote_mtime"),
|
| 881 |
+
)
|
| 882 |
+
)
|
| 883 |
+
|
| 884 |
+
return plan
|
| 885 |
+
|
| 886 |
+
|
| 887 |
+
# =============================================================================
|
| 888 |
+
# Plan execution
|
| 889 |
+
# =============================================================================
|
| 890 |
+
|
| 891 |
+
|
| 892 |
+
def _execute_plan(plan: SyncPlan, api: "HfApi", verbose: bool = False, status: Any | None = None) -> None:
|
| 893 |
+
"""Execute a sync plan."""
|
| 894 |
+
is_upload = not _is_bucket_path(plan.source) and _is_bucket_path(plan.dest)
|
| 895 |
+
is_download = _is_bucket_path(plan.source) and not _is_bucket_path(plan.dest)
|
| 896 |
+
|
| 897 |
+
# Validate here too: an --apply'd plan is read from disk, bypassing the _list_remote_files guard.
|
| 898 |
+
for op in plan.operations:
|
| 899 |
+
_validate_relative_filename(op.path)
|
| 900 |
+
|
| 901 |
+
if is_upload:
|
| 902 |
+
local_path = os.path.abspath(plan.source)
|
| 903 |
+
parsed = _parse_bucket_uri(plan.dest)
|
| 904 |
+
bucket_id, prefix = parsed.id, parsed.path_in_repo
|
| 905 |
+
|
| 906 |
+
# Collect operations
|
| 907 |
+
add_files: list[tuple[str | Path | bytes, str]] = []
|
| 908 |
+
delete_paths: list[str] = []
|
| 909 |
+
|
| 910 |
+
for op in plan.operations:
|
| 911 |
+
match op.action:
|
| 912 |
+
case "upload":
|
| 913 |
+
local_file = os.path.join(local_path, op.path)
|
| 914 |
+
remote_path = f"{prefix}/{op.path}" if prefix else op.path
|
| 915 |
+
if verbose:
|
| 916 |
+
print(f" Uploading: {op.path} ({op.reason})")
|
| 917 |
+
add_files.append((local_file, remote_path))
|
| 918 |
+
case "delete":
|
| 919 |
+
remote_path = f"{prefix}/{op.path}" if prefix else op.path
|
| 920 |
+
if verbose:
|
| 921 |
+
print(f" Deleting: {op.path} ({op.reason})")
|
| 922 |
+
delete_paths.append(remote_path)
|
| 923 |
+
case "skip" if verbose:
|
| 924 |
+
print(f" Skipping: {op.path} ({op.reason})")
|
| 925 |
+
|
| 926 |
+
# Execute batch operations
|
| 927 |
+
if add_files or delete_paths:
|
| 928 |
+
if status:
|
| 929 |
+
parts = []
|
| 930 |
+
if add_files:
|
| 931 |
+
parts.append(f"uploading {len(add_files)} files")
|
| 932 |
+
if delete_paths:
|
| 933 |
+
parts.append(f"deleting {len(delete_paths)} files")
|
| 934 |
+
status.done(", ".join(parts).capitalize())
|
| 935 |
+
api.batch_bucket_files(
|
| 936 |
+
bucket_id,
|
| 937 |
+
add=add_files or None,
|
| 938 |
+
delete=delete_paths or None,
|
| 939 |
+
)
|
| 940 |
+
|
| 941 |
+
elif is_download:
|
| 942 |
+
parsed = _parse_bucket_uri(plan.source)
|
| 943 |
+
bucket_id, prefix = parsed.id, parsed.path_in_repo
|
| 944 |
+
local_path = os.path.abspath(plan.dest)
|
| 945 |
+
|
| 946 |
+
# Ensure local directory exists
|
| 947 |
+
os.makedirs(local_path, exist_ok=True)
|
| 948 |
+
|
| 949 |
+
# Collect download operations
|
| 950 |
+
download_files: list[tuple[str | BucketFile, str | Path]] = []
|
| 951 |
+
delete_files: list[str] = []
|
| 952 |
+
|
| 953 |
+
for op in plan.operations:
|
| 954 |
+
if op.action == "download":
|
| 955 |
+
local_file = os.path.join(local_path, op.path)
|
| 956 |
+
# Ensure parent directory exists
|
| 957 |
+
os.makedirs(os.path.dirname(local_file), exist_ok=True)
|
| 958 |
+
if verbose:
|
| 959 |
+
print(f" Downloading: {op.path} ({op.reason})")
|
| 960 |
+
# Use BucketFile when available (avoids extra metadata fetch per file)
|
| 961 |
+
if op.bucket_file is not None:
|
| 962 |
+
download_files.append((op.bucket_file, local_file))
|
| 963 |
+
else:
|
| 964 |
+
remote_path = f"{prefix}/{op.path}" if prefix else op.path
|
| 965 |
+
download_files.append((remote_path, local_file))
|
| 966 |
+
elif op.action == "delete":
|
| 967 |
+
local_file = os.path.join(local_path, op.path)
|
| 968 |
+
if verbose:
|
| 969 |
+
print(f" Deleting: {op.path} ({op.reason})")
|
| 970 |
+
delete_files.append(local_file)
|
| 971 |
+
elif op.action == "skip" and verbose:
|
| 972 |
+
print(f" Skipping: {op.path} ({op.reason})")
|
| 973 |
+
|
| 974 |
+
# Execute downloads
|
| 975 |
+
if len(download_files) > 0:
|
| 976 |
+
if status:
|
| 977 |
+
status.done(f"Downloading {len(download_files)} files")
|
| 978 |
+
api.download_bucket_files(bucket_id, download_files)
|
| 979 |
+
|
| 980 |
+
# Execute deletes
|
| 981 |
+
if status and delete_files:
|
| 982 |
+
status.done(f"Deleting {len(delete_files)} local files")
|
| 983 |
+
for file_path in delete_files:
|
| 984 |
+
if os.path.exists(file_path):
|
| 985 |
+
os.remove(file_path)
|
| 986 |
+
# Remove empty parent directories
|
| 987 |
+
parent = os.path.dirname(file_path)
|
| 988 |
+
while parent != local_path:
|
| 989 |
+
try:
|
| 990 |
+
os.rmdir(parent)
|
| 991 |
+
parent = os.path.dirname(parent)
|
| 992 |
+
except OSError:
|
| 993 |
+
break
|
| 994 |
+
|
| 995 |
+
|
| 996 |
+
def _print_plan_summary(plan: SyncPlan) -> None:
|
| 997 |
+
"""Print a summary of the sync plan."""
|
| 998 |
+
summary = plan.summary()
|
| 999 |
+
print(f"Sync plan: {plan.source} -> {plan.dest}")
|
| 1000 |
+
print(f" Uploads: {summary['uploads']}")
|
| 1001 |
+
print(f" Downloads: {summary['downloads']}")
|
| 1002 |
+
print(f" Deletes: {summary['deletes']}")
|
| 1003 |
+
print(f" Skips: {summary['skips']}")
|
| 1004 |
+
|
| 1005 |
+
|
| 1006 |
+
# =============================================================================
|
| 1007 |
+
# Public sync function (Python API)
|
| 1008 |
+
# =============================================================================
|
| 1009 |
+
|
| 1010 |
+
|
| 1011 |
+
def sync_bucket_internal(
|
| 1012 |
+
source: str | None = None,
|
| 1013 |
+
dest: str | None = None,
|
| 1014 |
+
*,
|
| 1015 |
+
api: "HfApi",
|
| 1016 |
+
delete: bool = False,
|
| 1017 |
+
ignore_times: bool = False,
|
| 1018 |
+
ignore_sizes: bool = False,
|
| 1019 |
+
existing: bool = False,
|
| 1020 |
+
ignore_existing: bool = False,
|
| 1021 |
+
include: list[str] | None = None,
|
| 1022 |
+
exclude: list[str] | None = None,
|
| 1023 |
+
filter_from: str | None = None,
|
| 1024 |
+
plan: str | None = None,
|
| 1025 |
+
apply: str | None = None,
|
| 1026 |
+
dry_run: bool = False,
|
| 1027 |
+
verbose: bool = False,
|
| 1028 |
+
quiet: bool = False,
|
| 1029 |
+
token: bool | str | None = None,
|
| 1030 |
+
) -> SyncPlan:
|
| 1031 |
+
"""Sync files between a local directory and a bucket.
|
| 1032 |
+
|
| 1033 |
+
This is equivalent to the ``hf buckets sync`` CLI command. One of ``source`` or ``dest`` must be a bucket path
|
| 1034 |
+
(``hf://buckets/...``) and the other must be a local directory path.
|
| 1035 |
+
|
| 1036 |
+
Args:
|
| 1037 |
+
source (`str`, *optional*):
|
| 1038 |
+
Source path: local directory or ``hf://buckets/namespace/bucket_name(/prefix)``.
|
| 1039 |
+
Required unless using ``apply``.
|
| 1040 |
+
dest (`str`, *optional*):
|
| 1041 |
+
Destination path: local directory or ``hf://buckets/namespace/bucket_name(/prefix)``.
|
| 1042 |
+
Required unless using ``apply``.
|
| 1043 |
+
api ([`HfApi`]):
|
| 1044 |
+
The HfApi instance to use for API calls.
|
| 1045 |
+
delete (`bool`, *optional*, defaults to `False`):
|
| 1046 |
+
Delete destination files not present in source.
|
| 1047 |
+
ignore_times (`bool`, *optional*, defaults to `False`):
|
| 1048 |
+
Skip files only based on size, ignoring modification times.
|
| 1049 |
+
ignore_sizes (`bool`, *optional*, defaults to `False`):
|
| 1050 |
+
Skip files only based on modification times, ignoring sizes.
|
| 1051 |
+
existing (`bool`, *optional*, defaults to `False`):
|
| 1052 |
+
Skip creating new files on receiver (only update existing files).
|
| 1053 |
+
ignore_existing (`bool`, *optional*, defaults to `False`):
|
| 1054 |
+
Skip updating files that exist on receiver (only create new files).
|
| 1055 |
+
include (`list[str]`, *optional*):
|
| 1056 |
+
Include files matching patterns (fnmatch-style).
|
| 1057 |
+
exclude (`list[str]`, *optional*):
|
| 1058 |
+
Exclude files matching patterns (fnmatch-style).
|
| 1059 |
+
filter_from (`str`, *optional*):
|
| 1060 |
+
Path to a filter file with include/exclude rules.
|
| 1061 |
+
plan (`str`, *optional*):
|
| 1062 |
+
Save sync plan to this JSONL file instead of executing.
|
| 1063 |
+
apply (`str`, *optional*):
|
| 1064 |
+
Apply a previously saved plan file. When set, ``source`` and ``dest`` are not needed.
|
| 1065 |
+
dry_run (`bool`, *optional*, defaults to `False`):
|
| 1066 |
+
Print sync plan to stdout as JSONL without executing.
|
| 1067 |
+
verbose (`bool`, *optional*, defaults to `False`):
|
| 1068 |
+
Show detailed per-file operations.
|
| 1069 |
+
quiet (`bool`, *optional*, defaults to `False`):
|
| 1070 |
+
Suppress all output and progress bars.
|
| 1071 |
+
token (Union[bool, str, None], optional):
|
| 1072 |
+
A valid user access token. If not provided, the locally saved token will be used.
|
| 1073 |
+
|
| 1074 |
+
Returns:
|
| 1075 |
+
[`SyncPlan`]: The computed (or loaded) sync plan.
|
| 1076 |
+
|
| 1077 |
+
Raises:
|
| 1078 |
+
`ValueError`: If arguments are invalid (e.g., both paths are remote, conflicting options).
|
| 1079 |
+
|
| 1080 |
+
Example:
|
| 1081 |
+
```python
|
| 1082 |
+
>>> from huggingface_hub import HfApi
|
| 1083 |
+
>>> api = HfApi()
|
| 1084 |
+
|
| 1085 |
+
# Upload local directory to bucket
|
| 1086 |
+
>>> api.sync_bucket("./data", "hf://buckets/username/my-bucket")
|
| 1087 |
+
|
| 1088 |
+
# Download bucket to local directory
|
| 1089 |
+
>>> api.sync_bucket("hf://buckets/username/my-bucket", "./data")
|
| 1090 |
+
|
| 1091 |
+
# Sync with delete and filtering
|
| 1092 |
+
>>> api.sync_bucket(
|
| 1093 |
+
... "./data",
|
| 1094 |
+
... "hf://buckets/username/my-bucket",
|
| 1095 |
+
... delete=True,
|
| 1096 |
+
... include=["*.safetensors"],
|
| 1097 |
+
... )
|
| 1098 |
+
|
| 1099 |
+
# Dry run: preview what would be synced
|
| 1100 |
+
>>> plan = api.sync_bucket("./data", "hf://buckets/username/my-bucket", dry_run=True)
|
| 1101 |
+
>>> plan.summary()
|
| 1102 |
+
{'uploads': 3, 'downloads': 0, 'deletes': 0, 'skips': 1, 'total_size': 4096}
|
| 1103 |
+
|
| 1104 |
+
# Save plan for review, then apply
|
| 1105 |
+
>>> api.sync_bucket("./data", "hf://buckets/username/my-bucket", plan="sync-plan.jsonl")
|
| 1106 |
+
>>> api.sync_bucket(apply="sync-plan.jsonl")
|
| 1107 |
+
```
|
| 1108 |
+
"""
|
| 1109 |
+
# Build API with token if needed
|
| 1110 |
+
if token is not None:
|
| 1111 |
+
from .hf_api import HfApi
|
| 1112 |
+
|
| 1113 |
+
api = HfApi(
|
| 1114 |
+
endpoint=api.endpoint,
|
| 1115 |
+
token=token,
|
| 1116 |
+
library_name=api.library_name,
|
| 1117 |
+
library_version=api.library_version,
|
| 1118 |
+
user_agent=api.user_agent,
|
| 1119 |
+
headers=api.headers,
|
| 1120 |
+
)
|
| 1121 |
+
# --- Apply mode ---
|
| 1122 |
+
if apply:
|
| 1123 |
+
if source or dest:
|
| 1124 |
+
raise ValueError("Cannot specify source/dest when using apply.")
|
| 1125 |
+
if plan is not None:
|
| 1126 |
+
raise ValueError("Cannot specify both plan and apply.")
|
| 1127 |
+
if delete:
|
| 1128 |
+
raise ValueError("Cannot specify delete when using apply.")
|
| 1129 |
+
if ignore_times:
|
| 1130 |
+
raise ValueError("Cannot specify ignore_times when using apply.")
|
| 1131 |
+
if ignore_sizes:
|
| 1132 |
+
raise ValueError("Cannot specify ignore_sizes when using apply.")
|
| 1133 |
+
if include:
|
| 1134 |
+
raise ValueError("Cannot specify include when using apply.")
|
| 1135 |
+
if exclude:
|
| 1136 |
+
raise ValueError("Cannot specify exclude when using apply.")
|
| 1137 |
+
if filter_from:
|
| 1138 |
+
raise ValueError("Cannot specify filter_from when using apply.")
|
| 1139 |
+
if existing:
|
| 1140 |
+
raise ValueError("Cannot specify existing when using apply.")
|
| 1141 |
+
if ignore_existing:
|
| 1142 |
+
raise ValueError("Cannot specify ignore_existing when using apply.")
|
| 1143 |
+
if dry_run:
|
| 1144 |
+
raise ValueError("Cannot specify dry_run when using apply.")
|
| 1145 |
+
|
| 1146 |
+
sync_plan = _load_plan(apply)
|
| 1147 |
+
status = StatusLine(enabled=not quiet)
|
| 1148 |
+
if not quiet:
|
| 1149 |
+
_print_plan_summary(sync_plan)
|
| 1150 |
+
print("Executing plan...")
|
| 1151 |
+
|
| 1152 |
+
if quiet:
|
| 1153 |
+
disable_progress_bars()
|
| 1154 |
+
try:
|
| 1155 |
+
_execute_plan(sync_plan, api, verbose=verbose, status=status)
|
| 1156 |
+
finally:
|
| 1157 |
+
if quiet:
|
| 1158 |
+
enable_progress_bars()
|
| 1159 |
+
|
| 1160 |
+
if not quiet:
|
| 1161 |
+
print("Sync completed.")
|
| 1162 |
+
|
| 1163 |
+
return sync_plan
|
| 1164 |
+
|
| 1165 |
+
# --- Normal mode ---
|
| 1166 |
+
if not source or not dest:
|
| 1167 |
+
raise ValueError("Both source and dest are required (unless using apply).")
|
| 1168 |
+
|
| 1169 |
+
source_is_bucket = _is_bucket_path(source)
|
| 1170 |
+
dest_is_bucket = _is_bucket_path(dest)
|
| 1171 |
+
|
| 1172 |
+
if source_is_bucket and dest_is_bucket:
|
| 1173 |
+
raise ValueError("Remote to remote sync is not supported. One path must be local.")
|
| 1174 |
+
|
| 1175 |
+
if not source_is_bucket and not dest_is_bucket:
|
| 1176 |
+
raise ValueError("One of source or dest must be a bucket path (hf://buckets/...).")
|
| 1177 |
+
|
| 1178 |
+
if ignore_times and ignore_sizes:
|
| 1179 |
+
raise ValueError("Cannot specify both ignore_times and ignore_sizes.")
|
| 1180 |
+
|
| 1181 |
+
if existing and ignore_existing:
|
| 1182 |
+
raise ValueError("Cannot specify both existing and ignore_existing.")
|
| 1183 |
+
|
| 1184 |
+
if dry_run and plan:
|
| 1185 |
+
raise ValueError("Cannot specify both dry_run and plan.")
|
| 1186 |
+
|
| 1187 |
+
# Validate local path
|
| 1188 |
+
if source_is_bucket:
|
| 1189 |
+
if os.path.exists(dest) and not os.path.isdir(dest):
|
| 1190 |
+
raise ValueError(f"Destination must be a directory: {dest}")
|
| 1191 |
+
else:
|
| 1192 |
+
if not os.path.isdir(source):
|
| 1193 |
+
raise ValueError(f"Source must be an existing directory: {source}")
|
| 1194 |
+
|
| 1195 |
+
# Build filter matcher
|
| 1196 |
+
filter_rules = None
|
| 1197 |
+
if filter_from:
|
| 1198 |
+
filter_rules = _parse_filter_file(filter_from)
|
| 1199 |
+
|
| 1200 |
+
filter_matcher = FilterMatcher(
|
| 1201 |
+
include_patterns=include,
|
| 1202 |
+
exclude_patterns=exclude,
|
| 1203 |
+
filter_rules=filter_rules,
|
| 1204 |
+
)
|
| 1205 |
+
|
| 1206 |
+
# Compute sync plan
|
| 1207 |
+
status = StatusLine(enabled=not quiet and not dry_run)
|
| 1208 |
+
sync_plan = _compute_sync_plan(
|
| 1209 |
+
source=source,
|
| 1210 |
+
dest=dest,
|
| 1211 |
+
api=api,
|
| 1212 |
+
delete=delete,
|
| 1213 |
+
ignore_times=ignore_times,
|
| 1214 |
+
ignore_sizes=ignore_sizes,
|
| 1215 |
+
existing=existing,
|
| 1216 |
+
ignore_existing=ignore_existing,
|
| 1217 |
+
filter_matcher=filter_matcher,
|
| 1218 |
+
status=status,
|
| 1219 |
+
)
|
| 1220 |
+
|
| 1221 |
+
if dry_run:
|
| 1222 |
+
_write_plan(sync_plan, sys.stdout)
|
| 1223 |
+
return sync_plan
|
| 1224 |
+
|
| 1225 |
+
if plan:
|
| 1226 |
+
_save_plan(sync_plan, plan)
|
| 1227 |
+
if not quiet:
|
| 1228 |
+
_print_plan_summary(sync_plan)
|
| 1229 |
+
print(f"Plan saved to: {plan}")
|
| 1230 |
+
return sync_plan
|
| 1231 |
+
|
| 1232 |
+
# Execute plan
|
| 1233 |
+
if not quiet:
|
| 1234 |
+
_print_plan_summary(sync_plan)
|
| 1235 |
+
|
| 1236 |
+
summary = sync_plan.summary()
|
| 1237 |
+
if summary["uploads"] == 0 and summary["downloads"] == 0 and summary["deletes"] == 0:
|
| 1238 |
+
if not quiet:
|
| 1239 |
+
print("Nothing to sync.")
|
| 1240 |
+
return sync_plan
|
| 1241 |
+
|
| 1242 |
+
if not quiet:
|
| 1243 |
+
print("Syncing...")
|
| 1244 |
+
|
| 1245 |
+
if quiet:
|
| 1246 |
+
disable_progress_bars()
|
| 1247 |
+
try:
|
| 1248 |
+
_execute_plan(sync_plan, api, verbose=verbose, status=status)
|
| 1249 |
+
finally:
|
| 1250 |
+
if quiet:
|
| 1251 |
+
enable_progress_bars()
|
| 1252 |
+
|
| 1253 |
+
if not quiet:
|
| 1254 |
+
print("Sync completed.")
|
| 1255 |
+
|
| 1256 |
+
return sync_plan
|
.venv/lib/python3.12/site-packages/huggingface_hub/_commit_api.py
ADDED
|
@@ -0,0 +1,1080 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Type definitions and utilities for the `create_commit` API
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import base64
|
| 6 |
+
import io
|
| 7 |
+
import json
|
| 8 |
+
import os
|
| 9 |
+
import warnings
|
| 10 |
+
from collections import defaultdict
|
| 11 |
+
from collections.abc import Iterable, Iterator
|
| 12 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 13 |
+
from contextlib import contextmanager
|
| 14 |
+
from dataclasses import dataclass, field
|
| 15 |
+
from itertools import groupby
|
| 16 |
+
from pathlib import Path, PurePosixPath
|
| 17 |
+
from typing import TYPE_CHECKING, Any, BinaryIO, Literal, NamedTuple, Union
|
| 18 |
+
|
| 19 |
+
from . import constants
|
| 20 |
+
from .errors import EntryNotFoundError
|
| 21 |
+
from .file_download import hf_hub_url
|
| 22 |
+
from .lfs import UploadInfo, lfs_upload, post_lfs_batch_info
|
| 23 |
+
from .utils import (
|
| 24 |
+
FORBIDDEN_FOLDERS,
|
| 25 |
+
chunk_iterable,
|
| 26 |
+
get_session,
|
| 27 |
+
hf_raise_for_status,
|
| 28 |
+
http_backoff,
|
| 29 |
+
logging,
|
| 30 |
+
sha,
|
| 31 |
+
validate_hf_hub_args,
|
| 32 |
+
)
|
| 33 |
+
from .utils._runtime import is_xet_available
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
if TYPE_CHECKING:
|
| 37 |
+
from .hf_api import CommitInfo, RepoFile
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
logger = logging.get_logger(__name__)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
UploadMode = Literal["lfs", "regular"]
|
| 44 |
+
|
| 45 |
+
# Max is 1,000 per request on the Hub for HfApi.get_paths_info
|
| 46 |
+
# Otherwise we get:
|
| 47 |
+
# HfHubHTTPError: 413 Client Error: Payload Too Large for url: https://huggingface.co/api/datasets/xxx (Request ID: xxx)\n\ntoo many parameters
|
| 48 |
+
# See https://github.com/huggingface/huggingface_hub/issues/1503
|
| 49 |
+
FETCH_LFS_BATCH_SIZE = 500
|
| 50 |
+
DUPLICATE_LFS_BATCH_SIZE = 500
|
| 51 |
+
|
| 52 |
+
UPLOAD_BATCH_MAX_NUM_FILES = 256
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@dataclass
|
| 56 |
+
class CommitOperationDelete:
|
| 57 |
+
"""
|
| 58 |
+
Data structure holding necessary info to delete a file or a folder from a repository
|
| 59 |
+
on the Hub.
|
| 60 |
+
|
| 61 |
+
Args:
|
| 62 |
+
path_in_repo (`str`):
|
| 63 |
+
Relative filepath in the repo, for example: `"checkpoints/1fec34a/weights.bin"`
|
| 64 |
+
for a file or `"checkpoints/1fec34a/"` for a folder.
|
| 65 |
+
is_folder (`bool` or `Literal["auto"]`, *optional*):
|
| 66 |
+
Whether the Delete Operation applies to a folder or not. If "auto", the path
|
| 67 |
+
type (file or folder) is guessed automatically by looking if path ends with
|
| 68 |
+
a "/" (folder) or not (file). To explicitly set the path type, you can set
|
| 69 |
+
`is_folder=True` or `is_folder=False`.
|
| 70 |
+
"""
|
| 71 |
+
|
| 72 |
+
path_in_repo: str
|
| 73 |
+
is_folder: bool | Literal["auto"] = "auto"
|
| 74 |
+
|
| 75 |
+
def __post_init__(self):
|
| 76 |
+
self.path_in_repo = _validate_path_in_repo(self.path_in_repo)
|
| 77 |
+
|
| 78 |
+
if self.is_folder == "auto":
|
| 79 |
+
self.is_folder = self.path_in_repo.endswith("/")
|
| 80 |
+
if not isinstance(self.is_folder, bool):
|
| 81 |
+
raise ValueError(
|
| 82 |
+
f"Wrong value for `is_folder`. Must be one of [`True`, `False`, `'auto'`]. Got '{self.is_folder}'."
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
@dataclass
|
| 87 |
+
class CommitOperationCopy:
|
| 88 |
+
"""
|
| 89 |
+
Data structure holding necessary info to copy a file in a repository on the Hub.
|
| 90 |
+
|
| 91 |
+
Both LFS files and regular files are supported. LFS files are copied server-side while regular files are
|
| 92 |
+
downloaded and re-uploaded as part of the commit.
|
| 93 |
+
|
| 94 |
+
Cross-repository copies are supported by setting `src_repo_id` and `src_repo_type`. For cross-repo LFS copies,
|
| 95 |
+
the LFS objects are duplicated to the destination repository before the commit is created. This is handled
|
| 96 |
+
automatically by [`create_commit`]. Note that cross-repository copies only work within the same
|
| 97 |
+
[storage region](https://huggingface.co/docs/hub/storage-regions); copying across regions is not supported.
|
| 98 |
+
|
| 99 |
+
Note: you can combine a [`CommitOperationCopy`] and a [`CommitOperationDelete`] to rename an LFS file on the Hub.
|
| 100 |
+
|
| 101 |
+
Args:
|
| 102 |
+
src_path_in_repo (`str`):
|
| 103 |
+
Relative filepath in the repo of the file to be copied, e.g. `"checkpoints/1fec34a/weights.bin"`.
|
| 104 |
+
path_in_repo (`str`):
|
| 105 |
+
Relative filepath in the repo where to copy the file, e.g. `"checkpoints/1fec34a/weights_copy.bin"`.
|
| 106 |
+
src_revision (`str`, *optional*):
|
| 107 |
+
The git revision of the file to be copied. Can be any valid git revision.
|
| 108 |
+
Default to the target commit revision.
|
| 109 |
+
src_repo_id (`str`, *optional*):
|
| 110 |
+
The source repository to copy from (e.g. `"username/source-model"`).
|
| 111 |
+
Default to the destination repository (intra-repo copy).
|
| 112 |
+
src_repo_type (`str`, *optional*):
|
| 113 |
+
The type of the source repository (`"model"`, `"dataset"` or `"space"`).
|
| 114 |
+
Required when `src_repo_id` is set.
|
| 115 |
+
"""
|
| 116 |
+
|
| 117 |
+
src_path_in_repo: str
|
| 118 |
+
path_in_repo: str
|
| 119 |
+
src_revision: str | None = None
|
| 120 |
+
src_repo_id: str | None = None
|
| 121 |
+
src_repo_type: str | None = None
|
| 122 |
+
# set to the OID of the file to be copied if it has already been uploaded
|
| 123 |
+
# useful to determine if a commit will be empty or not.
|
| 124 |
+
_src_oid: str | None = None
|
| 125 |
+
# set to the OID of the file to copy to if it has already been uploaded
|
| 126 |
+
# useful to determine if a commit will be empty or not.
|
| 127 |
+
_dest_oid: str | None = None
|
| 128 |
+
# set to True once cross-repo LFS files have been duplicated to the destination repo
|
| 129 |
+
_is_duplicated: bool = False
|
| 130 |
+
|
| 131 |
+
def __post_init__(self):
|
| 132 |
+
self.src_path_in_repo = _validate_path_in_repo(self.src_path_in_repo)
|
| 133 |
+
self.path_in_repo = _validate_path_in_repo(self.path_in_repo)
|
| 134 |
+
if self.src_repo_id is not None and self.src_repo_type is None:
|
| 135 |
+
raise ValueError("`src_repo_type` is required when `src_repo_id` is set.")
|
| 136 |
+
if self.src_repo_type is not None and self.src_repo_id is None:
|
| 137 |
+
raise ValueError("`src_repo_id` is required when `src_repo_type` is set.")
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
@dataclass
|
| 141 |
+
class CommitOperationAdd:
|
| 142 |
+
"""
|
| 143 |
+
Data structure holding necessary info to upload a file to a repository on the Hub.
|
| 144 |
+
|
| 145 |
+
Args:
|
| 146 |
+
path_in_repo (`str`):
|
| 147 |
+
Relative filepath in the repo, for example: `"checkpoints/1fec34a/weights.bin"`
|
| 148 |
+
path_or_fileobj (`str`, `Path`, `bytes`, or `BinaryIO`):
|
| 149 |
+
Either:
|
| 150 |
+
- a path to a local file (as `str` or `pathlib.Path`) to upload
|
| 151 |
+
- a buffer of bytes (`bytes`) holding the content of the file to upload
|
| 152 |
+
- a "file object" (subclass of `io.BufferedIOBase`), typically obtained
|
| 153 |
+
with `open(path, "rb")`. It must support `seek()` and `tell()` methods.
|
| 154 |
+
|
| 155 |
+
Raises:
|
| 156 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
| 157 |
+
If `path_or_fileobj` is not one of `str`, `Path`, `bytes` or `io.BufferedIOBase`.
|
| 158 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
| 159 |
+
If `path_or_fileobj` is a `str` or `Path` but not a path to an existing file.
|
| 160 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
| 161 |
+
If `path_or_fileobj` is a `io.BufferedIOBase` but it doesn't support both
|
| 162 |
+
`seek()` and `tell()`.
|
| 163 |
+
"""
|
| 164 |
+
|
| 165 |
+
path_in_repo: str
|
| 166 |
+
path_or_fileobj: str | Path | bytes | BinaryIO
|
| 167 |
+
upload_info: UploadInfo = field(init=False, repr=False)
|
| 168 |
+
|
| 169 |
+
# Internal attributes
|
| 170 |
+
|
| 171 |
+
# set to "lfs" or "regular" once known
|
| 172 |
+
_upload_mode: UploadMode | None = field(init=False, repr=False, default=None)
|
| 173 |
+
|
| 174 |
+
# set to True if .gitignore rules prevent the file from being uploaded as LFS
|
| 175 |
+
# (server-side check)
|
| 176 |
+
_should_ignore: bool | None = field(init=False, repr=False, default=None)
|
| 177 |
+
|
| 178 |
+
# set to the remote OID of the file if it has already been uploaded
|
| 179 |
+
# useful to determine if a commit will be empty or not
|
| 180 |
+
_remote_oid: str | None = field(init=False, repr=False, default=None)
|
| 181 |
+
|
| 182 |
+
# set to True once the file has been uploaded as LFS
|
| 183 |
+
_is_uploaded: bool = field(init=False, repr=False, default=False)
|
| 184 |
+
|
| 185 |
+
# set to True once the file has been committed
|
| 186 |
+
_is_committed: bool = field(init=False, repr=False, default=False)
|
| 187 |
+
|
| 188 |
+
def __post_init__(self) -> None:
|
| 189 |
+
"""Validates `path_or_fileobj` and compute `upload_info`."""
|
| 190 |
+
self.path_in_repo = _validate_path_in_repo(self.path_in_repo)
|
| 191 |
+
|
| 192 |
+
# Validate `path_or_fileobj` value
|
| 193 |
+
if isinstance(self.path_or_fileobj, Path):
|
| 194 |
+
self.path_or_fileobj = str(self.path_or_fileobj)
|
| 195 |
+
if isinstance(self.path_or_fileobj, str):
|
| 196 |
+
self.path_or_fileobj = os.path.normpath(os.path.expanduser(self.path_or_fileobj))
|
| 197 |
+
if not os.path.isfile(self.path_or_fileobj):
|
| 198 |
+
raise ValueError(f"Provided path: '{self.path_or_fileobj}' is not a file on the local file system")
|
| 199 |
+
elif not isinstance(self.path_or_fileobj, (io.BufferedIOBase, bytes)):
|
| 200 |
+
# ^^ Inspired from: https://stackoverflow.com/questions/44584829/how-to-determine-if-file-is-opened-in-binary-or-text-mode
|
| 201 |
+
raise ValueError(
|
| 202 |
+
"path_or_fileobj must be either an instance of str, bytes or"
|
| 203 |
+
" io.BufferedIOBase. If you passed a file-like object, make sure it is"
|
| 204 |
+
" in binary mode."
|
| 205 |
+
)
|
| 206 |
+
if isinstance(self.path_or_fileobj, io.BufferedIOBase):
|
| 207 |
+
try:
|
| 208 |
+
self.path_or_fileobj.tell()
|
| 209 |
+
self.path_or_fileobj.seek(0, os.SEEK_CUR)
|
| 210 |
+
except (OSError, AttributeError) as exc:
|
| 211 |
+
raise ValueError(
|
| 212 |
+
"path_or_fileobj is a file-like object but does not implement seek() and tell()"
|
| 213 |
+
) from exc
|
| 214 |
+
|
| 215 |
+
# Compute "upload_info" attribute
|
| 216 |
+
if isinstance(self.path_or_fileobj, str):
|
| 217 |
+
self.upload_info = UploadInfo.from_path(self.path_or_fileobj)
|
| 218 |
+
elif isinstance(self.path_or_fileobj, bytes):
|
| 219 |
+
self.upload_info = UploadInfo.from_bytes(self.path_or_fileobj)
|
| 220 |
+
else:
|
| 221 |
+
self.upload_info = UploadInfo.from_fileobj(self.path_or_fileobj)
|
| 222 |
+
|
| 223 |
+
@contextmanager
|
| 224 |
+
def as_file(self, with_tqdm: bool = False) -> Iterator[BinaryIO]:
|
| 225 |
+
"""
|
| 226 |
+
A context manager that yields a file-like object allowing to read the underlying
|
| 227 |
+
data behind `path_or_fileobj`.
|
| 228 |
+
|
| 229 |
+
Args:
|
| 230 |
+
with_tqdm (`bool`, *optional*, defaults to `False`):
|
| 231 |
+
If True, iterating over the file object will display a progress bar. Only
|
| 232 |
+
works if the file-like object is a path to a file. Pure bytes and buffers
|
| 233 |
+
are not supported.
|
| 234 |
+
|
| 235 |
+
Example:
|
| 236 |
+
|
| 237 |
+
```python
|
| 238 |
+
>>> operation = CommitOperationAdd(
|
| 239 |
+
... path_in_repo="remote/dir/weights.h5",
|
| 240 |
+
... path_or_fileobj="./local/weights.h5",
|
| 241 |
+
... )
|
| 242 |
+
CommitOperationAdd(path_in_repo='remote/dir/weights.h5', path_or_fileobj='./local/weights.h5')
|
| 243 |
+
|
| 244 |
+
>>> with operation.as_file() as file:
|
| 245 |
+
... content = file.read()
|
| 246 |
+
|
| 247 |
+
>>> with operation.as_file(with_tqdm=True) as file:
|
| 248 |
+
... while True:
|
| 249 |
+
... data = file.read(1024)
|
| 250 |
+
... if not data:
|
| 251 |
+
... break
|
| 252 |
+
config.json: 100%|█████████████████████████| 8.19k/8.19k [00:02<00:00, 3.72kB/s]
|
| 253 |
+
|
| 254 |
+
>>> with operation.as_file(with_tqdm=True) as file:
|
| 255 |
+
... httpx2.put(..., data=file)
|
| 256 |
+
config.json: 100%|█████████████████████████| 8.19k/8.19k [00:02<00:00, 3.72kB/s]
|
| 257 |
+
```
|
| 258 |
+
"""
|
| 259 |
+
if isinstance(self.path_or_fileobj, str) or isinstance(self.path_or_fileobj, Path):
|
| 260 |
+
if with_tqdm:
|
| 261 |
+
from .utils import tqdm_stream_file
|
| 262 |
+
|
| 263 |
+
with tqdm_stream_file(self.path_or_fileobj) as file:
|
| 264 |
+
yield file
|
| 265 |
+
else:
|
| 266 |
+
with open(self.path_or_fileobj, "rb") as file:
|
| 267 |
+
yield file
|
| 268 |
+
elif isinstance(self.path_or_fileobj, bytes):
|
| 269 |
+
yield io.BytesIO(self.path_or_fileobj)
|
| 270 |
+
elif isinstance(self.path_or_fileobj, io.BufferedIOBase):
|
| 271 |
+
prev_pos = self.path_or_fileobj.tell()
|
| 272 |
+
yield self.path_or_fileobj
|
| 273 |
+
self.path_or_fileobj.seek(prev_pos, io.SEEK_SET)
|
| 274 |
+
|
| 275 |
+
def b64content(self) -> bytes:
|
| 276 |
+
"""
|
| 277 |
+
The base64-encoded content of `path_or_fileobj`
|
| 278 |
+
|
| 279 |
+
Returns: `bytes`
|
| 280 |
+
"""
|
| 281 |
+
with self.as_file() as file:
|
| 282 |
+
return base64.b64encode(file.read())
|
| 283 |
+
|
| 284 |
+
@property
|
| 285 |
+
def _local_oid(self) -> str | None:
|
| 286 |
+
"""Return the OID of the local file.
|
| 287 |
+
|
| 288 |
+
This OID is then compared to `self._remote_oid` to check if the file has changed compared to the remote one.
|
| 289 |
+
If the file did not change, we won't upload it again to prevent empty commits.
|
| 290 |
+
|
| 291 |
+
For LFS files, the OID corresponds to the SHA256 of the file content (used a LFS ref).
|
| 292 |
+
For regular files, the OID corresponds to the SHA1 of the file content.
|
| 293 |
+
Note: this is slightly different to git OID computation since the oid of an LFS file is usually the git-SHA1 of the
|
| 294 |
+
pointer file content (not the actual file content). However, using the SHA256 is enough to detect changes
|
| 295 |
+
and more convenient client-side.
|
| 296 |
+
"""
|
| 297 |
+
if self._upload_mode is None:
|
| 298 |
+
return None
|
| 299 |
+
elif self._upload_mode == "lfs":
|
| 300 |
+
return self.upload_info.sha256.hex()
|
| 301 |
+
else:
|
| 302 |
+
# Regular file => compute sha1
|
| 303 |
+
# => no need to read by chunk since the file is guaranteed to be <=5MB.
|
| 304 |
+
with self.as_file() as file:
|
| 305 |
+
return sha.git_hash(file.read())
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
def _validate_path_in_repo(path_in_repo: str) -> str:
|
| 309 |
+
# Validate `path_in_repo` value to prevent a server-side issue
|
| 310 |
+
if path_in_repo.startswith("/"):
|
| 311 |
+
path_in_repo = path_in_repo[1:]
|
| 312 |
+
# Reject any ".." segment, wherever it sits in the path: a segment in the middle
|
| 313 |
+
# (e.g. "a/../../etc/passwd" or "a/../file.txt") is not caught by a prefix check
|
| 314 |
+
# and can still escape the repo root once resolved.
|
| 315 |
+
if path_in_repo == "." or any(part == ".." for part in path_in_repo.split("/")):
|
| 316 |
+
raise ValueError(f"Invalid `path_in_repo` in CommitOperation: '{path_in_repo}'")
|
| 317 |
+
if path_in_repo.startswith("./"):
|
| 318 |
+
path_in_repo = path_in_repo[2:]
|
| 319 |
+
for forbidden in FORBIDDEN_FOLDERS:
|
| 320 |
+
if any(part == forbidden for part in path_in_repo.split("/")):
|
| 321 |
+
raise ValueError(
|
| 322 |
+
f"Invalid `path_in_repo` in CommitOperation: cannot update files under a '{forbidden}/' folder (path:"
|
| 323 |
+
f" '{path_in_repo}')."
|
| 324 |
+
)
|
| 325 |
+
return path_in_repo
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
CommitOperation = Union[CommitOperationAdd, CommitOperationCopy, CommitOperationDelete]
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
def _warn_on_overwriting_operations(operations: list[CommitOperation]) -> None:
|
| 332 |
+
"""
|
| 333 |
+
Warn user when a list of operations is expected to overwrite itself in a single
|
| 334 |
+
commit.
|
| 335 |
+
|
| 336 |
+
Rules:
|
| 337 |
+
- If a filepath is updated by multiple `CommitOperationAdd` operations, a warning
|
| 338 |
+
message is triggered.
|
| 339 |
+
- If a filepath is updated at least once by a `CommitOperationAdd` and then deleted
|
| 340 |
+
by a `CommitOperationDelete`, a warning is triggered.
|
| 341 |
+
- If a `CommitOperationDelete` deletes a filepath that is then updated by a
|
| 342 |
+
`CommitOperationAdd`, no warning is triggered. This is usually useless (no need to
|
| 343 |
+
delete before upload) but can happen if a user deletes an entire folder and then
|
| 344 |
+
add new files to it.
|
| 345 |
+
"""
|
| 346 |
+
nb_additions_per_path: dict[str, int] = defaultdict(int)
|
| 347 |
+
for operation in operations:
|
| 348 |
+
path_in_repo = operation.path_in_repo
|
| 349 |
+
if isinstance(operation, CommitOperationAdd):
|
| 350 |
+
if nb_additions_per_path[path_in_repo] > 0:
|
| 351 |
+
warnings.warn(
|
| 352 |
+
"About to update multiple times the same file in the same commit:"
|
| 353 |
+
f" '{path_in_repo}'. This can cause undesired inconsistencies in"
|
| 354 |
+
" your repo."
|
| 355 |
+
)
|
| 356 |
+
nb_additions_per_path[path_in_repo] += 1
|
| 357 |
+
for parent in PurePosixPath(path_in_repo).parents:
|
| 358 |
+
# Also keep track of number of updated files per folder
|
| 359 |
+
# => warns if deleting a folder overwrite some contained files
|
| 360 |
+
nb_additions_per_path[str(parent)] += 1
|
| 361 |
+
if isinstance(operation, CommitOperationDelete):
|
| 362 |
+
if nb_additions_per_path[str(PurePosixPath(path_in_repo))] > 0:
|
| 363 |
+
if operation.is_folder:
|
| 364 |
+
warnings.warn(
|
| 365 |
+
"About to delete a folder containing files that have just been"
|
| 366 |
+
f" updated within the same commit: '{path_in_repo}'. This can"
|
| 367 |
+
" cause undesired inconsistencies in your repo."
|
| 368 |
+
)
|
| 369 |
+
else:
|
| 370 |
+
warnings.warn(
|
| 371 |
+
"About to delete a file that have just been updated within the"
|
| 372 |
+
f" same commit: '{path_in_repo}'. This can cause undesired"
|
| 373 |
+
" inconsistencies in your repo."
|
| 374 |
+
)
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
@validate_hf_hub_args
|
| 378 |
+
def _upload_files(
|
| 379 |
+
*,
|
| 380 |
+
additions: list[CommitOperationAdd],
|
| 381 |
+
repo_type: str,
|
| 382 |
+
repo_id: str,
|
| 383 |
+
headers: dict[str, str],
|
| 384 |
+
endpoint: str | None = None,
|
| 385 |
+
num_threads: int = 5,
|
| 386 |
+
revision: str | None = None,
|
| 387 |
+
create_pr: bool | None = None,
|
| 388 |
+
):
|
| 389 |
+
"""
|
| 390 |
+
Uploads the files through the Xet protocol if possible, otherwise through the legacy LFS protocol.
|
| 391 |
+
|
| 392 |
+
The Xet path does not require any Python-side sha256 computation: hashing happens inside `hf_xet`
|
| 393 |
+
while chunking the files (single read pass) and is backfilled on the operations afterwards.
|
| 394 |
+
"""
|
| 395 |
+
has_buffered_io_data = any(isinstance(op.path_or_fileobj, io.BufferedIOBase) for op in additions)
|
| 396 |
+
if is_xet_available():
|
| 397 |
+
if not has_buffered_io_data:
|
| 398 |
+
_upload_xet_files(
|
| 399 |
+
additions=additions,
|
| 400 |
+
repo_type=repo_type,
|
| 401 |
+
repo_id=repo_id,
|
| 402 |
+
headers=headers,
|
| 403 |
+
endpoint=endpoint,
|
| 404 |
+
revision=revision,
|
| 405 |
+
create_pr=create_pr,
|
| 406 |
+
)
|
| 407 |
+
return
|
| 408 |
+
logger.warning(
|
| 409 |
+
"Uploading files as a binary IO buffer is not supported by Xet Storage. Falling back to HTTP upload."
|
| 410 |
+
)
|
| 411 |
+
|
| 412 |
+
# Legacy LFS path: sha256 is required by the LFS batch endpoint => compute missing ones (in parallel).
|
| 413 |
+
_compute_missing_sha256s(additions, num_threads=num_threads)
|
| 414 |
+
|
| 415 |
+
lfs_actions: list[dict[str, Any]] = []
|
| 416 |
+
lfs_oid2addop: dict[str, CommitOperationAdd] = {}
|
| 417 |
+
for chunk in chunk_iterable(additions, chunk_size=UPLOAD_BATCH_MAX_NUM_FILES):
|
| 418 |
+
chunk_list = [op for op in chunk]
|
| 419 |
+
actions_chunk, errors_chunk, _ = post_lfs_batch_info(
|
| 420 |
+
upload_infos=[op.upload_info for op in chunk_list],
|
| 421 |
+
repo_id=repo_id,
|
| 422 |
+
repo_type=repo_type,
|
| 423 |
+
revision=revision,
|
| 424 |
+
endpoint=endpoint,
|
| 425 |
+
headers=headers,
|
| 426 |
+
token=None, # already passed in 'headers'
|
| 427 |
+
transfers=["basic", "multipart"],
|
| 428 |
+
)
|
| 429 |
+
if errors_chunk:
|
| 430 |
+
message = "\n".join(
|
| 431 |
+
[
|
| 432 |
+
f"Encountered error for file with OID {err.get('oid')}: `{err.get('error', {}).get('message')}"
|
| 433 |
+
for err in errors_chunk
|
| 434 |
+
]
|
| 435 |
+
)
|
| 436 |
+
raise ValueError(f"LFS batch API returned errors:\n{message}")
|
| 437 |
+
lfs_actions.extend(actions_chunk)
|
| 438 |
+
for op in chunk_list:
|
| 439 |
+
lfs_oid2addop[op.upload_info.sha256.hex()] = op
|
| 440 |
+
|
| 441 |
+
if len(lfs_actions) > 0:
|
| 442 |
+
_upload_lfs_files(
|
| 443 |
+
actions=lfs_actions,
|
| 444 |
+
oid2addop=lfs_oid2addop,
|
| 445 |
+
headers=headers,
|
| 446 |
+
endpoint=endpoint,
|
| 447 |
+
num_threads=num_threads,
|
| 448 |
+
)
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
def _compute_missing_sha256s(additions: list[CommitOperationAdd], num_threads: int) -> None:
|
| 452 |
+
"""Compute the sha256 of the operations that don't have one yet, in parallel."""
|
| 453 |
+
not_hashed = [op for op in additions if not op.upload_info.is_hashed]
|
| 454 |
+
if len(not_hashed) == 0:
|
| 455 |
+
return
|
| 456 |
+
logger.info(f"Computing sha256 for {len(not_hashed)} files.")
|
| 457 |
+
if len(not_hashed) == 1:
|
| 458 |
+
_ = not_hashed[0].upload_info.sha256
|
| 459 |
+
return
|
| 460 |
+
with ThreadPoolExecutor(max_workers=num_threads) as executor:
|
| 461 |
+
list(executor.map(lambda op: op.upload_info.sha256, not_hashed))
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
@validate_hf_hub_args
|
| 465 |
+
def _upload_lfs_files(
|
| 466 |
+
*,
|
| 467 |
+
actions: list[dict[str, Any]],
|
| 468 |
+
oid2addop: dict[str, CommitOperationAdd],
|
| 469 |
+
headers: dict[str, str],
|
| 470 |
+
endpoint: str | None = None,
|
| 471 |
+
num_threads: int = 5,
|
| 472 |
+
):
|
| 473 |
+
"""
|
| 474 |
+
Uploads the content of `additions` to the Hub using the large file storage protocol.
|
| 475 |
+
|
| 476 |
+
Relevant external documentation:
|
| 477 |
+
- LFS Batch API: https://github.com/git-lfs/git-lfs/blob/main/docs/api/batch.md
|
| 478 |
+
|
| 479 |
+
Args:
|
| 480 |
+
actions (`list[dict[str, Any]]`):
|
| 481 |
+
LFS batch actions returned by the server.
|
| 482 |
+
oid2addop (`dict[str, CommitOperationAdd]`):
|
| 483 |
+
A dictionary mapping the OID of the file to the corresponding `CommitOperationAdd` object.
|
| 484 |
+
headers (`dict[str, str]`):
|
| 485 |
+
Headers to use for the request, including authorization headers and user agent.
|
| 486 |
+
endpoint (`str`, *optional*):
|
| 487 |
+
The endpoint to use for the request. Defaults to `constants.ENDPOINT`.
|
| 488 |
+
num_threads (`int`, *optional*):
|
| 489 |
+
The number of concurrent threads to use when uploading. Defaults to 5.
|
| 490 |
+
|
| 491 |
+
Raises:
|
| 492 |
+
[`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
|
| 493 |
+
If an upload failed for any reason
|
| 494 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
| 495 |
+
Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`.
|
| 496 |
+
repo_id (`str`):
|
| 497 |
+
A namespace (user or an organization) and a repo name separated
|
| 498 |
+
by a `/`.
|
| 499 |
+
headers (`dict[str, str]`):
|
| 500 |
+
Headers to use for the request, including authorization headers and user agent.
|
| 501 |
+
num_threads (`int`, *optional*):
|
| 502 |
+
The number of concurrent threads to use when uploading. Defaults to 5.
|
| 503 |
+
revision (`str`, *optional*):
|
| 504 |
+
The git revision to upload to.
|
| 505 |
+
|
| 506 |
+
Raises:
|
| 507 |
+
[`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
|
| 508 |
+
If an upload failed for any reason
|
| 509 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
| 510 |
+
If the server returns malformed responses
|
| 511 |
+
[`HfHubHTTPError`]
|
| 512 |
+
If the LFS batch endpoint returned an HTTP error.
|
| 513 |
+
"""
|
| 514 |
+
# Filter out files already present upstream
|
| 515 |
+
filtered_actions = []
|
| 516 |
+
for action in actions:
|
| 517 |
+
if action.get("actions") is None:
|
| 518 |
+
logger.debug(
|
| 519 |
+
f"Content of file {oid2addop[action['oid']].path_in_repo} is already present upstream - skipping upload."
|
| 520 |
+
)
|
| 521 |
+
else:
|
| 522 |
+
filtered_actions.append(action)
|
| 523 |
+
|
| 524 |
+
# Upload according to server-provided actions
|
| 525 |
+
def _wrapped_lfs_upload(batch_action) -> None:
|
| 526 |
+
try:
|
| 527 |
+
operation = oid2addop[batch_action["oid"]]
|
| 528 |
+
lfs_upload(operation=operation, lfs_batch_action=batch_action, headers=headers, endpoint=endpoint)
|
| 529 |
+
except Exception as exc:
|
| 530 |
+
raise RuntimeError(f"Error while uploading '{operation.path_in_repo}' to the Hub.") from exc
|
| 531 |
+
|
| 532 |
+
if len(filtered_actions) == 1:
|
| 533 |
+
logger.debug("Uploading 1 LFS file to the Hub")
|
| 534 |
+
_wrapped_lfs_upload(filtered_actions[0])
|
| 535 |
+
else:
|
| 536 |
+
logger.debug(
|
| 537 |
+
f"Uploading {len(filtered_actions)} LFS files to the Hub using up to {num_threads} threads concurrently"
|
| 538 |
+
)
|
| 539 |
+
from .utils import hf_thread_map
|
| 540 |
+
from .utils import tqdm as hf_tqdm
|
| 541 |
+
|
| 542 |
+
hf_thread_map(
|
| 543 |
+
_wrapped_lfs_upload,
|
| 544 |
+
filtered_actions,
|
| 545 |
+
desc=f"Upload {len(filtered_actions)} LFS files",
|
| 546 |
+
max_workers=num_threads,
|
| 547 |
+
tqdm_class=hf_tqdm,
|
| 548 |
+
)
|
| 549 |
+
|
| 550 |
+
|
| 551 |
+
@validate_hf_hub_args
|
| 552 |
+
def _upload_xet_files(
|
| 553 |
+
*,
|
| 554 |
+
additions: list[CommitOperationAdd],
|
| 555 |
+
repo_type: str,
|
| 556 |
+
repo_id: str,
|
| 557 |
+
headers: dict[str, str],
|
| 558 |
+
endpoint: str | None = None,
|
| 559 |
+
revision: str | None = None,
|
| 560 |
+
create_pr: bool | None = None,
|
| 561 |
+
):
|
| 562 |
+
"""
|
| 563 |
+
Uploads the content of `additions` to the Hub using the xet storage protocol.
|
| 564 |
+
This chunks the files and deduplicates the chunks before uploading them to xetcas storage.
|
| 565 |
+
|
| 566 |
+
Args:
|
| 567 |
+
additions (`` of `CommitOperationAdd`):
|
| 568 |
+
The files to be uploaded.
|
| 569 |
+
repo_type (`str`):
|
| 570 |
+
Type of the repo (e.g. `"model"`, `"dataset"`, `"space"`).
|
| 571 |
+
repo_id (`str`):
|
| 572 |
+
A namespace (user or an organization) and a repo name separated
|
| 573 |
+
by a `/`.
|
| 574 |
+
headers (`dict[str, str]`):
|
| 575 |
+
Headers to use for the request, including authorization headers and user agent.
|
| 576 |
+
endpoint: (`str`, *optional*):
|
| 577 |
+
The endpoint to use for the xetcas service. Defaults to `constants.ENDPOINT`.
|
| 578 |
+
revision (`str`, *optional*):
|
| 579 |
+
The git revision to upload to.
|
| 580 |
+
create_pr (`bool`, *optional*):
|
| 581 |
+
Whether or not to create a Pull Request with that commit.
|
| 582 |
+
|
| 583 |
+
Raises:
|
| 584 |
+
[`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
|
| 585 |
+
If an upload failed for any reason.
|
| 586 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
| 587 |
+
If the server returns malformed responses or if the user is unauthorized to upload to xet storage.
|
| 588 |
+
[`HfHubHTTPError`]
|
| 589 |
+
If the LFS batch endpoint returned an HTTP error.
|
| 590 |
+
|
| 591 |
+
**How it works:**
|
| 592 |
+
The file upload system uses Xet storage, which is a content-addressable storage system that breaks files into chunks
|
| 593 |
+
for efficient storage and transfer.
|
| 594 |
+
|
| 595 |
+
``session.new_upload_commit()`` manages uploading files by:
|
| 596 |
+
- Registering upload tasks and starting upload immediately in the background
|
| 597 |
+
- Breaking files into smaller chunks for efficient storage
|
| 598 |
+
- Avoiding duplicate storage by recognizing identical chunks across files
|
| 599 |
+
- Connecting to a storage server (CAS server) that manages these chunks
|
| 600 |
+
|
| 601 |
+
Authentication works transparently: the upload commit accepts a ``token_refresh_url``
|
| 602 |
+
that is used to refresh the short-lived xet write token as needed.
|
| 603 |
+
|
| 604 |
+
The upload process works like this:
|
| 605 |
+
1. Upload tasks run in parallel:
|
| 606 |
+
1.1. Read the file content from a path, bytes array, or a stream.
|
| 607 |
+
1.2. Split the file content into smaller chunks based on content patterns: each chunk gets a unique ID based on what's in it.
|
| 608 |
+
1.3. For each chunk:
|
| 609 |
+
- Check if it already exists in storage.
|
| 610 |
+
- Skip uploading chunks that already exist.
|
| 611 |
+
1.4. Group chunks into larger blocks for efficient transfer.
|
| 612 |
+
1.5. Upload these blocks to the storage server.
|
| 613 |
+
1.6. Assemble the file manifest locally and send it to the server for validation.
|
| 614 |
+
2. Return reference files that contain information about the uploaded files, which can be used later to download them.
|
| 615 |
+
"""
|
| 616 |
+
if len(additions) == 0:
|
| 617 |
+
return
|
| 618 |
+
|
| 619 |
+
# at this point, we know that hf_xet is installed
|
| 620 |
+
from .utils._xet import (
|
| 621 |
+
XetTokenType,
|
| 622 |
+
abort_xet_session,
|
| 623 |
+
get_xet_session,
|
| 624 |
+
xet_connection_info_refresh_url,
|
| 625 |
+
xet_headers_without_auth,
|
| 626 |
+
)
|
| 627 |
+
from .utils._xet_progress_reporting import XetUploadProgressReporter
|
| 628 |
+
|
| 629 |
+
refresh_url = xet_connection_info_refresh_url(
|
| 630 |
+
token_type=XetTokenType.WRITE,
|
| 631 |
+
repo_id=repo_id,
|
| 632 |
+
repo_type=repo_type,
|
| 633 |
+
revision=revision,
|
| 634 |
+
endpoint=endpoint,
|
| 635 |
+
)
|
| 636 |
+
if create_pr:
|
| 637 |
+
refresh_url += "?create_pr=1"
|
| 638 |
+
|
| 639 |
+
xet_headers = xet_headers_without_auth(headers)
|
| 640 |
+
|
| 641 |
+
import hf_xet
|
| 642 |
+
|
| 643 |
+
session = get_xet_session()
|
| 644 |
+
progress = None
|
| 645 |
+
|
| 646 |
+
def _sha256_arg(op: CommitOperationAdd):
|
| 647 |
+
# If the sha256 is already known, pass it to avoid recomputation. Otherwise let hf_xet
|
| 648 |
+
# compute it while chunking the file (single read pass) and backfill it afterwards.
|
| 649 |
+
return op.upload_info.sha256.hex() if op.upload_info.is_hashed else hf_xet.COMPUTE_SHA256
|
| 650 |
+
|
| 651 |
+
try:
|
| 652 |
+
from .utils import are_progress_bars_disabled
|
| 653 |
+
|
| 654 |
+
if not are_progress_bars_disabled():
|
| 655 |
+
progress = XetUploadProgressReporter()
|
| 656 |
+
progress_callback = progress.update_progress
|
| 657 |
+
else:
|
| 658 |
+
progress_callback = None
|
| 659 |
+
|
| 660 |
+
all_bytes_ops = [op for op in additions if isinstance(op.path_or_fileobj, bytes)]
|
| 661 |
+
all_paths_ops = [op for op in additions if isinstance(op.path_or_fileobj, (str, Path))]
|
| 662 |
+
|
| 663 |
+
handles: list[tuple[CommitOperationAdd, Any]] = []
|
| 664 |
+
with session.new_upload_commit(
|
| 665 |
+
token_refresh_url=refresh_url,
|
| 666 |
+
token_refresh_headers=headers,
|
| 667 |
+
custom_headers=xet_headers,
|
| 668 |
+
progress_callback=progress_callback,
|
| 669 |
+
) as commit:
|
| 670 |
+
for op in all_paths_ops:
|
| 671 |
+
handles.append((op, commit.start_upload_file(str(op.path_or_fileobj), sha256=_sha256_arg(op))))
|
| 672 |
+
for op in all_bytes_ops:
|
| 673 |
+
handles.append((op, commit.start_upload_bytes(op.path_or_fileobj, sha256=_sha256_arg(op))))
|
| 674 |
+
|
| 675 |
+
# Backfill sha256 computed by hf_xet (needed later for the commit payload).
|
| 676 |
+
for op, handle in handles:
|
| 677 |
+
if not op.upload_info.is_hashed:
|
| 678 |
+
op.upload_info.sha256 = bytes.fromhex(handle.result().xet_info.sha256)
|
| 679 |
+
except KeyboardInterrupt:
|
| 680 |
+
abort_xet_session()
|
| 681 |
+
raise
|
| 682 |
+
finally:
|
| 683 |
+
if progress is not None:
|
| 684 |
+
progress.close()
|
| 685 |
+
|
| 686 |
+
|
| 687 |
+
def _validate_preupload_info(preupload_info: dict):
|
| 688 |
+
files = preupload_info.get("files")
|
| 689 |
+
if not isinstance(files, list):
|
| 690 |
+
raise ValueError("preupload_info is improperly formatted")
|
| 691 |
+
for file_info in files:
|
| 692 |
+
if not (
|
| 693 |
+
isinstance(file_info, dict)
|
| 694 |
+
and isinstance(file_info.get("path"), str)
|
| 695 |
+
and isinstance(file_info.get("uploadMode"), str)
|
| 696 |
+
and (file_info["uploadMode"] in ("lfs", "regular"))
|
| 697 |
+
):
|
| 698 |
+
raise ValueError("preupload_info is improperly formatted:")
|
| 699 |
+
return preupload_info
|
| 700 |
+
|
| 701 |
+
|
| 702 |
+
@validate_hf_hub_args
|
| 703 |
+
def _fetch_upload_modes(
|
| 704 |
+
additions: Iterable[CommitOperationAdd],
|
| 705 |
+
repo_type: str,
|
| 706 |
+
repo_id: str,
|
| 707 |
+
headers: dict[str, str],
|
| 708 |
+
revision: str,
|
| 709 |
+
endpoint: str | None = None,
|
| 710 |
+
create_pr: bool = False,
|
| 711 |
+
gitignore_content: str | None = None,
|
| 712 |
+
) -> None:
|
| 713 |
+
"""
|
| 714 |
+
Requests the Hub "preupload" endpoint to determine whether each input file should be uploaded as a regular git blob,
|
| 715 |
+
as a git LFS blob, or as a XET file. Input `additions` are mutated in-place with the upload mode.
|
| 716 |
+
|
| 717 |
+
Args:
|
| 718 |
+
additions (`Iterable` of :class:`CommitOperationAdd`):
|
| 719 |
+
Iterable of :class:`CommitOperationAdd` describing the files to
|
| 720 |
+
upload to the Hub.
|
| 721 |
+
repo_type (`str`):
|
| 722 |
+
Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`.
|
| 723 |
+
repo_id (`str`):
|
| 724 |
+
A namespace (user or an organization) and a repo name separated
|
| 725 |
+
by a `/`.
|
| 726 |
+
headers (`dict[str, str]`):
|
| 727 |
+
Headers to use for the request, including authorization headers and user agent.
|
| 728 |
+
revision (`str`):
|
| 729 |
+
The git revision to upload the files to. Can be any valid git revision.
|
| 730 |
+
gitignore_content (`str`, *optional*):
|
| 731 |
+
The content of the `.gitignore` file to know which files should be ignored. The order of priority
|
| 732 |
+
is to first check if `gitignore_content` is passed, then check if the `.gitignore` file is present
|
| 733 |
+
in the list of files to commit and finally default to the `.gitignore` file already hosted on the Hub
|
| 734 |
+
(if any).
|
| 735 |
+
Raises:
|
| 736 |
+
[`~utils.HfHubHTTPError`]
|
| 737 |
+
If the Hub API returned an error.
|
| 738 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
| 739 |
+
If the Hub API response is improperly formatted.
|
| 740 |
+
"""
|
| 741 |
+
endpoint = endpoint if endpoint is not None else constants.ENDPOINT
|
| 742 |
+
|
| 743 |
+
# Fetch upload mode (LFS or regular) chunk by chunk.
|
| 744 |
+
upload_modes: dict[str, UploadMode] = {}
|
| 745 |
+
should_ignore_info: dict[str, bool] = {}
|
| 746 |
+
oid_info: dict[str, str | None] = {}
|
| 747 |
+
|
| 748 |
+
for chunk in chunk_iterable(additions, 256):
|
| 749 |
+
payload: dict = {
|
| 750 |
+
"files": [
|
| 751 |
+
{
|
| 752 |
+
"path": op.path_in_repo,
|
| 753 |
+
"sample": base64.b64encode(op.upload_info.sample).decode("ascii"),
|
| 754 |
+
"size": op.upload_info.size,
|
| 755 |
+
}
|
| 756 |
+
for op in chunk
|
| 757 |
+
]
|
| 758 |
+
}
|
| 759 |
+
if gitignore_content is not None:
|
| 760 |
+
payload["gitIgnore"] = gitignore_content
|
| 761 |
+
|
| 762 |
+
resp = http_backoff(
|
| 763 |
+
"POST",
|
| 764 |
+
f"{endpoint}/api/{repo_type}s/{repo_id}/preupload/{revision}",
|
| 765 |
+
json=payload,
|
| 766 |
+
headers=headers,
|
| 767 |
+
params={"create_pr": "1"} if create_pr else None,
|
| 768 |
+
)
|
| 769 |
+
hf_raise_for_status(resp)
|
| 770 |
+
preupload_info = _validate_preupload_info(resp.json())
|
| 771 |
+
upload_modes.update(**{file["path"]: file["uploadMode"] for file in preupload_info["files"]})
|
| 772 |
+
should_ignore_info.update(**{file["path"]: file["shouldIgnore"] for file in preupload_info["files"]})
|
| 773 |
+
oid_info.update(**{file["path"]: file.get("oid") for file in preupload_info["files"]})
|
| 774 |
+
|
| 775 |
+
# Set upload mode for each addition operation
|
| 776 |
+
for addition in additions:
|
| 777 |
+
addition._upload_mode = upload_modes[addition.path_in_repo]
|
| 778 |
+
addition._should_ignore = should_ignore_info[addition.path_in_repo]
|
| 779 |
+
addition._remote_oid = oid_info[addition.path_in_repo]
|
| 780 |
+
|
| 781 |
+
# Empty files cannot be uploaded as LFS (S3 would fail with a 501 Not Implemented)
|
| 782 |
+
# => empty files are uploaded as "regular" to still allow users to commit them.
|
| 783 |
+
for addition in additions:
|
| 784 |
+
if addition.upload_info.size == 0:
|
| 785 |
+
addition._upload_mode = "regular"
|
| 786 |
+
|
| 787 |
+
|
| 788 |
+
class _CopySource(NamedTuple):
|
| 789 |
+
src_repo_id: str | None
|
| 790 |
+
src_repo_type: str | None
|
| 791 |
+
path: str
|
| 792 |
+
revision: str | None
|
| 793 |
+
|
| 794 |
+
|
| 795 |
+
@validate_hf_hub_args
|
| 796 |
+
def _fetch_files_to_copy(
|
| 797 |
+
copies: Iterable[CommitOperationCopy],
|
| 798 |
+
repo_type: str,
|
| 799 |
+
repo_id: str,
|
| 800 |
+
headers: dict[str, str],
|
| 801 |
+
revision: str,
|
| 802 |
+
endpoint: str | None = None,
|
| 803 |
+
) -> dict[_CopySource, Union["RepoFile", bytes]]:
|
| 804 |
+
"""
|
| 805 |
+
Fetch information about the files to copy.
|
| 806 |
+
|
| 807 |
+
For LFS files, we only need their metadata (file size and sha256) while for regular files
|
| 808 |
+
we need to download the raw content from the Hub.
|
| 809 |
+
|
| 810 |
+
Args:
|
| 811 |
+
copies (`Iterable` of :class:`CommitOperationCopy`):
|
| 812 |
+
Iterable of :class:`CommitOperationCopy` describing the files to
|
| 813 |
+
copy on the Hub.
|
| 814 |
+
repo_type (`str`):
|
| 815 |
+
Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`.
|
| 816 |
+
repo_id (`str`):
|
| 817 |
+
A namespace (user or an organization) and a repo name separated
|
| 818 |
+
by a `/`.
|
| 819 |
+
headers (`dict[str, str]`):
|
| 820 |
+
Headers to use for the request, including authorization headers and user agent.
|
| 821 |
+
revision (`str`):
|
| 822 |
+
The git revision to upload the files to. Can be any valid git revision.
|
| 823 |
+
|
| 824 |
+
Returns: `dict[_CopySource, Union[RepoFile, bytes]]]`
|
| 825 |
+
Key is `(src_repo_id, src_repo_type, path, revision)`. For intra-repo copies,
|
| 826 |
+
`src_repo_id` and `src_repo_type` are `None`.
|
| 827 |
+
Value is the raw content as bytes (for regular files) or the file information as a RepoFile (for LFS files).
|
| 828 |
+
|
| 829 |
+
Raises:
|
| 830 |
+
[`~utils.HfHubHTTPError`]
|
| 831 |
+
If the Hub API returned an error.
|
| 832 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
| 833 |
+
If the Hub API response is improperly formatted.
|
| 834 |
+
"""
|
| 835 |
+
from .hf_api import HfApi, RepoFolder
|
| 836 |
+
|
| 837 |
+
hf_api = HfApi(endpoint=endpoint, headers=headers)
|
| 838 |
+
copies = list(copies)
|
| 839 |
+
files_to_copy: dict[_CopySource, Union["RepoFile", bytes]] = {}
|
| 840 |
+
oid_info: dict[tuple[str, str | None], str | None] = {}
|
| 841 |
+
|
| 842 |
+
# 1. Fetch OIDs for destination paths in batches.
|
| 843 |
+
dest_paths = [op.path_in_repo for op in copies]
|
| 844 |
+
for batch in chunk_iterable(dest_paths, FETCH_LFS_BATCH_SIZE):
|
| 845 |
+
dest_repo_files = hf_api.get_paths_info(
|
| 846 |
+
repo_id=repo_id,
|
| 847 |
+
paths=list(batch),
|
| 848 |
+
revision=revision,
|
| 849 |
+
repo_type=repo_type,
|
| 850 |
+
)
|
| 851 |
+
for file in dest_repo_files:
|
| 852 |
+
if not isinstance(file, RepoFolder):
|
| 853 |
+
oid_info[(file.path, revision)] = file.blob_id
|
| 854 |
+
|
| 855 |
+
# 2. Fetch source file info, grouped by (src_repo_id, src_repo_type, src_revision).
|
| 856 |
+
copies.sort(key=lambda op: (op.src_repo_id or "", op.src_repo_type or "", op.src_revision or ""))
|
| 857 |
+
for (src_repo_id_key, src_repo_type_key, src_revision_key), group in groupby(
|
| 858 |
+
copies, key=lambda op: (op.src_repo_id, op.src_repo_type, op.src_revision)
|
| 859 |
+
):
|
| 860 |
+
operations = list(group)
|
| 861 |
+
is_cross_repo = src_repo_id_key is not None
|
| 862 |
+
eff_repo_id = src_repo_id_key or repo_id
|
| 863 |
+
eff_repo_type = src_repo_type_key or repo_type
|
| 864 |
+
eff_revision = src_revision_key or ("main" if is_cross_repo else revision)
|
| 865 |
+
|
| 866 |
+
src_paths = [op.src_path_in_repo for op in operations]
|
| 867 |
+
for paths_batch in chunk_iterable(src_paths, FETCH_LFS_BATCH_SIZE):
|
| 868 |
+
src_repo_files = hf_api.get_paths_info(
|
| 869 |
+
repo_id=eff_repo_id,
|
| 870 |
+
paths=list(paths_batch),
|
| 871 |
+
revision=eff_revision,
|
| 872 |
+
repo_type=eff_repo_type,
|
| 873 |
+
)
|
| 874 |
+
for src_repo_file in src_repo_files:
|
| 875 |
+
if isinstance(src_repo_file, RepoFolder):
|
| 876 |
+
raise NotImplementedError("Copying a folder is not implemented.")
|
| 877 |
+
source = _CopySource(src_repo_id_key, src_repo_type_key, src_repo_file.path, src_revision_key)
|
| 878 |
+
if src_repo_file.lfs:
|
| 879 |
+
files_to_copy[source] = src_repo_file
|
| 880 |
+
else:
|
| 881 |
+
url = hf_hub_url(
|
| 882 |
+
endpoint=endpoint,
|
| 883 |
+
repo_type=eff_repo_type,
|
| 884 |
+
repo_id=eff_repo_id,
|
| 885 |
+
revision=eff_revision,
|
| 886 |
+
filename=src_repo_file.path,
|
| 887 |
+
)
|
| 888 |
+
response = get_session().get(url, headers=headers)
|
| 889 |
+
hf_raise_for_status(response)
|
| 890 |
+
files_to_copy[source] = response.content
|
| 891 |
+
if not is_cross_repo:
|
| 892 |
+
oid_info[(src_repo_file.path, src_revision_key)] = src_repo_file.blob_id
|
| 893 |
+
|
| 894 |
+
for operation in operations:
|
| 895 |
+
key = _CopySource(src_repo_id_key, src_repo_type_key, operation.src_path_in_repo, src_revision_key)
|
| 896 |
+
if key not in files_to_copy:
|
| 897 |
+
source_desc = f" from {eff_repo_type}s/{eff_repo_id}" if is_cross_repo else ""
|
| 898 |
+
raise EntryNotFoundError(
|
| 899 |
+
f"Cannot copy {operation.src_path_in_repo} at revision "
|
| 900 |
+
f"{eff_revision}{source_desc}: file is missing on repo."
|
| 901 |
+
)
|
| 902 |
+
operation._dest_oid = oid_info.get((operation.path_in_repo, revision))
|
| 903 |
+
if not is_cross_repo:
|
| 904 |
+
operation._src_oid = oid_info.get((operation.src_path_in_repo, operation.src_revision))
|
| 905 |
+
|
| 906 |
+
return files_to_copy
|
| 907 |
+
|
| 908 |
+
|
| 909 |
+
def _prepare_commit_payload(
|
| 910 |
+
operations: Iterable[CommitOperation],
|
| 911 |
+
files_to_copy: dict[_CopySource, Union["RepoFile", bytes]],
|
| 912 |
+
commit_message: str,
|
| 913 |
+
commit_description: str | None = None,
|
| 914 |
+
parent_commit: str | None = None,
|
| 915 |
+
) -> Iterable[dict[str, Any]]:
|
| 916 |
+
"""
|
| 917 |
+
Builds the payload to POST to the `/commit` API of the Hub.
|
| 918 |
+
|
| 919 |
+
Payload is returned as an iterator so that it can be streamed as a ndjson in the
|
| 920 |
+
POST request.
|
| 921 |
+
|
| 922 |
+
For more information, see:
|
| 923 |
+
- https://github.com/huggingface/huggingface_hub/issues/1085#issuecomment-1265208073
|
| 924 |
+
- http://ndjson.org/
|
| 925 |
+
"""
|
| 926 |
+
commit_description = commit_description if commit_description is not None else ""
|
| 927 |
+
|
| 928 |
+
# 1. Send a header item with the commit metadata
|
| 929 |
+
header_value = {"summary": commit_message, "description": commit_description}
|
| 930 |
+
if parent_commit is not None:
|
| 931 |
+
header_value["parentCommit"] = parent_commit
|
| 932 |
+
yield {"key": "header", "value": header_value}
|
| 933 |
+
|
| 934 |
+
nb_ignored_files = 0
|
| 935 |
+
|
| 936 |
+
# 2. Send operations, one per line
|
| 937 |
+
for operation in operations:
|
| 938 |
+
# Skip ignored files
|
| 939 |
+
if isinstance(operation, CommitOperationAdd) and operation._should_ignore:
|
| 940 |
+
logger.debug(f"Skipping file '{operation.path_in_repo}' in commit (ignored by gitignore file).")
|
| 941 |
+
nb_ignored_files += 1
|
| 942 |
+
continue
|
| 943 |
+
|
| 944 |
+
# 2.a. Case adding a regular file
|
| 945 |
+
if isinstance(operation, CommitOperationAdd) and operation._upload_mode == "regular":
|
| 946 |
+
yield {
|
| 947 |
+
"key": "file",
|
| 948 |
+
"value": {
|
| 949 |
+
"content": operation.b64content().decode(),
|
| 950 |
+
"path": operation.path_in_repo,
|
| 951 |
+
"encoding": "base64",
|
| 952 |
+
},
|
| 953 |
+
}
|
| 954 |
+
# 2.b. Case adding an LFS file
|
| 955 |
+
elif isinstance(operation, CommitOperationAdd) and operation._upload_mode == "lfs":
|
| 956 |
+
yield {
|
| 957 |
+
"key": "lfsFile",
|
| 958 |
+
"value": {
|
| 959 |
+
"path": operation.path_in_repo,
|
| 960 |
+
"algo": "sha256",
|
| 961 |
+
"oid": operation.upload_info.sha256.hex(),
|
| 962 |
+
"size": operation.upload_info.size,
|
| 963 |
+
},
|
| 964 |
+
}
|
| 965 |
+
# 2.c. Case deleting a file or folder
|
| 966 |
+
elif isinstance(operation, CommitOperationDelete):
|
| 967 |
+
yield {
|
| 968 |
+
"key": "deletedFolder" if operation.is_folder else "deletedFile",
|
| 969 |
+
"value": {"path": operation.path_in_repo},
|
| 970 |
+
}
|
| 971 |
+
# 2.d. Case copying a file or folder
|
| 972 |
+
elif isinstance(operation, CommitOperationCopy):
|
| 973 |
+
source = _CopySource(
|
| 974 |
+
operation.src_repo_id,
|
| 975 |
+
operation.src_repo_type,
|
| 976 |
+
operation.src_path_in_repo,
|
| 977 |
+
operation.src_revision,
|
| 978 |
+
)
|
| 979 |
+
file_to_copy = files_to_copy[source]
|
| 980 |
+
if isinstance(file_to_copy, bytes):
|
| 981 |
+
yield {
|
| 982 |
+
"key": "file",
|
| 983 |
+
"value": {
|
| 984 |
+
"content": base64.b64encode(file_to_copy).decode(),
|
| 985 |
+
"path": operation.path_in_repo,
|
| 986 |
+
"encoding": "base64",
|
| 987 |
+
},
|
| 988 |
+
}
|
| 989 |
+
elif file_to_copy.lfs:
|
| 990 |
+
yield {
|
| 991 |
+
"key": "lfsFile",
|
| 992 |
+
"value": {
|
| 993 |
+
"path": operation.path_in_repo,
|
| 994 |
+
"algo": "sha256",
|
| 995 |
+
"oid": file_to_copy.lfs.sha256,
|
| 996 |
+
},
|
| 997 |
+
}
|
| 998 |
+
else:
|
| 999 |
+
raise ValueError(
|
| 1000 |
+
"Malformed files_to_copy (should be raw file content as bytes or RepoFile objects with LFS info."
|
| 1001 |
+
)
|
| 1002 |
+
# 2.e. Never expected to happen
|
| 1003 |
+
else:
|
| 1004 |
+
raise ValueError(
|
| 1005 |
+
f"Unknown operation to commit. Operation: {operation}. Upload mode:"
|
| 1006 |
+
f" {getattr(operation, '_upload_mode', None)}"
|
| 1007 |
+
)
|
| 1008 |
+
|
| 1009 |
+
if nb_ignored_files > 0:
|
| 1010 |
+
logger.info(f"Skipped {nb_ignored_files} file(s) in commit (ignored by gitignore file).")
|
| 1011 |
+
|
| 1012 |
+
|
| 1013 |
+
def _send_commit(
|
| 1014 |
+
*,
|
| 1015 |
+
operations: Iterable[CommitOperation],
|
| 1016 |
+
files_to_copy: dict[_CopySource, Union["RepoFile", bytes]],
|
| 1017 |
+
commit_message: str,
|
| 1018 |
+
commit_description: str,
|
| 1019 |
+
repo_type: str,
|
| 1020 |
+
repo_id: str,
|
| 1021 |
+
headers: dict[str, str],
|
| 1022 |
+
revision: str,
|
| 1023 |
+
endpoint: str | None = None,
|
| 1024 |
+
parent_commit: str | None = None,
|
| 1025 |
+
create_pr: bool = False,
|
| 1026 |
+
hot_reload: bool = False,
|
| 1027 |
+
retry_on_error: bool = False,
|
| 1028 |
+
) -> "CommitInfo":
|
| 1029 |
+
"""
|
| 1030 |
+
Build the ndjson payload for `operations` and POST it to the `/commit` endpoint of the Hub.
|
| 1031 |
+
|
| 1032 |
+
`revision` must already be URL-quoted. Operations must be ready to commit: upload modes fetched
|
| 1033 |
+
and LFS/Xet content uploaded.
|
| 1034 |
+
|
| 1035 |
+
If `retry_on_error` is `True`, the POST is retried with exponential backoff on transient errors.
|
| 1036 |
+
Caution: if a commit succeeds but its response is lost, the retry will create a duplicate commit
|
| 1037 |
+
(and a duplicate pull request if `create_pr` is set) — only enable it when this is acceptable.
|
| 1038 |
+
|
| 1039 |
+
Returns a [`CommitInfo`] built from the server response.
|
| 1040 |
+
|
| 1041 |
+
Raises:
|
| 1042 |
+
[`~utils.HfHubHTTPError`]
|
| 1043 |
+
If the Hub API returned an error.
|
| 1044 |
+
"""
|
| 1045 |
+
endpoint = endpoint if endpoint is not None else constants.ENDPOINT
|
| 1046 |
+
payload = _prepare_commit_payload(
|
| 1047 |
+
operations=operations,
|
| 1048 |
+
files_to_copy=files_to_copy,
|
| 1049 |
+
commit_message=commit_message,
|
| 1050 |
+
commit_description=commit_description,
|
| 1051 |
+
parent_commit=parent_commit,
|
| 1052 |
+
)
|
| 1053 |
+
data = b"".join(json.dumps(item).encode() + b"\n" for item in payload)
|
| 1054 |
+
# See https://github.com/huggingface/huggingface_hub/issues/1085#issuecomment-1265208073
|
| 1055 |
+
headers = {"Content-Type": "application/x-ndjson", **headers}
|
| 1056 |
+
url = f"{endpoint}/api/{repo_type}s/{repo_id}/commit/{revision}"
|
| 1057 |
+
|
| 1058 |
+
params: dict[str, str] = {}
|
| 1059 |
+
if create_pr:
|
| 1060 |
+
params["create_pr"] = "1"
|
| 1061 |
+
if hot_reload:
|
| 1062 |
+
params["hot_reload"] = "1"
|
| 1063 |
+
|
| 1064 |
+
if retry_on_error:
|
| 1065 |
+
response = http_backoff("POST", url, headers=headers, content=data, params=params)
|
| 1066 |
+
else:
|
| 1067 |
+
response = get_session().post(url, headers=headers, content=data, params=params)
|
| 1068 |
+
hf_raise_for_status(response, endpoint_name="commit")
|
| 1069 |
+
|
| 1070 |
+
commit_data = response.json()
|
| 1071 |
+
from .hf_api import CommitInfo
|
| 1072 |
+
|
| 1073 |
+
return CommitInfo(
|
| 1074 |
+
commit_url=commit_data["commitUrl"],
|
| 1075 |
+
commit_message=commit_message,
|
| 1076 |
+
commit_description=commit_description,
|
| 1077 |
+
oid=commit_data["commitOid"],
|
| 1078 |
+
pr_url=commit_data["pullRequestUrl"] if create_pr else None,
|
| 1079 |
+
_endpoint=endpoint,
|
| 1080 |
+
)
|
.venv/lib/python3.12/site-packages/huggingface_hub/_commit_scheduler.py
ADDED
|
@@ -0,0 +1,353 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import atexit
|
| 2 |
+
import logging
|
| 3 |
+
import os
|
| 4 |
+
import time
|
| 5 |
+
from concurrent.futures import Future
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
from io import SEEK_END, SEEK_SET, BytesIO
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from threading import Lock, Thread
|
| 10 |
+
from typing import Optional
|
| 11 |
+
|
| 12 |
+
from ._commit_api import CommitOperationAdd
|
| 13 |
+
from .hf_api import DEFAULT_IGNORE_PATTERNS, CommitInfo, HfApi
|
| 14 |
+
from .utils import filter_repo_objects
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
logger = logging.getLogger(__name__)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@dataclass(frozen=True)
|
| 21 |
+
class _FileToUpload:
|
| 22 |
+
"""Temporary dataclass to store info about files to upload. Not meant to be used directly."""
|
| 23 |
+
|
| 24 |
+
local_path: Path
|
| 25 |
+
path_in_repo: str
|
| 26 |
+
size_limit: int
|
| 27 |
+
last_modified: float
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class CommitScheduler:
|
| 31 |
+
"""
|
| 32 |
+
Scheduler to upload a local folder to the Hub at regular intervals (e.g. push to hub every 5 minutes).
|
| 33 |
+
|
| 34 |
+
The recommended way to use the scheduler is to use it as a context manager. This ensures that the scheduler is
|
| 35 |
+
properly stopped and the last commit is triggered when the script ends. The scheduler can also be stopped manually
|
| 36 |
+
with the `stop` method. Checkout the [upload guide](https://huggingface.co/docs/huggingface_hub/guides/upload#scheduled-uploads)
|
| 37 |
+
to learn more about how to use it.
|
| 38 |
+
|
| 39 |
+
Args:
|
| 40 |
+
repo_id (`str`):
|
| 41 |
+
The id of the repo to commit to.
|
| 42 |
+
folder_path (`str` or `Path`):
|
| 43 |
+
Path to the local folder to upload regularly.
|
| 44 |
+
every (`int` or `float`, *optional*):
|
| 45 |
+
The number of minutes between each commit. Defaults to 5 minutes.
|
| 46 |
+
path_in_repo (`str`, *optional*):
|
| 47 |
+
Relative path of the directory in the repo, for example: `"checkpoints/"`. Defaults to the root folder
|
| 48 |
+
of the repository.
|
| 49 |
+
repo_type (`str`, *optional*):
|
| 50 |
+
The type of the repo to commit to. Defaults to `model`.
|
| 51 |
+
revision (`str`, *optional*):
|
| 52 |
+
The revision of the repo to commit to. Defaults to `main`.
|
| 53 |
+
private (`bool`, *optional*):
|
| 54 |
+
Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists.
|
| 55 |
+
token (`str`, *optional*):
|
| 56 |
+
The token to use to commit to the repo. Defaults to the token saved on the machine.
|
| 57 |
+
allow_patterns (`list[str]` or `str`, *optional*):
|
| 58 |
+
If provided, only files matching at least one pattern are uploaded.
|
| 59 |
+
ignore_patterns (`list[str]` or `str`, *optional*):
|
| 60 |
+
If provided, files matching any of the patterns are not uploaded.
|
| 61 |
+
squash_history (`bool`, *optional*):
|
| 62 |
+
Whether to squash the history of the repo after each commit. Defaults to `False`. Squashing commits is
|
| 63 |
+
useful to avoid degraded performances on the repo when it grows too large.
|
| 64 |
+
hf_api (`HfApi`, *optional*):
|
| 65 |
+
The [`HfApi`] client to use to commit to the Hub. Can be set with custom settings (user agent, token,...).
|
| 66 |
+
|
| 67 |
+
Example:
|
| 68 |
+
```py
|
| 69 |
+
>>> from pathlib import Path
|
| 70 |
+
>>> from huggingface_hub import CommitScheduler
|
| 71 |
+
|
| 72 |
+
# Scheduler uploads every 10 minutes
|
| 73 |
+
>>> csv_path = Path("watched_folder/data.csv")
|
| 74 |
+
>>> CommitScheduler(repo_id="test_scheduler", repo_type="dataset", folder_path=csv_path.parent, every=10)
|
| 75 |
+
|
| 76 |
+
>>> with csv_path.open("a") as f:
|
| 77 |
+
... f.write("first line")
|
| 78 |
+
|
| 79 |
+
# Some time later (...)
|
| 80 |
+
>>> with csv_path.open("a") as f:
|
| 81 |
+
... f.write("second line")
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
Example using a context manager:
|
| 85 |
+
```py
|
| 86 |
+
>>> from pathlib import Path
|
| 87 |
+
>>> from huggingface_hub import CommitScheduler
|
| 88 |
+
|
| 89 |
+
>>> with CommitScheduler(repo_id="test_scheduler", repo_type="dataset", folder_path="watched_folder", every=10) as scheduler:
|
| 90 |
+
... csv_path = Path("watched_folder/data.csv")
|
| 91 |
+
... with csv_path.open("a") as f:
|
| 92 |
+
... f.write("first line")
|
| 93 |
+
... (...)
|
| 94 |
+
... with csv_path.open("a") as f:
|
| 95 |
+
... f.write("second line")
|
| 96 |
+
|
| 97 |
+
# Scheduler is now stopped and last commit have been triggered
|
| 98 |
+
```
|
| 99 |
+
"""
|
| 100 |
+
|
| 101 |
+
def __init__(
|
| 102 |
+
self,
|
| 103 |
+
*,
|
| 104 |
+
repo_id: str,
|
| 105 |
+
folder_path: str | Path,
|
| 106 |
+
every: int | float = 5,
|
| 107 |
+
path_in_repo: str | None = None,
|
| 108 |
+
repo_type: str | None = None,
|
| 109 |
+
revision: str | None = None,
|
| 110 |
+
private: bool | None = None,
|
| 111 |
+
token: str | None = None,
|
| 112 |
+
allow_patterns: list[str] | str | None = None,
|
| 113 |
+
ignore_patterns: list[str] | str | None = None,
|
| 114 |
+
squash_history: bool = False,
|
| 115 |
+
hf_api: Optional["HfApi"] = None,
|
| 116 |
+
) -> None:
|
| 117 |
+
self.api = hf_api or HfApi(token=token)
|
| 118 |
+
|
| 119 |
+
# Folder
|
| 120 |
+
self.folder_path = Path(folder_path).expanduser().resolve()
|
| 121 |
+
self.path_in_repo = path_in_repo or ""
|
| 122 |
+
self.allow_patterns = allow_patterns
|
| 123 |
+
|
| 124 |
+
if ignore_patterns is None:
|
| 125 |
+
ignore_patterns = []
|
| 126 |
+
elif isinstance(ignore_patterns, str):
|
| 127 |
+
ignore_patterns = [ignore_patterns]
|
| 128 |
+
self.ignore_patterns = ignore_patterns + DEFAULT_IGNORE_PATTERNS
|
| 129 |
+
|
| 130 |
+
if self.folder_path.is_file():
|
| 131 |
+
raise ValueError(f"'folder_path' must be a directory, not a file: '{self.folder_path}'.")
|
| 132 |
+
self.folder_path.mkdir(parents=True, exist_ok=True)
|
| 133 |
+
|
| 134 |
+
# Repository
|
| 135 |
+
repo_url = self.api.create_repo(repo_id=repo_id, private=private, repo_type=repo_type, exist_ok=True)
|
| 136 |
+
self.repo_id = repo_url.repo_id
|
| 137 |
+
self.repo_type = repo_type
|
| 138 |
+
self.revision = revision
|
| 139 |
+
self.token = token
|
| 140 |
+
|
| 141 |
+
# Keep track of already uploaded files
|
| 142 |
+
self.last_uploaded: dict[Path, float] = {} # key is local path, value is timestamp
|
| 143 |
+
|
| 144 |
+
# Scheduler
|
| 145 |
+
if not every > 0:
|
| 146 |
+
raise ValueError(f"'every' must be a positive integer, not '{every}'.")
|
| 147 |
+
self.lock = Lock()
|
| 148 |
+
self.every = every
|
| 149 |
+
self.squash_history = squash_history
|
| 150 |
+
self.__stopped = False
|
| 151 |
+
|
| 152 |
+
logger.info(f"Scheduled job to push '{self.folder_path}' to '{self.repo_id}' every {self.every} minutes.")
|
| 153 |
+
self._scheduler_thread = Thread(target=self._run_scheduler, daemon=True)
|
| 154 |
+
self._scheduler_thread.start()
|
| 155 |
+
atexit.register(self._push_to_hub)
|
| 156 |
+
|
| 157 |
+
def stop(self) -> None:
|
| 158 |
+
"""Stop the scheduler.
|
| 159 |
+
|
| 160 |
+
A stopped scheduler cannot be restarted. Mostly for tests purposes.
|
| 161 |
+
"""
|
| 162 |
+
self.__stopped = True
|
| 163 |
+
|
| 164 |
+
def __enter__(self) -> "CommitScheduler":
|
| 165 |
+
return self
|
| 166 |
+
|
| 167 |
+
def __exit__(self, exc_type, exc_value, traceback) -> None:
|
| 168 |
+
# Upload last changes before exiting
|
| 169 |
+
self.trigger().result()
|
| 170 |
+
self.stop()
|
| 171 |
+
return
|
| 172 |
+
|
| 173 |
+
def _run_scheduler(self) -> None:
|
| 174 |
+
"""Dumb thread waiting between each scheduled push to Hub."""
|
| 175 |
+
while True:
|
| 176 |
+
self.last_future = self.trigger()
|
| 177 |
+
time.sleep(self.every * 60)
|
| 178 |
+
if self.__stopped:
|
| 179 |
+
break
|
| 180 |
+
|
| 181 |
+
def trigger(self) -> Future:
|
| 182 |
+
"""Trigger a `push_to_hub` and return a future.
|
| 183 |
+
|
| 184 |
+
This method is automatically called every `every` minutes. You can also call it manually to trigger a commit
|
| 185 |
+
immediately, without waiting for the next scheduled commit.
|
| 186 |
+
"""
|
| 187 |
+
return self.api.run_as_future(self._push_to_hub)
|
| 188 |
+
|
| 189 |
+
def _push_to_hub(self) -> CommitInfo | None:
|
| 190 |
+
if self.__stopped: # If stopped, already scheduled commits are ignored
|
| 191 |
+
return None
|
| 192 |
+
|
| 193 |
+
logger.info("(Background) scheduled commit triggered.")
|
| 194 |
+
try:
|
| 195 |
+
value = self.push_to_hub()
|
| 196 |
+
if self.squash_history:
|
| 197 |
+
logger.info("(Background) squashing repo history.")
|
| 198 |
+
self.api.super_squash_history(repo_id=self.repo_id, repo_type=self.repo_type, branch=self.revision)
|
| 199 |
+
return value
|
| 200 |
+
except Exception as e:
|
| 201 |
+
logger.error(f"Error while pushing to Hub: {e}") # Depending on the setup, error might be silenced
|
| 202 |
+
raise
|
| 203 |
+
|
| 204 |
+
def push_to_hub(self) -> CommitInfo | None:
|
| 205 |
+
"""
|
| 206 |
+
Push folder to the Hub and return the commit info.
|
| 207 |
+
|
| 208 |
+
> [!WARNING]
|
| 209 |
+
> This method is not meant to be called directly. It is run in the background by the scheduler, respecting a
|
| 210 |
+
> queue mechanism to avoid concurrent commits. Making a direct call to the method might lead to concurrency
|
| 211 |
+
> issues.
|
| 212 |
+
|
| 213 |
+
The default behavior of `push_to_hub` is to assume an append-only folder. It lists all files in the folder and
|
| 214 |
+
uploads only changed files. If no changes are found, the method returns without committing anything. If you want
|
| 215 |
+
to change this behavior, you can inherit from [`CommitScheduler`] and override this method. This can be useful
|
| 216 |
+
for example to compress data together in a single file before committing. For more details and examples, check
|
| 217 |
+
out our [integration guide](https://huggingface.co/docs/huggingface_hub/main/en/guides/upload#scheduled-uploads).
|
| 218 |
+
"""
|
| 219 |
+
# Check files to upload (with lock)
|
| 220 |
+
with self.lock:
|
| 221 |
+
logger.debug("Listing files to upload for scheduled commit.")
|
| 222 |
+
|
| 223 |
+
# List files from folder (taken from `_prepare_upload_folder_additions`)
|
| 224 |
+
relpath_to_abspath = {
|
| 225 |
+
path.relative_to(self.folder_path).as_posix(): path
|
| 226 |
+
for path in sorted(self.folder_path.glob("**/*")) # sorted to be deterministic
|
| 227 |
+
if path.is_file()
|
| 228 |
+
}
|
| 229 |
+
prefix = f"{self.path_in_repo.strip('/')}/" if self.path_in_repo else ""
|
| 230 |
+
|
| 231 |
+
# Filter with pattern + filter out unchanged files + retrieve current file size
|
| 232 |
+
files_to_upload: list[_FileToUpload] = []
|
| 233 |
+
for relpath in filter_repo_objects(
|
| 234 |
+
relpath_to_abspath.keys(), allow_patterns=self.allow_patterns, ignore_patterns=self.ignore_patterns
|
| 235 |
+
):
|
| 236 |
+
local_path = relpath_to_abspath[relpath]
|
| 237 |
+
stat = local_path.stat()
|
| 238 |
+
if self.last_uploaded.get(local_path) is None or self.last_uploaded[local_path] != stat.st_mtime:
|
| 239 |
+
files_to_upload.append(
|
| 240 |
+
_FileToUpload(
|
| 241 |
+
local_path=local_path,
|
| 242 |
+
path_in_repo=prefix + relpath,
|
| 243 |
+
size_limit=stat.st_size,
|
| 244 |
+
last_modified=stat.st_mtime,
|
| 245 |
+
)
|
| 246 |
+
)
|
| 247 |
+
|
| 248 |
+
# Return if nothing to upload
|
| 249 |
+
if len(files_to_upload) == 0:
|
| 250 |
+
logger.debug("Dropping schedule commit: no changed file to upload.")
|
| 251 |
+
return None
|
| 252 |
+
|
| 253 |
+
# Convert `_FileToUpload` as `CommitOperationAdd` (=> compute file shas + limit to file size)
|
| 254 |
+
logger.debug("Removing unchanged files since previous scheduled commit.")
|
| 255 |
+
add_operations = [
|
| 256 |
+
CommitOperationAdd(
|
| 257 |
+
# Cap the file to its current size, even if the user append data to it while a scheduled commit is happening
|
| 258 |
+
path_or_fileobj=PartialFileIO(file_to_upload.local_path, size_limit=file_to_upload.size_limit),
|
| 259 |
+
path_in_repo=file_to_upload.path_in_repo,
|
| 260 |
+
)
|
| 261 |
+
for file_to_upload in files_to_upload
|
| 262 |
+
]
|
| 263 |
+
|
| 264 |
+
# Upload files (append mode expected - no need for lock)
|
| 265 |
+
logger.debug("Uploading files for scheduled commit.")
|
| 266 |
+
commit_info = self.api.create_commit(
|
| 267 |
+
repo_id=self.repo_id,
|
| 268 |
+
repo_type=self.repo_type,
|
| 269 |
+
operations=add_operations,
|
| 270 |
+
commit_message="Scheduled Commit",
|
| 271 |
+
revision=self.revision,
|
| 272 |
+
)
|
| 273 |
+
|
| 274 |
+
# Successful commit: keep track of the latest "last_modified" for each file
|
| 275 |
+
for file in files_to_upload:
|
| 276 |
+
self.last_uploaded[file.local_path] = file.last_modified
|
| 277 |
+
return commit_info
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
class PartialFileIO(BytesIO):
|
| 281 |
+
"""A file-like object that reads only the first part of a file.
|
| 282 |
+
|
| 283 |
+
Useful to upload a file to the Hub when the user might still be appending data to it. Only the first part of the
|
| 284 |
+
file is uploaded (i.e. the part that was available when the filesystem was first scanned).
|
| 285 |
+
|
| 286 |
+
In practice, only used internally by the CommitScheduler to regularly push a folder to the Hub with minimal
|
| 287 |
+
disturbance for the user. The object is passed to `CommitOperationAdd`.
|
| 288 |
+
|
| 289 |
+
Only supports `read`, `tell` and `seek` methods.
|
| 290 |
+
|
| 291 |
+
Args:
|
| 292 |
+
file_path (`str` or `Path`):
|
| 293 |
+
Path to the file to read.
|
| 294 |
+
size_limit (`int`):
|
| 295 |
+
The maximum number of bytes to read from the file. If the file is larger than this, only the first part
|
| 296 |
+
will be read (and uploaded).
|
| 297 |
+
"""
|
| 298 |
+
|
| 299 |
+
def __init__(self, file_path: str | Path, size_limit: int) -> None:
|
| 300 |
+
self._file_path = Path(file_path)
|
| 301 |
+
self._file = self._file_path.open("rb")
|
| 302 |
+
self._size_limit = min(size_limit, os.fstat(self._file.fileno()).st_size)
|
| 303 |
+
|
| 304 |
+
def __del__(self) -> None:
|
| 305 |
+
self._file.close()
|
| 306 |
+
return super().__del__()
|
| 307 |
+
|
| 308 |
+
def __repr__(self) -> str:
|
| 309 |
+
return f"<PartialFileIO file_path={self._file_path} size_limit={self._size_limit}>"
|
| 310 |
+
|
| 311 |
+
def __len__(self) -> int:
|
| 312 |
+
return self._size_limit
|
| 313 |
+
|
| 314 |
+
def __getattribute__(self, name: str):
|
| 315 |
+
if name.startswith("_") or name in ("read", "tell", "seek", "fileno"): # only 4 public methods supported
|
| 316 |
+
return super().__getattribute__(name)
|
| 317 |
+
raise NotImplementedError(f"PartialFileIO does not support '{name}'.")
|
| 318 |
+
|
| 319 |
+
def fileno(self):
|
| 320 |
+
raise AttributeError("PartialFileIO does not have a fileno.")
|
| 321 |
+
|
| 322 |
+
def tell(self) -> int:
|
| 323 |
+
"""Return the current file position."""
|
| 324 |
+
return self._file.tell()
|
| 325 |
+
|
| 326 |
+
def seek(self, __offset: int, __whence: int = SEEK_SET) -> int:
|
| 327 |
+
"""Change the stream position to the given offset.
|
| 328 |
+
|
| 329 |
+
Behavior is the same as a regular file, except that the position is capped to the size limit.
|
| 330 |
+
"""
|
| 331 |
+
if __whence == SEEK_END:
|
| 332 |
+
# SEEK_END => set from the truncated end
|
| 333 |
+
__offset = len(self) + __offset
|
| 334 |
+
__whence = SEEK_SET
|
| 335 |
+
|
| 336 |
+
pos = self._file.seek(__offset, __whence)
|
| 337 |
+
if pos > self._size_limit:
|
| 338 |
+
return self._file.seek(self._size_limit)
|
| 339 |
+
return pos
|
| 340 |
+
|
| 341 |
+
def read(self, __size: int | None = -1) -> bytes:
|
| 342 |
+
"""Read at most `__size` bytes from the file.
|
| 343 |
+
|
| 344 |
+
Behavior is the same as a regular file, except that it is capped to the size limit.
|
| 345 |
+
"""
|
| 346 |
+
current = self._file.tell()
|
| 347 |
+
if __size is None or __size < 0:
|
| 348 |
+
# Read until file limit
|
| 349 |
+
truncated_size = self._size_limit - current
|
| 350 |
+
else:
|
| 351 |
+
# Read until file limit or __size
|
| 352 |
+
truncated_size = min(__size, self._size_limit - current)
|
| 353 |
+
return self._file.read(truncated_size)
|
.venv/lib/python3.12/site-packages/huggingface_hub/_dataset_viewer.py
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
import json
|
| 15 |
+
import os
|
| 16 |
+
import shutil
|
| 17 |
+
import subprocess
|
| 18 |
+
from dataclasses import dataclass
|
| 19 |
+
from typing import TYPE_CHECKING, Any, Union
|
| 20 |
+
|
| 21 |
+
from . import constants
|
| 22 |
+
from .utils import get_token
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
if TYPE_CHECKING:
|
| 26 |
+
import duckdb
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@dataclass(frozen=True)
|
| 30 |
+
class DatasetParquetEntry:
|
| 31 |
+
"""Represents a single parquet file available for a dataset on the Hub."""
|
| 32 |
+
|
| 33 |
+
config: str
|
| 34 |
+
split: str
|
| 35 |
+
url: str
|
| 36 |
+
size: int
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def execute_raw_sql_query(sql_query: str, *, token: str | bool | None = None) -> list[dict[str, Any]]:
|
| 40 |
+
normalized_query = sql_query.strip().rstrip(";").strip()
|
| 41 |
+
_raise_on_forbidden_query(normalized_query)
|
| 42 |
+
|
| 43 |
+
connection = None
|
| 44 |
+
try:
|
| 45 |
+
connection = _get_duckdb_connection(token=token)
|
| 46 |
+
relation = connection.sql(normalized_query)
|
| 47 |
+
if relation is None:
|
| 48 |
+
raise ValueError("SQL query must return rows.")
|
| 49 |
+
|
| 50 |
+
if isinstance(relation, _DuckDBCliRelation):
|
| 51 |
+
# DuckDB binary => run CLI => parse JSON
|
| 52 |
+
return relation.execute()
|
| 53 |
+
else:
|
| 54 |
+
# DuckDB Python API => fetch columns + rows => convert to dicts
|
| 55 |
+
columns = tuple(column[0] for column in relation.description)
|
| 56 |
+
rows = tuple(tuple(row) for row in relation.fetchall())
|
| 57 |
+
return [dict(zip(columns, row)) for row in rows]
|
| 58 |
+
finally:
|
| 59 |
+
if connection is not None:
|
| 60 |
+
connection.close()
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _raise_on_forbidden_query(query: str) -> None:
|
| 64 |
+
if len(query) == 0:
|
| 65 |
+
raise ValueError("SQL query cannot be empty.")
|
| 66 |
+
|
| 67 |
+
# DuckDB CLI meta-commands are dot-prefixed words (e.g. `.shell`, `.output`).
|
| 68 |
+
# Let's forbid them for now but allow SQL expressions like `.5` that can legitimately start a line.
|
| 69 |
+
for line in query.splitlines():
|
| 70 |
+
stripped = line.lstrip()
|
| 71 |
+
if stripped.startswith(".") and stripped[1:2].isalpha():
|
| 72 |
+
raise ValueError("DuckDB CLI meta-commands are not allowed in SQL queries.")
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _get_duckdb_connection(
|
| 76 |
+
token: str | bool | None,
|
| 77 |
+
) -> Union["duckdb.DuckDBPyConnection", "_DuckDBCliConnection"]:
|
| 78 |
+
try:
|
| 79 |
+
# If DuckDB is installed as a Python package, use it!
|
| 80 |
+
import duckdb
|
| 81 |
+
except ImportError as error:
|
| 82 |
+
# Otherwise, use the DuckDB CLI binary.
|
| 83 |
+
duckdb_binary = shutil.which("duckdb")
|
| 84 |
+
if duckdb_binary is None:
|
| 85 |
+
raise ImportError(
|
| 86 |
+
"DuckDB is required for `hf datasets sql`. Install the Python package with `pip install duckdb` or "
|
| 87 |
+
"install the DuckDB CLI binary (for example `brew install duckdb`)."
|
| 88 |
+
) from error
|
| 89 |
+
return _DuckDBCliConnection(binary_path=duckdb_binary, token=token)
|
| 90 |
+
|
| 91 |
+
# Create a new connection (Python API).
|
| 92 |
+
connection = duckdb.connect()
|
| 93 |
+
try:
|
| 94 |
+
for statement in _build_duckdb_secret_statements(token):
|
| 95 |
+
connection.execute(statement)
|
| 96 |
+
return connection
|
| 97 |
+
except Exception:
|
| 98 |
+
connection.close()
|
| 99 |
+
raise
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
@dataclass
|
| 103 |
+
class _DuckDBCliConnection:
|
| 104 |
+
"""DuckDB connection.
|
| 105 |
+
|
| 106 |
+
Mimics the DuckDB Python API, but runs the queries via the DuckDB CLI binary.
|
| 107 |
+
"""
|
| 108 |
+
|
| 109 |
+
binary_path: str
|
| 110 |
+
token: str | bool | None
|
| 111 |
+
|
| 112 |
+
def __post_init__(self) -> None:
|
| 113 |
+
self._setup_statements = _build_duckdb_secret_statements(self.token)
|
| 114 |
+
|
| 115 |
+
def sql(self, query: str) -> "_DuckDBCliRelation":
|
| 116 |
+
return _DuckDBCliRelation(binary_path=self.binary_path, setup_statements=self._setup_statements, query=query)
|
| 117 |
+
|
| 118 |
+
def close(self) -> None:
|
| 119 |
+
pass
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
@dataclass
|
| 123 |
+
class _DuckDBCliRelation:
|
| 124 |
+
"""DuckDB relation.
|
| 125 |
+
|
| 126 |
+
Mimics the DuckDB Python API, but runs the queries via the DuckDB CLI binary.
|
| 127 |
+
"""
|
| 128 |
+
|
| 129 |
+
binary_path: str
|
| 130 |
+
setup_statements: list[str]
|
| 131 |
+
query: str
|
| 132 |
+
|
| 133 |
+
def execute(self) -> list[dict[str, Any]]:
|
| 134 |
+
# Build the DuckDB CLI input.
|
| 135 |
+
setup = []
|
| 136 |
+
if self.setup_statements:
|
| 137 |
+
setup = [
|
| 138 |
+
f".output {os.devnull}",
|
| 139 |
+
*(f"{stmt};" for stmt in self.setup_statements),
|
| 140 |
+
".output",
|
| 141 |
+
]
|
| 142 |
+
full_query = "\n".join(setup + [self.query + ";"])
|
| 143 |
+
|
| 144 |
+
# Run DuckDB binary
|
| 145 |
+
result = subprocess.run(
|
| 146 |
+
[self.binary_path, "-json"],
|
| 147 |
+
input=full_query,
|
| 148 |
+
capture_output=True,
|
| 149 |
+
text=True,
|
| 150 |
+
encoding="utf-8",
|
| 151 |
+
check=False,
|
| 152 |
+
)
|
| 153 |
+
if result.returncode != 0:
|
| 154 |
+
error_message = result.stderr.strip() or result.stdout.strip() or "DuckDB CLI command failed."
|
| 155 |
+
raise RuntimeError(error_message)
|
| 156 |
+
|
| 157 |
+
# Parse JSON output and return
|
| 158 |
+
return json.loads(result.stdout.strip())
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def _build_duckdb_secret_statements(token: str | bool | None) -> list[str]:
|
| 162 |
+
if token is None or token is True:
|
| 163 |
+
token = get_token()
|
| 164 |
+
|
| 165 |
+
if not token:
|
| 166 |
+
return []
|
| 167 |
+
|
| 168 |
+
escaped_token = token.replace("'", "''")
|
| 169 |
+
escaped_endpoint = constants.ENDPOINT.replace("'", "''")
|
| 170 |
+
return [
|
| 171 |
+
f"CREATE OR REPLACE SECRET hf_hub_token (TYPE HTTP, BEARER_TOKEN '{escaped_token}', SCOPE '{escaped_endpoint}')",
|
| 172 |
+
f"CREATE OR REPLACE SECRET hf_token (TYPE HUGGINGFACE, TOKEN '{escaped_token}')",
|
| 173 |
+
]
|