Spaces:
Paused
Paused
Deploy Sensorflow Studio (part 2)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .venv-deploy/lib/python3.14/site-packages/httpcore-1.0.9.dist-info/INSTALLERAdded+1
- .venv-deploy/lib/python3.14/site-packages/httpcore-1.0.9.dist-info/METADATAAdded+625
- .venv-deploy/lib/python3.14/site-packages/httpcore-1.0.9.dist-info/RECORDAdded+68
- .venv-deploy/lib/python3.14/site-packages/httpcore-1.0.9.dist-info/WHEELAdded+4
- .venv-deploy/lib/python3.14/site-packages/httpcore-1.0.9.dist-info/licenses/LICENSE.mdAdded+27
- .venv-deploy/lib/python3.14/site-packages/httpcore/_sync/http_proxy.pyAdded+367
- .venv-deploy/lib/python3.14/site-packages/httpcore/_sync/interfaces.pyAdded+137
- .venv-deploy/lib/python3.14/site-packages/httpcore/_sync/socks_proxy.pyAdded+341
- .venv-deploy/lib/python3.14/site-packages/httpcore/_synchronization.pyAdded+318
- .venv-deploy/lib/python3.14/site-packages/httpcore/_trace.pyAdded+107
- .venv-deploy/lib/python3.14/site-packages/httpcore/_utils.pyAdded+37
- .venv-deploy/lib/python3.14/site-packages/httpcore/py.typedAdded
- .venv-deploy/lib/python3.14/site-packages/httpx-0.28.1.dist-info/INSTALLERAdded+1
- .venv-deploy/lib/python3.14/site-packages/httpx-0.28.1.dist-info/METADATAAdded+203
- .venv-deploy/lib/python3.14/site-packages/httpx-0.28.1.dist-info/RECORDAdded+54
- .venv-deploy/lib/python3.14/site-packages/httpx-0.28.1.dist-info/WHEELAdded+4
- .venv-deploy/lib/python3.14/site-packages/httpx-0.28.1.dist-info/entry_points.txtAdded+2
- .venv-deploy/lib/python3.14/site-packages/httpx-0.28.1.dist-info/licenses/LICENSE.mdAdded+12
- .venv-deploy/lib/python3.14/site-packages/httpx/__init__.pyAdded+105
- .venv-deploy/lib/python3.14/site-packages/httpx/__version__.pyAdded+3
- .venv-deploy/lib/python3.14/site-packages/httpx/_api.pyAdded+438
- .venv-deploy/lib/python3.14/site-packages/httpx/_auth.pyAdded+348
- .venv-deploy/lib/python3.14/site-packages/httpx/_client.pyAdded+2019
- .venv-deploy/lib/python3.14/site-packages/httpx/_config.pyAdded+248
- .venv-deploy/lib/python3.14/site-packages/httpx/_content.pyAdded+240
- .venv-deploy/lib/python3.14/site-packages/httpx/_decoders.pyAdded+393
- .venv-deploy/lib/python3.14/site-packages/httpx/_exceptions.pyAdded+379
- .venv-deploy/lib/python3.14/site-packages/httpx/_main.pyAdded+506
- .venv-deploy/lib/python3.14/site-packages/httpx/_models.pyAdded+1277
- .venv-deploy/lib/python3.14/site-packages/httpx/_multipart.pyAdded+300
- .venv-deploy/lib/python3.14/site-packages/httpx/_status_codes.pyAdded+162
- .venv-deploy/lib/python3.14/site-packages/httpx/_transports/__init__.pyAdded+15
- .venv-deploy/lib/python3.14/site-packages/httpx/_transports/asgi.pyAdded+187
- .venv-deploy/lib/python3.14/site-packages/httpx/_transports/base.pyAdded+86
- .venv-deploy/lib/python3.14/site-packages/httpx/_transports/default.pyAdded+406
- .venv-deploy/lib/python3.14/site-packages/httpx/_transports/mock.pyAdded+43
- .venv-deploy/lib/python3.14/site-packages/httpx/_transports/wsgi.pyAdded+149
- .venv-deploy/lib/python3.14/site-packages/httpx/_types.pyAdded+114
- .venv-deploy/lib/python3.14/site-packages/httpx/_urlparse.pyAdded+527
- .venv-deploy/lib/python3.14/site-packages/httpx/_urls.pyAdded+641
- .venv-deploy/lib/python3.14/site-packages/httpx/_utils.pyAdded+242
- .venv-deploy/lib/python3.14/site-packages/httpx/py.typedAdded
- .venv-deploy/lib/python3.14/site-packages/huggingface_hub-1.27.0.dist-info/INSTALLERAdded+1
- .venv-deploy/lib/python3.14/site-packages/huggingface_hub-1.27.0.dist-info/METADATAAdded+373
- .venv-deploy/lib/python3.14/site-packages/huggingface_hub-1.27.0.dist-info/RECORDAdded+380
- .venv-deploy/lib/python3.14/site-packages/huggingface_hub-1.27.0.dist-info/REQUESTEDAdded
- .venv-deploy/lib/python3.14/site-packages/huggingface_hub-1.27.0.dist-info/WHEELAdded+5
- .venv-deploy/lib/python3.14/site-packages/huggingface_hub-1.27.0.dist-info/entry_points.txtAdded+7
- .venv-deploy/lib/python3.14/site-packages/huggingface_hub-1.27.0.dist-info/licenses/LICENSEAdded+201
- .venv-deploy/lib/python3.14/site-packages/huggingface_hub-1.27.0.dist-info/top_level.txtAdded+1
1pip123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625Metadata-Version: 2.4Name: httpcoreVersion: 1.0.9Summary: A minimal low-level HTTP client.Project-URL: Documentation, https://www.encode.io/httpcoreProject-URL: Homepage, https://www.encode.io/httpcore/Project-URL: Source, https://github.com/encode/httpcoreAuthor-email: Tom Christie <tom@tomchristie.com>License-Expression: BSD-3-ClauseLicense-File: LICENSE.mdClassifier: Development Status :: 3 - AlphaClassifier: Environment :: Web EnvironmentClassifier: Framework :: AsyncIOClassifier: Framework :: TrioClassifier: Intended Audience :: DevelopersClassifier: License :: OSI Approved :: BSD LicenseClassifier: Operating System :: OS IndependentClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: 3 :: OnlyClassifier: Programming Language :: Python :: 3.8Classifier: Programming Language :: Python :: 3.9Classifier: Programming Language :: Python :: 3.10Classifier: Programming Language :: Python :: 3.11Classifier: Programming Language :: Python :: 3.12Classifier: Topic :: Internet :: WWW/HTTPRequires-Python: >=3.8Requires-Dist: certifiRequires-Dist: h11>=0.16Provides-Extra: asyncioRequires-Dist: anyio<5.0,>=4.0; extra == 'asyncio'Provides-Extra: http2Requires-Dist: h2<5,>=3; extra == 'http2'Provides-Extra: socksRequires-Dist: socksio==1.*; extra == 'socks'Provides-Extra: trioRequires-Dist: trio<1.0,>=0.22.0; extra == 'trio'Description-Content-Type: text/markdown
# HTTP Core
[](https://github.com/encode/httpcore/actions)[](https://pypi.org/project/httpcore/)
> *Do one thing, and do it well.*
The HTTP Core package provides a minimal low-level HTTP client, which doesone thing only. Sending HTTP requests.
It does not provide any high level model abstractions over the API,does not handle redirects, multipart uploads, building authentication headers,transparent HTTP caching, URL parsing, session cookie handling,content or charset decoding, handling JSON, environment based configurationdefaults, or any of that Jazz.
Some things HTTP Core does do:
* Sending HTTP requests.* Thread-safe / task-safe connection pooling.* HTTP(S) proxy & SOCKS proxy support.* Supports HTTP/1.1 and HTTP/2.* Provides both sync and async interfaces.* Async backend support for `asyncio` and `trio`.
## Requirements
Python 3.8+
## Installation
For HTTP/1.1 only support, install with:
```shell$ pip install httpcore```
There are also a number of optional extras available...
```shell$ pip install httpcore['asyncio,trio,http2,socks']```
## Sending requests
Send an HTTP request:
```pythonimport httpcore
response = httpcore.request("GET", "https://www.example.com/")
print(response)# <Response [200]>print(response.status)# 200print(response.headers)# [(b'Accept-Ranges', b'bytes'), (b'Age', b'557328'), (b'Cache-Control', b'max-age=604800'), ...]print(response.content)# b'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>\n\n<meta charset="utf-8"/>\n ...'```
The top-level `httpcore.request()` function is provided for convenience. In practice whenever you're working with `httpcore` you'll want to use the connection pooling functionality that it provides.
```pythonimport httpcore
http = httpcore.ConnectionPool()response = http.request("GET", "https://www.example.com/")```
Once you're ready to get going, [head over to the documentation](https://www.encode.io/httpcore/).
## Motivation
You *probably* don't want to be using HTTP Core directly. It might make sense ifyou're writing something like a proxy service in Python, and you just wantsomething at the lowest possible level, but more typically you'll want to usea higher level client library, such as `httpx`.
The motivation for `httpcore` is:
* To provide a reusable low-level client library, that other packages can then build on top of.* To provide a *really clear interface split* between the networking code and client logic, so that each is easier to understand and reason about in isolation.
## Dependencies
The `httpcore` package has the following dependencies...
* `h11`* `certifi`
And the following optional extras...
* `anyio` - Required by `pip install httpcore['asyncio']`.* `trio` - Required by `pip install httpcore['trio']`.* `h2` - Required by `pip install httpcore['http2']`.* `socksio` - Required by `pip install httpcore['socks']`.
## Versioning
We use [SEMVER for our versioning policy](https://semver.org/).
For changes between package versions please see our [project changelog](CHANGELOG.md).
We recommend pinning your requirements either the most current major version, or a more specific version range:
```pythonpip install 'httpcore==1.*'```# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## Version 1.0.9 (April 24th, 2025)
- Resolve https://github.com/advisories/GHSA-vqfr-h8mv-ghfj with h11 dependency update. (#1008)
## Version 1.0.8 (April 11th, 2025)
- Fix `AttributeError` when importing on Python 3.14. (#1005)
## Version 1.0.7 (November 15th, 2024)
- Support `proxy=…` configuration on `ConnectionPool()`. (#974)
## Version 1.0.6 (October 1st, 2024)
- Relax `trio` dependency pinning. (#956)- Handle `trio` raising `NotImplementedError` on unsupported platforms. (#955)- Handle mapping `ssl.SSLError` to `httpcore.ConnectError`. (#918)
## 1.0.5 (March 27th, 2024)
- Handle `EndOfStream` exception for anyio backend. (#899)- Allow trio `0.25.*` series in package dependancies. (#903)
## 1.0.4 (February 21st, 2024)
- Add `target` request extension. (#888)- Fix support for connection `Upgrade` and `CONNECT` when some data in the stream has been read. (#882)
## 1.0.3 (February 13th, 2024)
- Fix support for async cancellations. (#880)- Fix trace extension when used with socks proxy. (#849)- Fix SSL context for connections using the "wss" scheme (#869)
## 1.0.2 (November 10th, 2023)
- Fix `float("inf")` timeouts in `Event.wait` function. (#846)
## 1.0.1 (November 3rd, 2023)
- Fix pool timeout to account for the total time spent retrying. (#823)- Raise a neater RuntimeError when the correct async deps are not installed. (#826)- Add support for synchronous TLS-in-TLS streams. (#840)
## 1.0.0 (October 6th, 2023)
From version 1.0 our async support is now optional, as the package has minimal dependencies by default.
For async support use either `pip install 'httpcore[asyncio]'` or `pip install 'httpcore[trio]'`.
The project versioning policy is now explicitly governed by SEMVER. See https://semver.org/.
- Async support becomes fully optional. (#809)- Add support for Python 3.12. (#807)
## 0.18.0 (September 8th, 2023)
- Add support for HTTPS proxies. (#745, #786)- Drop Python 3.7 support. (#727)- Handle `sni_hostname` extension with SOCKS proxy. (#774)- Handle HTTP/1.1 half-closed connections gracefully. (#641)- Change the type of `Extensions` from `Mapping[Str, Any]` to `MutableMapping[Str, Any]`. (#762)
## 0.17.3 (July 5th, 2023)
- Support async cancellations, ensuring that the connection pool is left in a clean state when cancellations occur. (#726)- The networking backend interface has [been added to the public API](https://www.encode.io/httpcore/network-backends). Some classes which were previously private implementation detail are now part of the top-level public API. (#699)- Graceful handling of HTTP/2 GoAway frames, with requests being transparently retried on a new connection. (#730)- Add exceptions when a synchronous `trace callback` is passed to an asynchronous request or an asynchronous `trace callback` is passed to a synchronous request. (#717)- Drop Python 3.7 support. (#727)
## 0.17.2 (May 23th, 2023)
- Add `socket_options` argument to `ConnectionPool` and `HTTProxy` classes. (#668)- Improve logging with per-module logger names. (#690)- Add `sni_hostname` request extension. (#696)- Resolve race condition during import of `anyio` package. (#692)- Enable TCP_NODELAY for all synchronous sockets. (#651)
## 0.17.1 (May 17th, 2023)
- If 'retries' is set, then allow retries if an SSL handshake error occurs. (#669)- Improve correctness of tracebacks on network exceptions, by raising properly chained exceptions. (#678)- Prevent connection-hanging behaviour when HTTP/2 connections are closed by a server-sent 'GoAway' frame. (#679)- Fix edge-case exception when removing requests from the connection pool. (#680)- Fix pool timeout edge-case. (#688)
## 0.17.0 (March 16th, 2023)
- Add DEBUG level logging. (#648)- Respect HTTP/2 max concurrent streams when settings updates are sent by server. (#652)- Increase the allowable HTTP header size to 100kB. (#647)- Add `retries` option to SOCKS proxy classes. (#643)
## 0.16.3 (December 20th, 2022)
- Allow `ws` and `wss` schemes. Allows us to properly support websocket upgrade connections. (#625)- Forwarding HTTP proxies use a connection-per-remote-host. Required by some proxy implementations. (#637)- Don't raise `RuntimeError` when closing a connection pool with active connections. Removes some error cases when cancellations are used. (#631)- Lazy import `anyio`, so that it's no longer a hard dependancy, and isn't imported if unused. (#639)
## 0.16.2 (November 25th, 2022)
- Revert 'Fix async cancellation behaviour', which introduced race conditions. (#627)- Raise `RuntimeError` if attempting to us UNIX domain sockets on Windows. (#619)
## 0.16.1 (November 17th, 2022)
- Fix HTTP/1.1 interim informational responses, such as "100 Continue". (#605)
## 0.16.0 (October 11th, 2022)
- Support HTTP/1.1 informational responses. (#581)- Fix async cancellation behaviour. (#580)- Support `h11` 0.14. (#579)
## 0.15.0 (May 17th, 2022)
- Drop Python 3.6 support (#535)- Ensure HTTP proxy CONNECT requests include `timeout` configuration. (#506)- Switch to explicit `typing.Optional` for type hints. (#513)- For `trio` map OSError exceptions to `ConnectError`. (#543)
## 0.14.7 (February 4th, 2022)
- Requests which raise a PoolTimeout need to be removed from the pool queue. (#502)- Fix AttributeError that happened when Socks5Connection were terminated. (#501)
## 0.14.6 (February 1st, 2022)
- Fix SOCKS support for `http://` URLs. (#492)- Resolve race condition around exceptions during streaming a response. (#491)
## 0.14.5 (January 18th, 2022)
- SOCKS proxy support. (#478)- Add proxy_auth argument to HTTPProxy. (#481)- Improve error message on 'RemoteProtocolError' exception when server disconnects without sending a response. (#479)
## 0.14.4 (January 5th, 2022)
- Support HTTP/2 on HTTPS tunnelling proxies. (#468)- Fix proxy headers missing on HTTP forwarding. (#456)- Only instantiate SSL context if required. (#457)- More robust HTTP/2 handling. (#253, #439, #440, #441)
## 0.14.3 (November 17th, 2021)
- Fix race condition when removing closed connections from the pool. (#437)
## 0.14.2 (November 16th, 2021)
- Failed connections no longer remain in the pool. (Pull #433)
## 0.14.1 (November 12th, 2021)
- `max_connections` becomes optional. (Pull #429)- `certifi` is now included in the install dependancies. (Pull #428)- `h2` is now strictly optional. (Pull #428)
## 0.14.0 (November 11th, 2021)
The 0.14 release is a complete reworking of `httpcore`, comprehensively addressing some underlying issues in the connection pooling, as well as substantially redesigning the API to be more user friendly.
Some of the lower-level API design also makes the components more easily testable in isolation, and the package now has 100% test coverage.
See [discussion #419](https://github.com/encode/httpcore/discussions/419) for a little more background.
There's some other neat bits in there too, such as the "trace" extension, which gives a hook into inspecting the internal events that occur during the request/response cycle. This extension is needed for the HTTPX cli, in order to...
* Log the point at which the connection is established, and the IP/port on which it is made.* Determine if the outgoing request should log as HTTP/1.1 or HTTP/2, rather than having to assume it's HTTP/2 if the --http2 flag was passed. (Which may not actually be true.)* Log SSL version info / certificate info.
Note that `curio` support is not currently available in 0.14.0. If you're using `httpcore` with `curio` please get in touch, so we can assess if we ought to prioritize it as a feature or not.
## 0.13.7 (September 13th, 2021)
- Fix broken error messaging when URL scheme is missing, or a non HTTP(S) scheme is used. (Pull #403)
## 0.13.6 (June 15th, 2021)
### Fixed
- Close sockets when read or write timeouts occur. (Pull #365)
## 0.13.5 (June 14th, 2021)
### Fixed
- Resolved niggles with AnyIO EOF behaviours. (Pull #358, #362)
## 0.13.4 (June 9th, 2021)
### Added
- Improved error messaging when URL scheme is missing, or a non HTTP(S) scheme is used. (Pull #354)
### Fixed
- Switched to `anyio` as the default backend implementation when running with `asyncio`. Resolves some awkward [TLS timeout issues](https://github.com/encode/httpx/discussions/1511).
## 0.13.3 (May 6th, 2021)
### Added
- Support HTTP/2 prior knowledge, using `httpcore.SyncConnectionPool(http1=False)`. (Pull #333)
### Fixed
- Handle cases where environment does not provide `select.poll` support. (Pull #331)
## 0.13.2 (April 29th, 2021)
### Added
- Improve error message for specific case of `RemoteProtocolError` where server disconnects without sending a response. (Pull #313)
## 0.13.1 (April 28th, 2021)
### Fixed
- More resiliant testing for closed connections. (Pull #311)- Don't raise exceptions on ungraceful connection closes. (Pull #310)
## 0.13.0 (April 21st, 2021)
The 0.13 release updates the core API in order to match the HTTPX Transport API,introduced in HTTPX 0.18 onwards.
An example of making requests with the new interface is:
```pythonwith httpcore.SyncConnectionPool() as http: status_code, headers, stream, extensions = http.handle_request( method=b'GET', url=(b'https', b'example.org', 443, b'/'), headers=[(b'host', b'example.org'), (b'user-agent', b'httpcore')] stream=httpcore.ByteStream(b''), extensions={} ) body = stream.read() print(status_code, body)```
### Changed
- The `.request()` method is now `handle_request()`. (Pull #296)- The `.arequest()` method is now `.handle_async_request()`. (Pull #296)- The `headers` argument is no longer optional. (Pull #296)- The `stream` argument is no longer optional. (Pull #296)- The `ext` argument is now named `extensions`, and is no longer optional. (Pull #296)- The `"reason"` extension keyword is now named `"reason_phrase"`. (Pull #296)- The `"reason_phrase"` and `"http_version"` extensions now use byte strings for their values. (Pull #296)- The `httpcore.PlainByteStream()` class becomes `httpcore.ByteStream()`. (Pull #296)
### Added
- Streams now support a `.read()` interface. (Pull #296)
### Fixed
- Task cancellation no longer leaks connections from the connection pool. (Pull #305)
## 0.12.3 (December 7th, 2020)
### Fixed
- Abort SSL connections on close rather than waiting for remote EOF when using `asyncio`. (Pull #167)- Fix exception raised in case of connect timeouts when using the `anyio` backend. (Pull #236)- Fix `Host` header precedence for `:authority` in HTTP/2. (Pull #241, #243)- Handle extra edge case when detecting for socket readability when using `asyncio`. (Pull #242, #244)- Fix `asyncio` SSL warning when using proxy tunneling. (Pull #249)
## 0.12.2 (November 20th, 2020)
### Fixed
- Properly wrap connect errors on the asyncio backend. (Pull #235)- Fix `ImportError` occurring on Python 3.9 when using the HTTP/1.1 sync client in a multithreaded context. (Pull #237)
## 0.12.1 (November 7th, 2020)
### Added
- Add connect retries. (Pull #221)
### Fixed
- Tweak detection of dropped connections, resolving an issue with open files limits on Linux. (Pull #185)- Avoid leaking connections when establishing an HTTP tunnel to a proxy has failed. (Pull #223)- Properly wrap OS errors when using `trio`. (Pull #225)
## 0.12.0 (October 6th, 2020)
### Changed
- HTTP header casing is now preserved, rather than always sent in lowercase. (#216 and python-hyper/h11#104)
### Added
- Add Python 3.9 to officially supported versions.
### Fixed
- Gracefully handle a stdlib asyncio bug when a connection is closed while it is in a paused-for-reading state. (#201)
## 0.11.1 (September 28nd, 2020)
### Fixed
- Add await to async semaphore release() coroutine (#197)- Drop incorrect curio classifier (#192)
## 0.11.0 (September 22nd, 2020)
The Transport API with 0.11.0 has a couple of significant changes.
Firstly we've moved changed the request interface in order to allow extensions, which will later enable us to support featuressuch as trailing headers, HTTP/2 server push, and CONNECT/Upgrade connections.
The interface changes from:
```pythondef request(method, url, headers, stream, timeout): return (http_version, status_code, reason, headers, stream)```
To instead including an optional dictionary of extensions on the request and response:
```pythondef request(method, url, headers, stream, ext): return (status_code, headers, stream, ext)```
Having an open-ended extensions point will allow us to add later support for various optional features, that wouldn't otherwise be supported without these API changes.
In particular:
* Trailing headers support.* HTTP/2 Server Push* sendfile.* Exposing raw connection on CONNECT, Upgrade, HTTP/2 bi-di streaming.* Exposing debug information out of the API, including template name, template context.
Currently extensions are limited to:
* request: `timeout` - Optional. Timeout dictionary.* response: `http_version` - Optional. Include the HTTP version used on the response.* response: `reason` - Optional. Include the reason phrase used on the response. Only valid with HTTP/1.*.
See https://github.com/encode/httpx/issues/1274#issuecomment-694884553 for the history behind this.
Secondly, the async version of `request` is now namespaced as `arequest`.
This allows concrete transports to support both sync and async implementations on the same class.
### Added
- Add curio support. (Pull #168)- Add anyio support, with `backend="anyio"`. (Pull #169)
### Changed
- Update the Transport API to use 'ext' for optional extensions. (Pull #190)- Update the Transport API to use `.request` and `.arequest` so implementations can support both sync and async. (Pull #189)
## 0.10.2 (August 20th, 2020)
### Added
- Added Unix Domain Socket support. (Pull #139)
### Fixed
- Always include the port on proxy CONNECT requests. (Pull #154)- Fix `max_keepalive_connections` configuration. (Pull #153)- Fixes behaviour in HTTP/1.1 where server disconnects can be used to signal the end of the response body. (Pull #164)
## 0.10.1 (August 7th, 2020)
- Include `max_keepalive_connections` on `AsyncHTTPProxy`/`SyncHTTPProxy` classes.
## 0.10.0 (August 7th, 2020)
The most notable change in the 0.10.0 release is that HTTP/2 support is now fully optional.
Use either `pip install httpcore` for HTTP/1.1 support only, or `pip install httpcore[http2]` for HTTP/1.1 and HTTP/2 support.
### Added
- HTTP/2 support becomes optional. (Pull #121, #130)- Add `local_address=...` support. (Pull #100, #134)- Add `PlainByteStream`, `IteratorByteStream`, `AsyncIteratorByteStream`. The `AsyncByteSteam` and `SyncByteStream` classes are now pure interface classes. (#133)- Add `LocalProtocolError`, `RemoteProtocolError` exceptions. (Pull #129)- Add `UnsupportedProtocol` exception. (Pull #128)- Add `.get_connection_info()` method. (Pull #102, #137)- Add better TRACE logs. (Pull #101)
### Changed
- `max_keepalive` is deprecated in favour of `max_keepalive_connections`. (Pull #140)
### Fixed
- Improve handling of server disconnects. (Pull #112)
## 0.9.1 (May 27th, 2020)
### Fixed
- Proper host resolution for sync case, including IPv6 support. (Pull #97)- Close outstanding connections when connection pool is closed. (Pull #98)
## 0.9.0 (May 21th, 2020)
### Changed
- URL port becomes an `Optional[int]` instead of `int`. (Pull #92)
### Fixed
- Honor HTTP/2 max concurrent streams settings. (Pull #89, #90)- Remove incorrect debug log. (Pull #83)
## 0.8.4 (May 11th, 2020)
### Added
- Logging via HTTPCORE_LOG_LEVEL and HTTPX_LOG_LEVEL environment variablesand TRACE level logging. (Pull #79)
### Fixed
- Reuse of connections on HTTP/2 in close concurrency situations. (Pull #81)
## 0.8.3 (May 6rd, 2020)
### Fixed
- Include `Host` and `Accept` headers on proxy "CONNECT" requests.- De-duplicate any headers also contained in proxy_headers.- HTTP/2 flag not being passed down to proxy connections.
## 0.8.2 (May 3rd, 2020)
### Fixed
- Fix connections using proxy forwarding requests not being added to theconnection pool properly. (Pull #70)
## 0.8.1 (April 30th, 2020)
### Changed
- Allow inherintance of both `httpcore.AsyncByteStream`, `httpcore.SyncByteStream` without type conflicts.
## 0.8.0 (April 30th, 2020)
### Fixed
- Fixed tunnel proxy support.
### Added
- New `TimeoutException` base class.
## 0.7.0 (March 5th, 2020)
- First integration with HTTPX.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768httpcore-1.0.9.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
httpcore-1.0.9.dist-info/METADATA,sha256=_i1P2mGZEol4d54M8n88BFxTGGP83Zh-rMdPOhjUHCE,21529
httpcore-1.0.9.dist-info/RECORD,,
httpcore-1.0.9.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
httpcore-1.0.9.dist-info/licenses/LICENSE.md,sha256=_ctZFUx0y6uhahEkL3dAvqnyPW_rVUeRfYxflKgDkqU,1518
httpcore/__init__.py,sha256=9kT_kqChCCJUTHww24ZmR_ezcdbpRYWksD-gYNzkZP8,3445
httpcore/__pycache__/__init__.cpython-314.pyc,,
httpcore/__pycache__/_api.cpython-314.pyc,,
httpcore/__pycache__/_exceptions.cpython-314.pyc,,
httpcore/__pycache__/_models.cpython-314.pyc,,
httpcore/__pycache__/_ssl.cpython-314.pyc,,
httpcore/__pycache__/_synchronization.cpython-314.pyc,,
httpcore/__pycache__/_trace.cpython-314.pyc,,
httpcore/__pycache__/_utils.cpython-314.pyc,,
httpcore/_api.py,sha256=unZmeDschBWCGCPCwkS3Wot9euK6bg_kKxLtGTxw214,3146
httpcore/_async/__init__.py,sha256=EWdl2v4thnAHzJpqjU4h2a8DUiGAvNiWrkii9pfhTf0,1221
httpcore/_async/__pycache__/__init__.cpython-314.pyc,,
httpcore/_async/__pycache__/connection.cpython-314.pyc,,
httpcore/_async/__pycache__/connection_pool.cpython-314.pyc,,
httpcore/_async/__pycache__/http11.cpython-314.pyc,,
httpcore/_async/__pycache__/http2.cpython-314.pyc,,
httpcore/_async/__pycache__/http_proxy.cpython-314.pyc,,
httpcore/_async/__pycache__/interfaces.cpython-314.pyc,,
httpcore/_async/__pycache__/socks_proxy.cpython-314.pyc,,
httpcore/_async/connection.py,sha256=6OcPXqMEfc0BU38_-iHUNDd1vKSTc2UVT09XqNb_BOk,8449
httpcore/_async/connection_pool.py,sha256=DOIQ2s2ZCf9qfwxhzMprTPLqCL8OxGXiKF6qRHxvVyY,17307
httpcore/_async/http11.py,sha256=-qM9bV7PjSQF5vxs37-eUXOIFwbIjPcZbNliuX9TtBw,13880
httpcore/_async/http2.py,sha256=azX1fcmtXaIwjputFlZ4vd92J8xwjGOa9ax9QIv4394,23936
httpcore/_async/http_proxy.py,sha256=2zVkrlv-Ds-rWGaqaXlrhEJiAQFPo23BT3Gq_sWoBXU,14701
httpcore/_async/interfaces.py,sha256=jTiaWL83pgpGC9ziv90ZfwaKNMmHwmOalzaKiuTxATo,4455
httpcore/_async/socks_proxy.py,sha256=lLKgLlggPfhFlqi0ODeBkOWvt9CghBBUyqsnsU1tx6Q,13841
httpcore/_backends/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
httpcore/_backends/__pycache__/__init__.cpython-314.pyc,,
httpcore/_backends/__pycache__/anyio.cpython-314.pyc,,
httpcore/_backends/__pycache__/auto.cpython-314.pyc,,
httpcore/_backends/__pycache__/base.cpython-314.pyc,,
httpcore/_backends/__pycache__/mock.cpython-314.pyc,,
httpcore/_backends/__pycache__/sync.cpython-314.pyc,,
httpcore/_backends/__pycache__/trio.cpython-314.pyc,,
httpcore/_backends/anyio.py,sha256=x8PgEhXRC8bVqsdzk_YJx8Y6d9Tub06CuUSwnbmtqoY,5252
httpcore/_backends/auto.py,sha256=zO136PKZmsaTDK-HRk84eA-MUg8_2wJf4NvmK432Aio,1662
httpcore/_backends/base.py,sha256=aShgRdZnMmRhFWHetjumlM73f8Kz1YOAyCUP_4kHslA,3042
httpcore/_backends/mock.py,sha256=er9T436uSe7NLrfiLa4x6Nuqg5ivQ693CxWYCWsgbH4,4077
httpcore/_backends/sync.py,sha256=bhE4d9iK9Umxdsdsgm2EfKnXaBms2WggGYU-7jmUujU,7977
httpcore/_backends/trio.py,sha256=LHu4_Mr5MswQmmT3yE4oLgf9b_JJfeVS4BjDxeJc7Ro,5996
httpcore/_exceptions.py,sha256=looCKga3_YVYu3s-d3L9RMPRJyhsY7fiuuGxvkOD0c0,1184
httpcore/_models.py,sha256=IO2CcXcdpovRcLTdGFGB6RyBZdEm2h_TOmoCc4rEKho,17623
httpcore/_ssl.py,sha256=srqmSNU4iOUvWF-SrJvb8G_YEbHFELOXQOwdDIBTS9c,187
httpcore/_sync/__init__.py,sha256=JBDIgXt5la1LCJ1sLQeKhjKFpLnpNr8Svs6z2ni3fgg,1141
httpcore/_sync/__pycache__/__init__.cpython-314.pyc,,
httpcore/_sync/__pycache__/connection.cpython-314.pyc,,
httpcore/_sync/__pycache__/connection_pool.cpython-314.pyc,,
httpcore/_sync/__pycache__/http11.cpython-314.pyc,,
httpcore/_sync/__pycache__/http2.cpython-314.pyc,,
httpcore/_sync/__pycache__/http_proxy.cpython-314.pyc,,
httpcore/_sync/__pycache__/interfaces.cpython-314.pyc,,
httpcore/_sync/__pycache__/socks_proxy.cpython-314.pyc,,
httpcore/_sync/connection.py,sha256=9exGOb3PB-Mp2T1-sckSeL2t-tJ_9-NXomV8ihmWCgU,8238
httpcore/_sync/connection_pool.py,sha256=a-T8LTsUxc7r0Ww1atfHSDoWPjQ0fA8Ul7S3-F0Mj70,16955
httpcore/_sync/http11.py,sha256=IFobD1Md5JFlJGKWnh1_Q3epikUryI8qo09v8MiJIEA,13476
httpcore/_sync/http2.py,sha256=AxU4yhcq68Bn5vqdJYtiXKYUj7nvhYbxz3v4rT4xnvA,23400
httpcore/_sync/http_proxy.py,sha256=_al_6crKuEZu2wyvu493RZImJdBJnj5oGKNjLOJL2Zo,14463
httpcore/_sync/interfaces.py,sha256=snXON42vUDHO5JBJvo8D4VWk2Wat44z2OXXHDrjbl94,4344
httpcore/_sync/socks_proxy.py,sha256=zegZW9Snqj2_992DFJa8_CppOVBkVL4AgwduRkStakQ,13614
httpcore/_synchronization.py,sha256=zSi13mAColBnknjZBknUC6hKNDQT4C6ijnezZ-r0T2s,9434
httpcore/_trace.py,sha256=ck6ZoIzYTkdNAIfq5MGeKqBXDtqjOX-qfYwmZFbrGco,3952
httpcore/_utils.py,sha256=_RLgXYOAYC350ikALV59GZ68IJrdocRZxPs9PjmzdFY,1537
httpcore/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,01234Wheel-Version: 1.0Generator: hatchling 1.27.0Root-Is-Purelib: trueTag: py3-none-any123456789101112131415161718192021222324252627Copyright © 2020, [Encode OSS Ltd](https://www.encode.io/).All rights reserved.
Redistribution and use in source and binary forms, with or withoutmodification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* 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.
* 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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THEIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AREDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLEFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIALDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS ORSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVERCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USEOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367from __future__ import annotations
import base64import loggingimport sslimport typing
from .._backends.base import SOCKET_OPTION, NetworkBackendfrom .._exceptions import ProxyErrorfrom .._models import ( URL, Origin, Request, Response, enforce_bytes, enforce_headers, enforce_url,)from .._ssl import default_ssl_contextfrom .._synchronization import Lockfrom .._trace import Tracefrom .connection import HTTPConnectionfrom .connection_pool import ConnectionPoolfrom .http11 import HTTP11Connectionfrom .interfaces import ConnectionInterface
ByteOrStr = typing.Union[bytes, str]HeadersAsSequence = typing.Sequence[typing.Tuple[ByteOrStr, ByteOrStr]]HeadersAsMapping = typing.Mapping[ByteOrStr, ByteOrStr]
logger = logging.getLogger("httpcore.proxy")
def merge_headers( default_headers: typing.Sequence[tuple[bytes, bytes]] | None = None, override_headers: typing.Sequence[tuple[bytes, bytes]] | None = None,) -> list[tuple[bytes, bytes]]: """ Append default_headers and override_headers, de-duplicating if a key exists in both cases. """ default_headers = [] if default_headers is None else list(default_headers) override_headers = [] if override_headers is None else list(override_headers) has_override = set(key.lower() for key, value in override_headers) default_headers = [ (key, value) for key, value in default_headers if key.lower() not in has_override ] return default_headers + override_headers
class HTTPProxy(ConnectionPool): # pragma: nocover """ A connection pool that sends requests via an HTTP proxy. """
def __init__( self, proxy_url: URL | bytes | str, proxy_auth: tuple[bytes | str, bytes | str] | None = None, proxy_headers: HeadersAsMapping | HeadersAsSequence | None = None, ssl_context: ssl.SSLContext | None = None, proxy_ssl_context: ssl.SSLContext | None = None, max_connections: int | None = 10, max_keepalive_connections: int | None = None, keepalive_expiry: float | None = None, http1: bool = True, http2: bool = False, retries: int = 0, local_address: str | None = None, uds: str | None = None, network_backend: NetworkBackend | None = None, socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> None: """ A connection pool for making HTTP requests.
Parameters: proxy_url: The URL to use when connecting to the proxy server. For example `"http://127.0.0.1:8080/"`. proxy_auth: Any proxy authentication as a two-tuple of (username, password). May be either bytes or ascii-only str. proxy_headers: Any HTTP headers to use for the proxy requests. For example `{"Proxy-Authorization": "Basic <username>:<password>"}`. ssl_context: An SSL context to use for verifying connections. If not specified, the default `httpcore.default_ssl_context()` will be used. proxy_ssl_context: The same as `ssl_context`, but for a proxy server rather than a remote origin. max_connections: The maximum number of concurrent HTTP connections that the pool should allow. Any attempt to send a request on a pool that would exceed this amount will block until a connection is available. max_keepalive_connections: The maximum number of idle HTTP connections that will be maintained in the pool. keepalive_expiry: The duration in seconds that an idle HTTP connection may be maintained for before being expired from the pool. http1: A boolean indicating if HTTP/1.1 requests should be supported by the connection pool. Defaults to True. http2: A boolean indicating if HTTP/2 requests should be supported by the connection pool. Defaults to False. retries: The maximum number of retries when trying to establish a connection. local_address: Local address to connect from. Can also be used to connect using a particular address family. Using `local_address="0.0.0.0"` will connect using an `AF_INET` address (IPv4), while using `local_address="::"` will connect using an `AF_INET6` address (IPv6). uds: Path to a Unix Domain Socket to use instead of TCP sockets. network_backend: A backend instance to use for handling network I/O. """ super().__init__( ssl_context=ssl_context, max_connections=max_connections, max_keepalive_connections=max_keepalive_connections, keepalive_expiry=keepalive_expiry, http1=http1, http2=http2, network_backend=network_backend, retries=retries, local_address=local_address, uds=uds, socket_options=socket_options, )
self._proxy_url = enforce_url(proxy_url, name="proxy_url") if ( self._proxy_url.scheme == b"http" and proxy_ssl_context is not None ): # pragma: no cover raise RuntimeError( "The `proxy_ssl_context` argument is not allowed for the http scheme" )
self._ssl_context = ssl_context self._proxy_ssl_context = proxy_ssl_context self._proxy_headers = enforce_headers(proxy_headers, name="proxy_headers") if proxy_auth is not None: username = enforce_bytes(proxy_auth[0], name="proxy_auth") password = enforce_bytes(proxy_auth[1], name="proxy_auth") userpass = username + b":" + password authorization = b"Basic " + base64.b64encode(userpass) self._proxy_headers = [ (b"Proxy-Authorization", authorization) ] + self._proxy_headers
def create_connection(self, origin: Origin) -> ConnectionInterface: if origin.scheme == b"http": return ForwardHTTPConnection( proxy_origin=self._proxy_url.origin, proxy_headers=self._proxy_headers, remote_origin=origin, keepalive_expiry=self._keepalive_expiry, network_backend=self._network_backend, proxy_ssl_context=self._proxy_ssl_context, ) return TunnelHTTPConnection( proxy_origin=self._proxy_url.origin, proxy_headers=self._proxy_headers, remote_origin=origin, ssl_context=self._ssl_context, proxy_ssl_context=self._proxy_ssl_context, keepalive_expiry=self._keepalive_expiry, http1=self._http1, http2=self._http2, network_backend=self._network_backend, )
class ForwardHTTPConnection(ConnectionInterface): def __init__( self, proxy_origin: Origin, remote_origin: Origin, proxy_headers: HeadersAsMapping | HeadersAsSequence | None = None, keepalive_expiry: float | None = None, network_backend: NetworkBackend | None = None, socket_options: typing.Iterable[SOCKET_OPTION] | None = None, proxy_ssl_context: ssl.SSLContext | None = None, ) -> None: self._connection = HTTPConnection( origin=proxy_origin, keepalive_expiry=keepalive_expiry, network_backend=network_backend, socket_options=socket_options, ssl_context=proxy_ssl_context, ) self._proxy_origin = proxy_origin self._proxy_headers = enforce_headers(proxy_headers, name="proxy_headers") self._remote_origin = remote_origin
def handle_request(self, request: Request) -> Response: headers = merge_headers(self._proxy_headers, request.headers) url = URL( scheme=self._proxy_origin.scheme, host=self._proxy_origin.host, port=self._proxy_origin.port, target=bytes(request.url), ) proxy_request = Request( method=request.method, url=url, headers=headers, content=request.stream, extensions=request.extensions, ) return self._connection.handle_request(proxy_request)
def can_handle_request(self, origin: Origin) -> bool: return origin == self._remote_origin
def close(self) -> None: self._connection.close()
def info(self) -> str: return self._connection.info()
def is_available(self) -> bool: return self._connection.is_available()
def has_expired(self) -> bool: return self._connection.has_expired()
def is_idle(self) -> bool: return self._connection.is_idle()
def is_closed(self) -> bool: return self._connection.is_closed()
def __repr__(self) -> str: return f"<{self.__class__.__name__} [{self.info()}]>"
class TunnelHTTPConnection(ConnectionInterface): def __init__( self, proxy_origin: Origin, remote_origin: Origin, ssl_context: ssl.SSLContext | None = None, proxy_ssl_context: ssl.SSLContext | None = None, proxy_headers: typing.Sequence[tuple[bytes, bytes]] | None = None, keepalive_expiry: float | None = None, http1: bool = True, http2: bool = False, network_backend: NetworkBackend | None = None, socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> None: self._connection: ConnectionInterface = HTTPConnection( origin=proxy_origin, keepalive_expiry=keepalive_expiry, network_backend=network_backend, socket_options=socket_options, ssl_context=proxy_ssl_context, ) self._proxy_origin = proxy_origin self._remote_origin = remote_origin self._ssl_context = ssl_context self._proxy_ssl_context = proxy_ssl_context self._proxy_headers = enforce_headers(proxy_headers, name="proxy_headers") self._keepalive_expiry = keepalive_expiry self._http1 = http1 self._http2 = http2 self._connect_lock = Lock() self._connected = False
def handle_request(self, request: Request) -> Response: timeouts = request.extensions.get("timeout", {}) timeout = timeouts.get("connect", None)
with self._connect_lock: if not self._connected: target = b"%b:%d" % (self._remote_origin.host, self._remote_origin.port)
connect_url = URL( scheme=self._proxy_origin.scheme, host=self._proxy_origin.host, port=self._proxy_origin.port, target=target, ) connect_headers = merge_headers( [(b"Host", target), (b"Accept", b"*/*")], self._proxy_headers ) connect_request = Request( method=b"CONNECT", url=connect_url, headers=connect_headers, extensions=request.extensions, ) connect_response = self._connection.handle_request( connect_request )
if connect_response.status < 200 or connect_response.status > 299: reason_bytes = connect_response.extensions.get("reason_phrase", b"") reason_str = reason_bytes.decode("ascii", errors="ignore") msg = "%d %s" % (connect_response.status, reason_str) self._connection.close() raise ProxyError(msg)
stream = connect_response.extensions["network_stream"]
# Upgrade the stream to SSL ssl_context = ( default_ssl_context() if self._ssl_context is None else self._ssl_context ) alpn_protocols = ["http/1.1", "h2"] if self._http2 else ["http/1.1"] ssl_context.set_alpn_protocols(alpn_protocols)
kwargs = { "ssl_context": ssl_context, "server_hostname": self._remote_origin.host.decode("ascii"), "timeout": timeout, } with Trace("start_tls", logger, request, kwargs) as trace: stream = stream.start_tls(**kwargs) trace.return_value = stream
# Determine if we should be using HTTP/1.1 or HTTP/2 ssl_object = stream.get_extra_info("ssl_object") http2_negotiated = ( ssl_object is not None and ssl_object.selected_alpn_protocol() == "h2" )
# Create the HTTP/1.1 or HTTP/2 connection if http2_negotiated or (self._http2 and not self._http1): from .http2 import HTTP2Connection
self._connection = HTTP2Connection( origin=self._remote_origin, stream=stream, keepalive_expiry=self._keepalive_expiry, ) else: self._connection = HTTP11Connection( origin=self._remote_origin, stream=stream, keepalive_expiry=self._keepalive_expiry, )
self._connected = True return self._connection.handle_request(request)
def can_handle_request(self, origin: Origin) -> bool: return origin == self._remote_origin
def close(self) -> None: self._connection.close()
def info(self) -> str: return self._connection.info()
def is_available(self) -> bool: return self._connection.is_available()
def has_expired(self) -> bool: return self._connection.has_expired()
def is_idle(self) -> bool: return self._connection.is_idle()
def is_closed(self) -> bool: return self._connection.is_closed()
def __repr__(self) -> str: return f"<{self.__class__.__name__} [{self.info()}]>"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137from __future__ import annotations
import contextlibimport typing
from .._models import ( URL, Extensions, HeaderTypes, Origin, Request, Response, enforce_bytes, enforce_headers, enforce_url, include_request_headers,)
class RequestInterface: def request( self, method: bytes | str, url: URL | bytes | str, *, headers: HeaderTypes = None, content: bytes | typing.Iterator[bytes] | None = None, extensions: Extensions | None = None, ) -> Response: # Strict type checking on our parameters. method = enforce_bytes(method, name="method") url = enforce_url(url, name="url") headers = enforce_headers(headers, name="headers")
# Include Host header, and optionally Content-Length or Transfer-Encoding. headers = include_request_headers(headers, url=url, content=content)
request = Request( method=method, url=url, headers=headers, content=content, extensions=extensions, ) response = self.handle_request(request) try: response.read() finally: response.close() return response
@contextlib.contextmanager def stream( self, method: bytes | str, url: URL | bytes | str, *, headers: HeaderTypes = None, content: bytes | typing.Iterator[bytes] | None = None, extensions: Extensions | None = None, ) -> typing.Iterator[Response]: # Strict type checking on our parameters. method = enforce_bytes(method, name="method") url = enforce_url(url, name="url") headers = enforce_headers(headers, name="headers")
# Include Host header, and optionally Content-Length or Transfer-Encoding. headers = include_request_headers(headers, url=url, content=content)
request = Request( method=method, url=url, headers=headers, content=content, extensions=extensions, ) response = self.handle_request(request) try: yield response finally: response.close()
def handle_request(self, request: Request) -> Response: raise NotImplementedError() # pragma: nocover
class ConnectionInterface(RequestInterface): def close(self) -> None: raise NotImplementedError() # pragma: nocover
def info(self) -> str: raise NotImplementedError() # pragma: nocover
def can_handle_request(self, origin: Origin) -> bool: raise NotImplementedError() # pragma: nocover
def is_available(self) -> bool: """ Return `True` if the connection is currently able to accept an outgoing request.
An HTTP/1.1 connection will only be available if it is currently idle.
An HTTP/2 connection will be available so long as the stream ID space is not yet exhausted, and the connection is not in an error state.
While the connection is being established we may not yet know if it is going to result in an HTTP/1.1 or HTTP/2 connection. The connection should be treated as being available, but might ultimately raise `NewConnectionRequired` required exceptions if multiple requests are attempted over a connection that ends up being established as HTTP/1.1. """ raise NotImplementedError() # pragma: nocover
def has_expired(self) -> bool: """ Return `True` if the connection is in a state where it should be closed.
This either means that the connection is idle and it has passed the expiry time on its keep-alive, or that server has sent an EOF. """ raise NotImplementedError() # pragma: nocover
def is_idle(self) -> bool: """ Return `True` if the connection is currently idle. """ raise NotImplementedError() # pragma: nocover
def is_closed(self) -> bool: """ Return `True` if the connection has been closed.
Used when a response is closed to determine if the connection may be returned to the connection pool or not. """ raise NotImplementedError() # pragma: nocover123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341from __future__ import annotations
import loggingimport ssl
import socksio
from .._backends.sync import SyncBackendfrom .._backends.base import NetworkBackend, NetworkStreamfrom .._exceptions import ConnectionNotAvailable, ProxyErrorfrom .._models import URL, Origin, Request, Response, enforce_bytes, enforce_urlfrom .._ssl import default_ssl_contextfrom .._synchronization import Lockfrom .._trace import Tracefrom .connection_pool import ConnectionPoolfrom .http11 import HTTP11Connectionfrom .interfaces import ConnectionInterface
logger = logging.getLogger("httpcore.socks")
AUTH_METHODS = { b"\x00": "NO AUTHENTICATION REQUIRED", b"\x01": "GSSAPI", b"\x02": "USERNAME/PASSWORD", b"\xff": "NO ACCEPTABLE METHODS",}
REPLY_CODES = { b"\x00": "Succeeded", b"\x01": "General SOCKS server failure", b"\x02": "Connection not allowed by ruleset", b"\x03": "Network unreachable", b"\x04": "Host unreachable", b"\x05": "Connection refused", b"\x06": "TTL expired", b"\x07": "Command not supported", b"\x08": "Address type not supported",}
def _init_socks5_connection( stream: NetworkStream, *, host: bytes, port: int, auth: tuple[bytes, bytes] | None = None,) -> None: conn = socksio.socks5.SOCKS5Connection()
# Auth method request auth_method = ( socksio.socks5.SOCKS5AuthMethod.NO_AUTH_REQUIRED if auth is None else socksio.socks5.SOCKS5AuthMethod.USERNAME_PASSWORD ) conn.send(socksio.socks5.SOCKS5AuthMethodsRequest([auth_method])) outgoing_bytes = conn.data_to_send() stream.write(outgoing_bytes)
# Auth method response incoming_bytes = stream.read(max_bytes=4096) response = conn.receive_data(incoming_bytes) assert isinstance(response, socksio.socks5.SOCKS5AuthReply) if response.method != auth_method: requested = AUTH_METHODS.get(auth_method, "UNKNOWN") responded = AUTH_METHODS.get(response.method, "UNKNOWN") raise ProxyError( f"Requested {requested} from proxy server, but got {responded}." )
if response.method == socksio.socks5.SOCKS5AuthMethod.USERNAME_PASSWORD: # Username/password request assert auth is not None username, password = auth conn.send(socksio.socks5.SOCKS5UsernamePasswordRequest(username, password)) outgoing_bytes = conn.data_to_send() stream.write(outgoing_bytes)
# Username/password response incoming_bytes = stream.read(max_bytes=4096) response = conn.receive_data(incoming_bytes) assert isinstance(response, socksio.socks5.SOCKS5UsernamePasswordReply) if not response.success: raise ProxyError("Invalid username/password")
# Connect request conn.send( socksio.socks5.SOCKS5CommandRequest.from_address( socksio.socks5.SOCKS5Command.CONNECT, (host, port) ) ) outgoing_bytes = conn.data_to_send() stream.write(outgoing_bytes)
# Connect response incoming_bytes = stream.read(max_bytes=4096) response = conn.receive_data(incoming_bytes) assert isinstance(response, socksio.socks5.SOCKS5Reply) if response.reply_code != socksio.socks5.SOCKS5ReplyCode.SUCCEEDED: reply_code = REPLY_CODES.get(response.reply_code, "UNKOWN") raise ProxyError(f"Proxy Server could not connect: {reply_code}.")
class SOCKSProxy(ConnectionPool): # pragma: nocover """ A connection pool that sends requests via an HTTP proxy. """
def __init__( self, proxy_url: URL | bytes | str, proxy_auth: tuple[bytes | str, bytes | str] | None = None, ssl_context: ssl.SSLContext | None = None, max_connections: int | None = 10, max_keepalive_connections: int | None = None, keepalive_expiry: float | None = None, http1: bool = True, http2: bool = False, retries: int = 0, network_backend: NetworkBackend | None = None, ) -> None: """ A connection pool for making HTTP requests.
Parameters: proxy_url: The URL to use when connecting to the proxy server. For example `"http://127.0.0.1:8080/"`. ssl_context: An SSL context to use for verifying connections. If not specified, the default `httpcore.default_ssl_context()` will be used. max_connections: The maximum number of concurrent HTTP connections that the pool should allow. Any attempt to send a request on a pool that would exceed this amount will block until a connection is available. max_keepalive_connections: The maximum number of idle HTTP connections that will be maintained in the pool. keepalive_expiry: The duration in seconds that an idle HTTP connection may be maintained for before being expired from the pool. http1: A boolean indicating if HTTP/1.1 requests should be supported by the connection pool. Defaults to True. http2: A boolean indicating if HTTP/2 requests should be supported by the connection pool. Defaults to False. retries: The maximum number of retries when trying to establish a connection. local_address: Local address to connect from. Can also be used to connect using a particular address family. Using `local_address="0.0.0.0"` will connect using an `AF_INET` address (IPv4), while using `local_address="::"` will connect using an `AF_INET6` address (IPv6). uds: Path to a Unix Domain Socket to use instead of TCP sockets. network_backend: A backend instance to use for handling network I/O. """ super().__init__( ssl_context=ssl_context, max_connections=max_connections, max_keepalive_connections=max_keepalive_connections, keepalive_expiry=keepalive_expiry, http1=http1, http2=http2, network_backend=network_backend, retries=retries, ) self._ssl_context = ssl_context self._proxy_url = enforce_url(proxy_url, name="proxy_url") if proxy_auth is not None: username, password = proxy_auth username_bytes = enforce_bytes(username, name="proxy_auth") password_bytes = enforce_bytes(password, name="proxy_auth") self._proxy_auth: tuple[bytes, bytes] | None = ( username_bytes, password_bytes, ) else: self._proxy_auth = None
def create_connection(self, origin: Origin) -> ConnectionInterface: return Socks5Connection( proxy_origin=self._proxy_url.origin, remote_origin=origin, proxy_auth=self._proxy_auth, ssl_context=self._ssl_context, keepalive_expiry=self._keepalive_expiry, http1=self._http1, http2=self._http2, network_backend=self._network_backend, )
class Socks5Connection(ConnectionInterface): def __init__( self, proxy_origin: Origin, remote_origin: Origin, proxy_auth: tuple[bytes, bytes] | None = None, ssl_context: ssl.SSLContext | None = None, keepalive_expiry: float | None = None, http1: bool = True, http2: bool = False, network_backend: NetworkBackend | None = None, ) -> None: self._proxy_origin = proxy_origin self._remote_origin = remote_origin self._proxy_auth = proxy_auth self._ssl_context = ssl_context self._keepalive_expiry = keepalive_expiry self._http1 = http1 self._http2 = http2
self._network_backend: NetworkBackend = ( SyncBackend() if network_backend is None else network_backend ) self._connect_lock = Lock() self._connection: ConnectionInterface | None = None self._connect_failed = False
def handle_request(self, request: Request) -> Response: timeouts = request.extensions.get("timeout", {}) sni_hostname = request.extensions.get("sni_hostname", None) timeout = timeouts.get("connect", None)
with self._connect_lock: if self._connection is None: try: # Connect to the proxy kwargs = { "host": self._proxy_origin.host.decode("ascii"), "port": self._proxy_origin.port, "timeout": timeout, } with Trace("connect_tcp", logger, request, kwargs) as trace: stream = self._network_backend.connect_tcp(**kwargs) trace.return_value = stream
# Connect to the remote host using socks5 kwargs = { "stream": stream, "host": self._remote_origin.host.decode("ascii"), "port": self._remote_origin.port, "auth": self._proxy_auth, } with Trace( "setup_socks5_connection", logger, request, kwargs ) as trace: _init_socks5_connection(**kwargs) trace.return_value = stream
# Upgrade the stream to SSL if self._remote_origin.scheme == b"https": ssl_context = ( default_ssl_context() if self._ssl_context is None else self._ssl_context ) alpn_protocols = ( ["http/1.1", "h2"] if self._http2 else ["http/1.1"] ) ssl_context.set_alpn_protocols(alpn_protocols)
kwargs = { "ssl_context": ssl_context, "server_hostname": sni_hostname or self._remote_origin.host.decode("ascii"), "timeout": timeout, } with Trace("start_tls", logger, request, kwargs) as trace: stream = stream.start_tls(**kwargs) trace.return_value = stream
# Determine if we should be using HTTP/1.1 or HTTP/2 ssl_object = stream.get_extra_info("ssl_object") http2_negotiated = ( ssl_object is not None and ssl_object.selected_alpn_protocol() == "h2" )
# Create the HTTP/1.1 or HTTP/2 connection if http2_negotiated or ( self._http2 and not self._http1 ): # pragma: nocover from .http2 import HTTP2Connection
self._connection = HTTP2Connection( origin=self._remote_origin, stream=stream, keepalive_expiry=self._keepalive_expiry, ) else: self._connection = HTTP11Connection( origin=self._remote_origin, stream=stream, keepalive_expiry=self._keepalive_expiry, ) except Exception as exc: self._connect_failed = True raise exc elif not self._connection.is_available(): # pragma: nocover raise ConnectionNotAvailable()
return self._connection.handle_request(request)
def can_handle_request(self, origin: Origin) -> bool: return origin == self._remote_origin
def close(self) -> None: if self._connection is not None: self._connection.close()
def is_available(self) -> bool: if self._connection is None: # pragma: nocover # If HTTP/2 support is enabled, and the resulting connection could # end up as HTTP/2 then we should indicate the connection as being # available to service multiple requests. return ( self._http2 and (self._remote_origin.scheme == b"https" or not self._http1) and not self._connect_failed ) return self._connection.is_available()
def has_expired(self) -> bool: if self._connection is None: # pragma: nocover return self._connect_failed return self._connection.has_expired()
def is_idle(self) -> bool: if self._connection is None: # pragma: nocover return self._connect_failed return self._connection.is_idle()
def is_closed(self) -> bool: if self._connection is None: # pragma: nocover return self._connect_failed return self._connection.is_closed()
def info(self) -> str: if self._connection is None: # pragma: nocover return "CONNECTION FAILED" if self._connect_failed else "CONNECTING" return self._connection.info()
def __repr__(self) -> str: return f"<{self.__class__.__name__} [{self.info()}]>"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318from __future__ import annotations
import threadingimport types
from ._exceptions import ExceptionMapping, PoolTimeout, map_exceptions
# Our async synchronization primatives use either 'anyio' or 'trio' depending# on if they're running under asyncio or trio.
try: import trioexcept (ImportError, NotImplementedError): # pragma: nocover trio = None # type: ignore
try: import anyioexcept ImportError: # pragma: nocover anyio = None # type: ignore
def current_async_library() -> str: # Determine if we're running under trio or asyncio. # See https://sniffio.readthedocs.io/en/latest/ try: import sniffio except ImportError: # pragma: nocover environment = "asyncio" else: environment = sniffio.current_async_library()
if environment not in ("asyncio", "trio"): # pragma: nocover raise RuntimeError("Running under an unsupported async environment.")
if environment == "asyncio" and anyio is None: # pragma: nocover raise RuntimeError( "Running with asyncio requires installation of 'httpcore[asyncio]'." )
if environment == "trio" and trio is None: # pragma: nocover raise RuntimeError( "Running with trio requires installation of 'httpcore[trio]'." )
return environment
class AsyncLock: """ This is a standard lock.
In the sync case `Lock` provides thread locking. In the async case `AsyncLock` provides async locking. """
def __init__(self) -> None: self._backend = ""
def setup(self) -> None: """ Detect if we're running under 'asyncio' or 'trio' and create a lock with the correct implementation. """ self._backend = current_async_library() if self._backend == "trio": self._trio_lock = trio.Lock() elif self._backend == "asyncio": self._anyio_lock = anyio.Lock()
async def __aenter__(self) -> AsyncLock: if not self._backend: self.setup()
if self._backend == "trio": await self._trio_lock.acquire() elif self._backend == "asyncio": await self._anyio_lock.acquire()
return self
async def __aexit__( self, exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, traceback: types.TracebackType | None = None, ) -> None: if self._backend == "trio": self._trio_lock.release() elif self._backend == "asyncio": self._anyio_lock.release()
class AsyncThreadLock: """ This is a threading-only lock for no-I/O contexts.
In the sync case `ThreadLock` provides thread locking. In the async case `AsyncThreadLock` is a no-op. """
def __enter__(self) -> AsyncThreadLock: return self
def __exit__( self, exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, traceback: types.TracebackType | None = None, ) -> None: pass
class AsyncEvent: def __init__(self) -> None: self._backend = ""
def setup(self) -> None: """ Detect if we're running under 'asyncio' or 'trio' and create a lock with the correct implementation. """ self._backend = current_async_library() if self._backend == "trio": self._trio_event = trio.Event() elif self._backend == "asyncio": self._anyio_event = anyio.Event()
def set(self) -> None: if not self._backend: self.setup()
if self._backend == "trio": self._trio_event.set() elif self._backend == "asyncio": self._anyio_event.set()
async def wait(self, timeout: float | None = None) -> None: if not self._backend: self.setup()
if self._backend == "trio": trio_exc_map: ExceptionMapping = {trio.TooSlowError: PoolTimeout} timeout_or_inf = float("inf") if timeout is None else timeout with map_exceptions(trio_exc_map): with trio.fail_after(timeout_or_inf): await self._trio_event.wait() elif self._backend == "asyncio": anyio_exc_map: ExceptionMapping = {TimeoutError: PoolTimeout} with map_exceptions(anyio_exc_map): with anyio.fail_after(timeout): await self._anyio_event.wait()
class AsyncSemaphore: def __init__(self, bound: int) -> None: self._bound = bound self._backend = ""
def setup(self) -> None: """ Detect if we're running under 'asyncio' or 'trio' and create a semaphore with the correct implementation. """ self._backend = current_async_library() if self._backend == "trio": self._trio_semaphore = trio.Semaphore( initial_value=self._bound, max_value=self._bound ) elif self._backend == "asyncio": self._anyio_semaphore = anyio.Semaphore( initial_value=self._bound, max_value=self._bound )
async def acquire(self) -> None: if not self._backend: self.setup()
if self._backend == "trio": await self._trio_semaphore.acquire() elif self._backend == "asyncio": await self._anyio_semaphore.acquire()
async def release(self) -> None: if self._backend == "trio": self._trio_semaphore.release() elif self._backend == "asyncio": self._anyio_semaphore.release()
class AsyncShieldCancellation: # For certain portions of our codebase where we're dealing with # closing connections during exception handling we want to shield # the operation from being cancelled. # # with AsyncShieldCancellation(): # ... # clean-up operations, shielded from cancellation.
def __init__(self) -> None: """ Detect if we're running under 'asyncio' or 'trio' and create a shielded scope with the correct implementation. """ self._backend = current_async_library()
if self._backend == "trio": self._trio_shield = trio.CancelScope(shield=True) elif self._backend == "asyncio": self._anyio_shield = anyio.CancelScope(shield=True)
def __enter__(self) -> AsyncShieldCancellation: if self._backend == "trio": self._trio_shield.__enter__() elif self._backend == "asyncio": self._anyio_shield.__enter__() return self
def __exit__( self, exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, traceback: types.TracebackType | None = None, ) -> None: if self._backend == "trio": self._trio_shield.__exit__(exc_type, exc_value, traceback) elif self._backend == "asyncio": self._anyio_shield.__exit__(exc_type, exc_value, traceback)
# Our thread-based synchronization primitives...
class Lock: """ This is a standard lock.
In the sync case `Lock` provides thread locking. In the async case `AsyncLock` provides async locking. """
def __init__(self) -> None: self._lock = threading.Lock()
def __enter__(self) -> Lock: self._lock.acquire() return self
def __exit__( self, exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, traceback: types.TracebackType | None = None, ) -> None: self._lock.release()
class ThreadLock: """ This is a threading-only lock for no-I/O contexts.
In the sync case `ThreadLock` provides thread locking. In the async case `AsyncThreadLock` is a no-op. """
def __init__(self) -> None: self._lock = threading.Lock()
def __enter__(self) -> ThreadLock: self._lock.acquire() return self
def __exit__( self, exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, traceback: types.TracebackType | None = None, ) -> None: self._lock.release()
class Event: def __init__(self) -> None: self._event = threading.Event()
def set(self) -> None: self._event.set()
def wait(self, timeout: float | None = None) -> None: if timeout == float("inf"): # pragma: no cover timeout = None if not self._event.wait(timeout=timeout): raise PoolTimeout() # pragma: nocover
class Semaphore: def __init__(self, bound: int) -> None: self._semaphore = threading.Semaphore(value=bound)
def acquire(self) -> None: self._semaphore.acquire()
def release(self) -> None: self._semaphore.release()
class ShieldCancellation: # Thread-synchronous codebases don't support cancellation semantics. # We have this class because we need to mirror the async and sync # cases within our package, but it's just a no-op. def __enter__(self) -> ShieldCancellation: return self
def __exit__( self, exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, traceback: types.TracebackType | None = None, ) -> None: pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107from __future__ import annotations
import inspectimport loggingimport typesimport typing
from ._models import Request
class Trace: def __init__( self, name: str, logger: logging.Logger, request: Request | None = None, kwargs: dict[str, typing.Any] | None = None, ) -> None: self.name = name self.logger = logger self.trace_extension = ( None if request is None else request.extensions.get("trace") ) self.debug = self.logger.isEnabledFor(logging.DEBUG) self.kwargs = kwargs or {} self.return_value: typing.Any = None self.should_trace = self.debug or self.trace_extension is not None self.prefix = self.logger.name.split(".")[-1]
def trace(self, name: str, info: dict[str, typing.Any]) -> None: if self.trace_extension is not None: prefix_and_name = f"{self.prefix}.{name}" ret = self.trace_extension(prefix_and_name, info) if inspect.iscoroutine(ret): # pragma: no cover raise TypeError( "If you are using a synchronous interface, " "the callback of the `trace` extension should " "be a normal function instead of an asynchronous function." )
if self.debug: if not info or "return_value" in info and info["return_value"] is None: message = name else: args = " ".join([f"{key}={value!r}" for key, value in info.items()]) message = f"{name} {args}" self.logger.debug(message)
def __enter__(self) -> Trace: if self.should_trace: info = self.kwargs self.trace(f"{self.name}.started", info) return self
def __exit__( self, exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, traceback: types.TracebackType | None = None, ) -> None: if self.should_trace: if exc_value is None: info = {"return_value": self.return_value} self.trace(f"{self.name}.complete", info) else: info = {"exception": exc_value} self.trace(f"{self.name}.failed", info)
async def atrace(self, name: str, info: dict[str, typing.Any]) -> None: if self.trace_extension is not None: prefix_and_name = f"{self.prefix}.{name}" coro = self.trace_extension(prefix_and_name, info) if not inspect.iscoroutine(coro): # pragma: no cover raise TypeError( "If you're using an asynchronous interface, " "the callback of the `trace` extension should " "be an asynchronous function rather than a normal function." ) await coro
if self.debug: if not info or "return_value" in info and info["return_value"] is None: message = name else: args = " ".join([f"{key}={value!r}" for key, value in info.items()]) message = f"{name} {args}" self.logger.debug(message)
async def __aenter__(self) -> Trace: if self.should_trace: info = self.kwargs await self.atrace(f"{self.name}.started", info) return self
async def __aexit__( self, exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, traceback: types.TracebackType | None = None, ) -> None: if self.should_trace: if exc_value is None: info = {"return_value": self.return_value} await self.atrace(f"{self.name}.complete", info) else: info = {"exception": exc_value} await self.atrace(f"{self.name}.failed", info)12345678910111213141516171819202122232425262728293031323334353637from __future__ import annotations
import selectimport socketimport sys
def is_socket_readable(sock: socket.socket | None) -> bool: """ Return whether a socket, as identifed by its file descriptor, is readable. "A socket is readable" means that the read buffer isn't empty, i.e. that calling .recv() on it would immediately return some data. """ # NOTE: we want check for readability without actually attempting to read, because # we don't want to block forever if it's not readable.
# In the case that the socket no longer exists, or cannot return a file # descriptor, we treat it as being readable, as if it the next read operation # on it is ready to return the terminating `b""`. sock_fd = None if sock is None else sock.fileno() if sock_fd is None or sock_fd < 0: # pragma: nocover return True
# The implementation below was stolen from: # https://github.com/python-trio/trio/blob/20ee2b1b7376db637435d80e266212a35837ddcc/trio/_socket.py#L471-L478 # See also: https://github.com/encode/httpcore/pull/193#issuecomment-703129316
# Use select.select on Windows, and when poll is unavailable and select.poll # everywhere else. (E.g. When eventlet is in use. See #327) if ( sys.platform == "win32" or getattr(select, "poll", None) is None ): # pragma: nocover rready, _, _ = select.select([sock_fd], [], [], 0) return bool(rready) p = select.poll() p.register(sock_fd, select.POLLIN) return bool(p.poll(0))1pip123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203Metadata-Version: 2.3Name: httpxVersion: 0.28.1Summary: The next generation HTTP client.Project-URL: Changelog, https://github.com/encode/httpx/blob/master/CHANGELOG.mdProject-URL: Documentation, https://www.python-httpx.orgProject-URL: Homepage, https://github.com/encode/httpxProject-URL: Source, https://github.com/encode/httpxAuthor-email: Tom Christie <tom@tomchristie.com>License: BSD-3-ClauseClassifier: Development Status :: 4 - BetaClassifier: Environment :: Web EnvironmentClassifier: Framework :: AsyncIOClassifier: Framework :: TrioClassifier: Intended Audience :: DevelopersClassifier: License :: OSI Approved :: BSD LicenseClassifier: Operating System :: OS IndependentClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: 3 :: OnlyClassifier: Programming Language :: Python :: 3.8Classifier: Programming Language :: Python :: 3.9Classifier: Programming Language :: Python :: 3.10Classifier: Programming Language :: Python :: 3.11Classifier: Programming Language :: Python :: 3.12Classifier: Topic :: Internet :: WWW/HTTPRequires-Python: >=3.8Requires-Dist: anyioRequires-Dist: certifiRequires-Dist: httpcore==1.*Requires-Dist: idnaProvides-Extra: brotliRequires-Dist: brotli; (platform_python_implementation == 'CPython') and extra == 'brotli'Requires-Dist: brotlicffi; (platform_python_implementation != 'CPython') and extra == 'brotli'Provides-Extra: cliRequires-Dist: click==8.*; extra == 'cli'Requires-Dist: pygments==2.*; extra == 'cli'Requires-Dist: rich<14,>=10; extra == 'cli'Provides-Extra: http2Requires-Dist: h2<5,>=3; extra == 'http2'Provides-Extra: socksRequires-Dist: socksio==1.*; extra == 'socks'Provides-Extra: zstdRequires-Dist: zstandard>=0.18.0; extra == 'zstd'Description-Content-Type: text/markdown
<p align="center"> <a href="https://www.python-httpx.org/"><img width="350" height="208" src="https://raw.githubusercontent.com/encode/httpx/master/docs/img/butterfly.png" alt='HTTPX'></a></p>
<p align="center"><strong>HTTPX</strong> <em>- A next-generation HTTP client for Python.</em></p>
<p align="center"><a href="https://github.com/encode/httpx/actions"> <img src="https://github.com/encode/httpx/workflows/Test%20Suite/badge.svg" alt="Test Suite"></a><a href="https://pypi.org/project/httpx/"> <img src="https://badge.fury.io/py/httpx.svg" alt="Package version"></a></p>
HTTPX is a fully featured HTTP client library for Python 3. It includes **an integrated command line client**, has support for both **HTTP/1.1 and HTTP/2**, and provides both **sync and async APIs**.
---
Install HTTPX using pip:
```shell$ pip install httpx```
Now, let's get started:
```pycon>>> import httpx>>> r = httpx.get('https://www.example.org/')>>> r<Response [200 OK]>>>> r.status_code200>>> r.headers['content-type']'text/html; charset=UTF-8'>>> r.text'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'```
Or, using the command-line client.
```shell$ pip install 'httpx[cli]' # The command line client is an optional dependency.```
Which now allows us to use HTTPX directly from the command-line...
<p align="center"> <img width="700" src="https://raw.githubusercontent.com/encode/httpx/master/docs/img/httpx-help.png" alt='httpx --help'></p>
Sending a request...
<p align="center"> <img width="700" src="https://raw.githubusercontent.com/encode/httpx/master/docs/img/httpx-request.png" alt='httpx http://httpbin.org/json'></p>
## Features
HTTPX builds on the well-established usability of `requests`, and gives you:
* A broadly [requests-compatible API](https://www.python-httpx.org/compatibility/).* An integrated command-line client.* HTTP/1.1 [and HTTP/2 support](https://www.python-httpx.org/http2/).* Standard synchronous interface, but with [async support if you need it](https://www.python-httpx.org/async/).* Ability to make requests directly to [WSGI applications](https://www.python-httpx.org/advanced/transports/#wsgi-transport) or [ASGI applications](https://www.python-httpx.org/advanced/transports/#asgi-transport).* Strict timeouts everywhere.* Fully type annotated.* 100% test coverage.
Plus all the standard features of `requests`...
* International Domains and URLs* Keep-Alive & Connection Pooling* Sessions with Cookie Persistence* Browser-style SSL Verification* Basic/Digest Authentication* Elegant Key/Value Cookies* Automatic Decompression* Automatic Content Decoding* Unicode Response Bodies* Multipart File Uploads* HTTP(S) Proxy Support* Connection Timeouts* Streaming Downloads* .netrc Support* Chunked Requests
## Installation
Install with pip:
```shell$ pip install httpx```
Or, to include the optional HTTP/2 support, use:
```shell$ pip install httpx[http2]```
HTTPX requires Python 3.8+.
## Documentation
Project documentation is available at [https://www.python-httpx.org/](https://www.python-httpx.org/).
For a run-through of all the basics, head over to the [QuickStart](https://www.python-httpx.org/quickstart/).
For more advanced topics, see the [Advanced Usage](https://www.python-httpx.org/advanced/) section, the [async support](https://www.python-httpx.org/async/) section, or the [HTTP/2](https://www.python-httpx.org/http2/) section.
The [Developer Interface](https://www.python-httpx.org/api/) provides a comprehensive API reference.
To find out about tools that integrate with HTTPX, see [Third Party Packages](https://www.python-httpx.org/third_party_packages/).
## Contribute
If you want to contribute with HTTPX check out the [Contributing Guide](https://www.python-httpx.org/contributing/) to learn how to start.
## Dependencies
The HTTPX project relies on these excellent libraries:
* `httpcore` - The underlying transport implementation for `httpx`. * `h11` - HTTP/1.1 support.* `certifi` - SSL certificates.* `idna` - Internationalized domain name support.* `sniffio` - Async library autodetection.
As well as these optional installs:
* `h2` - HTTP/2 support. *(Optional, with `httpx[http2]`)** `socksio` - SOCKS proxy support. *(Optional, with `httpx[socks]`)** `rich` - Rich terminal support. *(Optional, with `httpx[cli]`)** `click` - Command line client support. *(Optional, with `httpx[cli]`)** `brotli` or `brotlicffi` - Decoding for "brotli" compressed responses. *(Optional, with `httpx[brotli]`)** `zstandard` - Decoding for "zstd" compressed responses. *(Optional, with `httpx[zstd]`)*
A huge amount of credit is due to `requests` for the API layout thatmuch of this work follows, as well as to `urllib3` for plenty of designinspiration around the lower-level networking details.
---
<p align="center"><i>HTTPX is <a href="https://github.com/encode/httpx/blob/master/LICENSE.md">BSD licensed</a> code.<br/>Designed & crafted with care.</i><br/>— 🦋 —</p>
## Release Information
### Fixed
* Reintroduced supposedly-private `URLTypes` shortcut. (#2673)
---
[Full changelog](https://github.com/encode/httpx/blob/master/CHANGELOG.md)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354../../../bin/httpx,sha256=hB9-eGh3DG9nI7MPg5wJMOi7v2VKesO-vyBRclyG8Yk,294
httpx-0.28.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
httpx-0.28.1.dist-info/METADATA,sha256=_rubD48-gNV8gZnDBPNcQzboWB0dGNeYPJJ2a4J5OyU,7052
httpx-0.28.1.dist-info/RECORD,,
httpx-0.28.1.dist-info/WHEEL,sha256=C2FUgwZgiLbznR-k0b_5k3Ai_1aASOXDss3lzCUsUug,87
httpx-0.28.1.dist-info/entry_points.txt,sha256=2lVkdQmxLA1pNMgSN2eV89o90HCZezhmNwsy6ryKDSA,37
httpx-0.28.1.dist-info/licenses/LICENSE.md,sha256=TsWdVE8StfU5o6cW_TIaxYzNgDC0ZSIfLIgCAM3yjY0,1508
httpx/__init__.py,sha256=CsaZe6yZj0rHg6322AWKWHGTMVr9txgEfD5P3_Rrz60,2171
httpx/__pycache__/__init__.cpython-314.pyc,,
httpx/__pycache__/__version__.cpython-314.pyc,,
httpx/__pycache__/_api.cpython-314.pyc,,
httpx/__pycache__/_auth.cpython-314.pyc,,
httpx/__pycache__/_client.cpython-314.pyc,,
httpx/__pycache__/_config.cpython-314.pyc,,
httpx/__pycache__/_content.cpython-314.pyc,,
httpx/__pycache__/_decoders.cpython-314.pyc,,
httpx/__pycache__/_exceptions.cpython-314.pyc,,
httpx/__pycache__/_main.cpython-314.pyc,,
httpx/__pycache__/_models.cpython-314.pyc,,
httpx/__pycache__/_multipart.cpython-314.pyc,,
httpx/__pycache__/_status_codes.cpython-314.pyc,,
httpx/__pycache__/_types.cpython-314.pyc,,
httpx/__pycache__/_urlparse.cpython-314.pyc,,
httpx/__pycache__/_urls.cpython-314.pyc,,
httpx/__pycache__/_utils.cpython-314.pyc,,
httpx/__version__.py,sha256=LoUyYeOXTieGzuP_64UL0wxdtxjuu_QbOvE7NOg-IqU,108
httpx/_api.py,sha256=r_Zgs4jIpcPJLqK5dbbSayqo_iVMKFaxZCd-oOHxLEs,11743
httpx/_auth.py,sha256=Yr3QwaUSK17rGYx-7j-FdicFIzz4Y9FFV-1F4-7RXX4,11891
httpx/_client.py,sha256=xD-UG67-WMkeltAAOeGGj-cZ2RRTAm19sWRxlFY7_40,65714
httpx/_config.py,sha256=pPp2U-wicfcKsF-KYRE1LYdt3e6ERGeIoXZ8Gjo3LWc,8547
httpx/_content.py,sha256=LGGzrJTR3OvN4Mb1GVVNLXkXJH-6oKlwAttO9p5w_yg,8161
httpx/_decoders.py,sha256=p0dX8I0NEHexs3UGp4SsZutiMhsXrrWl6-GnqVb0iKM,12041
httpx/_exceptions.py,sha256=bxW7fxzgVMAdNTbwT0Vnq04gJDW1_gI_GFiQPuMyjL0,8527
httpx/_main.py,sha256=Cg9GMabiTT_swaDfUgIRitSwxLRMSwUDOm7LdSGqlA4,15626
httpx/_models.py,sha256=4__Guyv1gLxuZChwim8kfQNiIOcJ9acreFOSurvZfms,44700
httpx/_multipart.py,sha256=KOHEZZl6oohg9mPaKyyu345qq1rJLg35TUG3YAzXB3Y,9843
httpx/_status_codes.py,sha256=DYn-2ufBgMeXy5s8x3_TB7wjAuAAMewTakPrm5rXEsc,5639
httpx/_transports/__init__.py,sha256=GbUoBSAOp7z-l-9j5YhMhR3DMIcn6FVLhj072O3Nnno,275
httpx/_transports/__pycache__/__init__.cpython-314.pyc,,
httpx/_transports/__pycache__/asgi.cpython-314.pyc,,
httpx/_transports/__pycache__/base.cpython-314.pyc,,
httpx/_transports/__pycache__/default.cpython-314.pyc,,
httpx/_transports/__pycache__/mock.cpython-314.pyc,,
httpx/_transports/__pycache__/wsgi.cpython-314.pyc,,
httpx/_transports/asgi.py,sha256=HRfiDYMPt4wQH2gFgHZg4c-i3sblo6bL5GTqcET-xz8,5501
httpx/_transports/base.py,sha256=kZS_VMbViYfF570pogUCJ1bulz-ybfL51Pqs9yktebU,2523
httpx/_transports/default.py,sha256=AzeaRUyVwCccTyyNJexDf0n1dFfzzydpdIQgvw7PLnk,13983
httpx/_transports/mock.py,sha256=PTo0d567RITXxGrki6kN7_67wwAxfwiMDcuXJiZCjEo,1232
httpx/_transports/wsgi.py,sha256=NcPX3Xap_EwCFZWO_OaSyQNuInCYx1QMNbO8GAei6jY,4825
httpx/_types.py,sha256=Jyh41GQq7AOev8IOWKDAg7zCbvHAfufmW5g_PiTtErY,2965
httpx/_urlparse.py,sha256=ZAmH47ONfkxrrj-PPYhGeiHjb6AjKCS-ANWIN4OL_KY,18546
httpx/_urls.py,sha256=dX99VR1DSOHpgo9Aq7PzYO4FKdxqKjwyNp8grf8dHN0,21550
httpx/_utils.py,sha256=_TVeqAKvxJkKHdz7dFeb4s0LZqQXgeFkXSgfiHBK_1o,8285
httpx/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,01234Wheel-Version: 1.0Generator: hatchling 1.26.3Root-Is-Purelib: trueTag: py3-none-any12[console_scripts]httpx = httpx:main123456789101112Copyright © 2019, [Encode OSS Ltd](https://www.encode.io/).All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* 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.
* 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.
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.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105from .__version__ import __description__, __title__, __version__from ._api import *from ._auth import *from ._client import *from ._config import *from ._content import *from ._exceptions import *from ._models import *from ._status_codes import *from ._transports import *from ._types import *from ._urls import *
try: from ._main import mainexcept ImportError: # pragma: no cover
def main() -> None: # type: ignore import sys
print( "The httpx command line client could not run because the required " "dependencies were not installed.\nMake sure you've installed " "everything with: pip install 'httpx[cli]'" ) sys.exit(1)
__all__ = [ "__description__", "__title__", "__version__", "ASGITransport", "AsyncBaseTransport", "AsyncByteStream", "AsyncClient", "AsyncHTTPTransport", "Auth", "BaseTransport", "BasicAuth", "ByteStream", "Client", "CloseError", "codes", "ConnectError", "ConnectTimeout", "CookieConflict", "Cookies", "create_ssl_context", "DecodingError", "delete", "DigestAuth", "get", "head", "Headers", "HTTPError", "HTTPStatusError", "HTTPTransport", "InvalidURL", "Limits", "LocalProtocolError", "main", "MockTransport", "NetRCAuth", "NetworkError", "options", "patch", "PoolTimeout", "post", "ProtocolError", "Proxy", "ProxyError", "put", "QueryParams", "ReadError", "ReadTimeout", "RemoteProtocolError", "request", "Request", "RequestError", "RequestNotRead", "Response", "ResponseNotRead", "stream", "StreamClosed", "StreamConsumed", "StreamError", "SyncByteStream", "Timeout", "TimeoutException", "TooManyRedirects", "TransportError", "UnsupportedProtocol", "URL", "USE_CLIENT_DEFAULT", "WriteError", "WriteTimeout", "WSGITransport",]
__locals = locals()for __name in __all__: if not __name.startswith("__"): setattr(__locals[__name], "__module__", "httpx") # noqa123__title__ = "httpx"__description__ = "A next generation HTTP client, for Python 3."__version__ = "0.28.1"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438from __future__ import annotations
import typingfrom contextlib import contextmanager
from ._client import Clientfrom ._config import DEFAULT_TIMEOUT_CONFIGfrom ._models import Responsefrom ._types import ( AuthTypes, CookieTypes, HeaderTypes, ProxyTypes, QueryParamTypes, RequestContent, RequestData, RequestFiles, TimeoutTypes,)from ._urls import URL
if typing.TYPE_CHECKING: import ssl # pragma: no cover
__all__ = [ "delete", "get", "head", "options", "patch", "post", "put", "request", "stream",]
def request( method: str, url: URL | str, *, params: QueryParamTypes | None = None, content: RequestContent | None = None, data: RequestData | None = None, files: RequestFiles | None = None, json: typing.Any | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | None = None, proxy: ProxyTypes | None = None, timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, follow_redirects: bool = False, verify: ssl.SSLContext | str | bool = True, trust_env: bool = True,) -> Response: """ Sends an HTTP request.
**Parameters:**
* **method** - HTTP method for the new `Request` object: `GET`, `OPTIONS`, `HEAD`, `POST`, `PUT`, `PATCH`, or `DELETE`. * **url** - URL for the new `Request` object. * **params** - *(optional)* Query parameters to include in the URL, as a string, dictionary, or sequence of two-tuples. * **content** - *(optional)* Binary content to include in the body of the request, as bytes or a byte iterator. * **data** - *(optional)* Form data to include in the body of the request, as a dictionary. * **files** - *(optional)* A dictionary of upload files to include in the body of the request. * **json** - *(optional)* A JSON serializable object to include in the body of the request. * **headers** - *(optional)* Dictionary of HTTP headers to include in the request. * **cookies** - *(optional)* Dictionary of Cookie items to include in the request. * **auth** - *(optional)* An authentication class to use when sending the request. * **proxy** - *(optional)* A proxy URL where all the traffic should be routed. * **timeout** - *(optional)* The timeout configuration to use when sending the request. * **follow_redirects** - *(optional)* Enables or disables HTTP redirects. * **verify** - *(optional)* Either `True` to use an SSL context with the default CA bundle, `False` to disable verification, or an instance of `ssl.SSLContext` to use a custom context. * **trust_env** - *(optional)* Enables or disables usage of environment variables for configuration.
**Returns:** `Response`
Usage:
``` >>> import httpx >>> response = httpx.request('GET', 'https://httpbin.org/get') >>> response <Response [200 OK]> ``` """ with Client( cookies=cookies, proxy=proxy, verify=verify, timeout=timeout, trust_env=trust_env, ) as client: return client.request( method=method, url=url, content=content, data=data, files=files, json=json, params=params, headers=headers, auth=auth, follow_redirects=follow_redirects, )
@contextmanagerdef stream( method: str, url: URL | str, *, params: QueryParamTypes | None = None, content: RequestContent | None = None, data: RequestData | None = None, files: RequestFiles | None = None, json: typing.Any | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | None = None, proxy: ProxyTypes | None = None, timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, follow_redirects: bool = False, verify: ssl.SSLContext | str | bool = True, trust_env: bool = True,) -> typing.Iterator[Response]: """ Alternative to `httpx.request()` that streams the response body instead of loading it into memory at once.
**Parameters**: See `httpx.request`.
See also: [Streaming Responses][0]
[0]: /quickstart#streaming-responses """ with Client( cookies=cookies, proxy=proxy, verify=verify, timeout=timeout, trust_env=trust_env, ) as client: with client.stream( method=method, url=url, content=content, data=data, files=files, json=json, params=params, headers=headers, auth=auth, follow_redirects=follow_redirects, ) as response: yield response
def get( url: URL | str, *, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | None = None, proxy: ProxyTypes | None = None, follow_redirects: bool = False, verify: ssl.SSLContext | str | bool = True, timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, trust_env: bool = True,) -> Response: """ Sends a `GET` request.
**Parameters**: See `httpx.request`.
Note that the `data`, `files`, `json` and `content` parameters are not available on this function, as `GET` requests should not include a request body. """ return request( "GET", url, params=params, headers=headers, cookies=cookies, auth=auth, proxy=proxy, follow_redirects=follow_redirects, verify=verify, timeout=timeout, trust_env=trust_env, )
def options( url: URL | str, *, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | None = None, proxy: ProxyTypes | None = None, follow_redirects: bool = False, verify: ssl.SSLContext | str | bool = True, timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, trust_env: bool = True,) -> Response: """ Sends an `OPTIONS` request.
**Parameters**: See `httpx.request`.
Note that the `data`, `files`, `json` and `content` parameters are not available on this function, as `OPTIONS` requests should not include a request body. """ return request( "OPTIONS", url, params=params, headers=headers, cookies=cookies, auth=auth, proxy=proxy, follow_redirects=follow_redirects, verify=verify, timeout=timeout, trust_env=trust_env, )
def head( url: URL | str, *, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | None = None, proxy: ProxyTypes | None = None, follow_redirects: bool = False, verify: ssl.SSLContext | str | bool = True, timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, trust_env: bool = True,) -> Response: """ Sends a `HEAD` request.
**Parameters**: See `httpx.request`.
Note that the `data`, `files`, `json` and `content` parameters are not available on this function, as `HEAD` requests should not include a request body. """ return request( "HEAD", url, params=params, headers=headers, cookies=cookies, auth=auth, proxy=proxy, follow_redirects=follow_redirects, verify=verify, timeout=timeout, trust_env=trust_env, )
def post( url: URL | str, *, content: RequestContent | None = None, data: RequestData | None = None, files: RequestFiles | None = None, json: typing.Any | None = None, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | None = None, proxy: ProxyTypes | None = None, follow_redirects: bool = False, verify: ssl.SSLContext | str | bool = True, timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, trust_env: bool = True,) -> Response: """ Sends a `POST` request.
**Parameters**: See `httpx.request`. """ return request( "POST", url, content=content, data=data, files=files, json=json, params=params, headers=headers, cookies=cookies, auth=auth, proxy=proxy, follow_redirects=follow_redirects, verify=verify, timeout=timeout, trust_env=trust_env, )
def put( url: URL | str, *, content: RequestContent | None = None, data: RequestData | None = None, files: RequestFiles | None = None, json: typing.Any | None = None, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | None = None, proxy: ProxyTypes | None = None, follow_redirects: bool = False, verify: ssl.SSLContext | str | bool = True, timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, trust_env: bool = True,) -> Response: """ Sends a `PUT` request.
**Parameters**: See `httpx.request`. """ return request( "PUT", url, content=content, data=data, files=files, json=json, params=params, headers=headers, cookies=cookies, auth=auth, proxy=proxy, follow_redirects=follow_redirects, verify=verify, timeout=timeout, trust_env=trust_env, )
def patch( url: URL | str, *, content: RequestContent | None = None, data: RequestData | None = None, files: RequestFiles | None = None, json: typing.Any | None = None, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | None = None, proxy: ProxyTypes | None = None, follow_redirects: bool = False, verify: ssl.SSLContext | str | bool = True, timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, trust_env: bool = True,) -> Response: """ Sends a `PATCH` request.
**Parameters**: See `httpx.request`. """ return request( "PATCH", url, content=content, data=data, files=files, json=json, params=params, headers=headers, cookies=cookies, auth=auth, proxy=proxy, follow_redirects=follow_redirects, verify=verify, timeout=timeout, trust_env=trust_env, )
def delete( url: URL | str, *, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | None = None, proxy: ProxyTypes | None = None, follow_redirects: bool = False, timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, verify: ssl.SSLContext | str | bool = True, trust_env: bool = True,) -> Response: """ Sends a `DELETE` request.
**Parameters**: See `httpx.request`.
Note that the `data`, `files`, `json` and `content` parameters are not available on this function, as `DELETE` requests should not include a request body. """ return request( "DELETE", url, params=params, headers=headers, cookies=cookies, auth=auth, proxy=proxy, follow_redirects=follow_redirects, verify=verify, timeout=timeout, trust_env=trust_env, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348from __future__ import annotations
import hashlibimport osimport reimport timeimport typingfrom base64 import b64encodefrom urllib.request import parse_http_list
from ._exceptions import ProtocolErrorfrom ._models import Cookies, Request, Responsefrom ._utils import to_bytes, to_str, unquote
if typing.TYPE_CHECKING: # pragma: no cover from hashlib import _Hash
__all__ = ["Auth", "BasicAuth", "DigestAuth", "NetRCAuth"]
class Auth: """ Base class for all authentication schemes.
To implement a custom authentication scheme, subclass `Auth` and override the `.auth_flow()` method.
If the authentication scheme does I/O such as disk access or network calls, or uses synchronization primitives such as locks, you should override `.sync_auth_flow()` and/or `.async_auth_flow()` instead of `.auth_flow()` to provide specialized implementations that will be used by `Client` and `AsyncClient` respectively. """
requires_request_body = False requires_response_body = False
def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]: """ Execute the authentication flow.
To dispatch a request, `yield` it:
``` yield request ```
The client will `.send()` the response back into the flow generator. You can access it like so:
``` response = yield request ```
A `return` (or reaching the end of the generator) will result in the client returning the last response obtained from the server.
You can dispatch as many requests as is necessary. """ yield request
def sync_auth_flow( self, request: Request ) -> typing.Generator[Request, Response, None]: """ Execute the authentication flow synchronously.
By default, this defers to `.auth_flow()`. You should override this method when the authentication scheme does I/O and/or uses concurrency primitives. """ if self.requires_request_body: request.read()
flow = self.auth_flow(request) request = next(flow)
while True: response = yield request if self.requires_response_body: response.read()
try: request = flow.send(response) except StopIteration: break
async def async_auth_flow( self, request: Request ) -> typing.AsyncGenerator[Request, Response]: """ Execute the authentication flow asynchronously.
By default, this defers to `.auth_flow()`. You should override this method when the authentication scheme does I/O and/or uses concurrency primitives. """ if self.requires_request_body: await request.aread()
flow = self.auth_flow(request) request = next(flow)
while True: response = yield request if self.requires_response_body: await response.aread()
try: request = flow.send(response) except StopIteration: break
class FunctionAuth(Auth): """ Allows the 'auth' argument to be passed as a simple callable function, that takes the request, and returns a new, modified request. """
def __init__(self, func: typing.Callable[[Request], Request]) -> None: self._func = func
def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]: yield self._func(request)
class BasicAuth(Auth): """ Allows the 'auth' argument to be passed as a (username, password) pair, and uses HTTP Basic authentication. """
def __init__(self, username: str | bytes, password: str | bytes) -> None: self._auth_header = self._build_auth_header(username, password)
def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]: request.headers["Authorization"] = self._auth_header yield request
def _build_auth_header(self, username: str | bytes, password: str | bytes) -> str: userpass = b":".join((to_bytes(username), to_bytes(password))) token = b64encode(userpass).decode() return f"Basic {token}"
class NetRCAuth(Auth): """ Use a 'netrc' file to lookup basic auth credentials based on the url host. """
def __init__(self, file: str | None = None) -> None: # Lazily import 'netrc'. # There's no need for us to load this module unless 'NetRCAuth' is being used. import netrc
self._netrc_info = netrc.netrc(file)
def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]: auth_info = self._netrc_info.authenticators(request.url.host) if auth_info is None or not auth_info[2]: # The netrc file did not have authentication credentials for this host. yield request else: # Build a basic auth header with credentials from the netrc file. request.headers["Authorization"] = self._build_auth_header( username=auth_info[0], password=auth_info[2] ) yield request
def _build_auth_header(self, username: str | bytes, password: str | bytes) -> str: userpass = b":".join((to_bytes(username), to_bytes(password))) token = b64encode(userpass).decode() return f"Basic {token}"
class DigestAuth(Auth): _ALGORITHM_TO_HASH_FUNCTION: dict[str, typing.Callable[[bytes], _Hash]] = { "MD5": hashlib.md5, "MD5-SESS": hashlib.md5, "SHA": hashlib.sha1, "SHA-SESS": hashlib.sha1, "SHA-256": hashlib.sha256, "SHA-256-SESS": hashlib.sha256, "SHA-512": hashlib.sha512, "SHA-512-SESS": hashlib.sha512, }
def __init__(self, username: str | bytes, password: str | bytes) -> None: self._username = to_bytes(username) self._password = to_bytes(password) self._last_challenge: _DigestAuthChallenge | None = None self._nonce_count = 1
def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]: if self._last_challenge: request.headers["Authorization"] = self._build_auth_header( request, self._last_challenge )
response = yield request
if response.status_code != 401 or "www-authenticate" not in response.headers: # If the response is not a 401 then we don't # need to build an authenticated request. return
for auth_header in response.headers.get_list("www-authenticate"): if auth_header.lower().startswith("digest "): break else: # If the response does not include a 'WWW-Authenticate: Digest ...' # header, then we don't need to build an authenticated request. return
self._last_challenge = self._parse_challenge(request, response, auth_header) self._nonce_count = 1
request.headers["Authorization"] = self._build_auth_header( request, self._last_challenge ) if response.cookies: Cookies(response.cookies).set_cookie_header(request=request) yield request
def _parse_challenge( self, request: Request, response: Response, auth_header: str ) -> _DigestAuthChallenge: """ Returns a challenge from a Digest WWW-Authenticate header. These take the form of: `Digest realm="realm@host.com",qop="auth,auth-int",nonce="abc",opaque="xyz"` """ scheme, _, fields = auth_header.partition(" ")
# This method should only ever have been called with a Digest auth header. assert scheme.lower() == "digest"
header_dict: dict[str, str] = {} for field in parse_http_list(fields): key, value = field.strip().split("=", 1) header_dict[key] = unquote(value)
try: realm = header_dict["realm"].encode() nonce = header_dict["nonce"].encode() algorithm = header_dict.get("algorithm", "MD5") opaque = header_dict["opaque"].encode() if "opaque" in header_dict else None qop = header_dict["qop"].encode() if "qop" in header_dict else None return _DigestAuthChallenge( realm=realm, nonce=nonce, algorithm=algorithm, opaque=opaque, qop=qop ) except KeyError as exc: message = "Malformed Digest WWW-Authenticate header" raise ProtocolError(message, request=request) from exc
def _build_auth_header( self, request: Request, challenge: _DigestAuthChallenge ) -> str: hash_func = self._ALGORITHM_TO_HASH_FUNCTION[challenge.algorithm.upper()]
def digest(data: bytes) -> bytes: return hash_func(data).hexdigest().encode()
A1 = b":".join((self._username, challenge.realm, self._password))
path = request.url.raw_path A2 = b":".join((request.method.encode(), path)) # TODO: implement auth-int HA2 = digest(A2)
nc_value = b"%08x" % self._nonce_count cnonce = self._get_client_nonce(self._nonce_count, challenge.nonce) self._nonce_count += 1
HA1 = digest(A1) if challenge.algorithm.lower().endswith("-sess"): HA1 = digest(b":".join((HA1, challenge.nonce, cnonce)))
qop = self._resolve_qop(challenge.qop, request=request) if qop is None: # Following RFC 2069 digest_data = [HA1, challenge.nonce, HA2] else: # Following RFC 2617/7616 digest_data = [HA1, challenge.nonce, nc_value, cnonce, qop, HA2]
format_args = { "username": self._username, "realm": challenge.realm, "nonce": challenge.nonce, "uri": path, "response": digest(b":".join(digest_data)), "algorithm": challenge.algorithm.encode(), } if challenge.opaque: format_args["opaque"] = challenge.opaque if qop: format_args["qop"] = b"auth" format_args["nc"] = nc_value format_args["cnonce"] = cnonce
return "Digest " + self._get_header_value(format_args)
def _get_client_nonce(self, nonce_count: int, nonce: bytes) -> bytes: s = str(nonce_count).encode() s += nonce s += time.ctime().encode() s += os.urandom(8)
return hashlib.sha1(s).hexdigest()[:16].encode()
def _get_header_value(self, header_fields: dict[str, bytes]) -> str: NON_QUOTED_FIELDS = ("algorithm", "qop", "nc") QUOTED_TEMPLATE = '{}="{}"' NON_QUOTED_TEMPLATE = "{}={}"
header_value = "" for i, (field, value) in enumerate(header_fields.items()): if i > 0: header_value += ", " template = ( QUOTED_TEMPLATE if field not in NON_QUOTED_FIELDS else NON_QUOTED_TEMPLATE ) header_value += template.format(field, to_str(value))
return header_value
def _resolve_qop(self, qop: bytes | None, request: Request) -> bytes | None: if qop is None: return None qops = re.split(b", ?", qop) if b"auth" in qops: return b"auth"
if qops == [b"auth-int"]: raise NotImplementedError("Digest auth-int support is not yet implemented")
message = f'Unexpected qop value "{qop!r}" in digest auth' raise ProtocolError(message, request=request)
class _DigestAuthChallenge(typing.NamedTuple): realm: bytes nonce: bytes algorithm: str opaque: bytes | None qop: bytes | None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019from __future__ import annotations
import datetimeimport enumimport loggingimport timeimport typingimport warningsfrom contextlib import asynccontextmanager, contextmanagerfrom types import TracebackType
from .__version__ import __version__from ._auth import Auth, BasicAuth, FunctionAuthfrom ._config import ( DEFAULT_LIMITS, DEFAULT_MAX_REDIRECTS, DEFAULT_TIMEOUT_CONFIG, Limits, Proxy, Timeout,)from ._decoders import SUPPORTED_DECODERSfrom ._exceptions import ( InvalidURL, RemoteProtocolError, TooManyRedirects, request_context,)from ._models import Cookies, Headers, Request, Responsefrom ._status_codes import codesfrom ._transports.base import AsyncBaseTransport, BaseTransportfrom ._transports.default import AsyncHTTPTransport, HTTPTransportfrom ._types import ( AsyncByteStream, AuthTypes, CertTypes, CookieTypes, HeaderTypes, ProxyTypes, QueryParamTypes, RequestContent, RequestData, RequestExtensions, RequestFiles, SyncByteStream, TimeoutTypes,)from ._urls import URL, QueryParamsfrom ._utils import URLPattern, get_environment_proxies
if typing.TYPE_CHECKING: import ssl # pragma: no cover
__all__ = ["USE_CLIENT_DEFAULT", "AsyncClient", "Client"]
# The type annotation for @classmethod and context managers here follows PEP 484# https://www.python.org/dev/peps/pep-0484/#annotating-instance-and-class-methodsT = typing.TypeVar("T", bound="Client")U = typing.TypeVar("U", bound="AsyncClient")
def _is_https_redirect(url: URL, location: URL) -> bool: """ Return 'True' if 'location' is a HTTPS upgrade of 'url' """ if url.host != location.host: return False
return ( url.scheme == "http" and _port_or_default(url) == 80 and location.scheme == "https" and _port_or_default(location) == 443 )
def _port_or_default(url: URL) -> int | None: if url.port is not None: return url.port return {"http": 80, "https": 443}.get(url.scheme)
def _same_origin(url: URL, other: URL) -> bool: """ Return 'True' if the given URLs share the same origin. """ return ( url.scheme == other.scheme and url.host == other.host and _port_or_default(url) == _port_or_default(other) )
class UseClientDefault: """ For some parameters such as `auth=...` and `timeout=...` we need to be able to indicate the default "unset" state, in a way that is distinctly different to using `None`.
The default "unset" state indicates that whatever default is set on the client should be used. This is different to setting `None`, which explicitly disables the parameter, possibly overriding a client default.
For example we use `timeout=USE_CLIENT_DEFAULT` in the `request()` signature. Omitting the `timeout` parameter will send a request using whatever default timeout has been configured on the client. Including `timeout=None` will ensure no timeout is used.
Note that user code shouldn't need to use the `USE_CLIENT_DEFAULT` constant, but it is used internally when a parameter is not included. """
USE_CLIENT_DEFAULT = UseClientDefault()
logger = logging.getLogger("httpx")
USER_AGENT = f"python-httpx/{__version__}"ACCEPT_ENCODING = ", ".join( [key for key in SUPPORTED_DECODERS.keys() if key != "identity"])
class ClientState(enum.Enum): # UNOPENED: # The client has been instantiated, but has not been used to send a request, # or been opened by entering the context of a `with` block. UNOPENED = 1 # OPENED: # The client has either sent a request, or is within a `with` block. OPENED = 2 # CLOSED: # The client has either exited the `with` block, or `close()` has # been called explicitly. CLOSED = 3
class BoundSyncStream(SyncByteStream): """ A byte stream that is bound to a given response instance, and that ensures the `response.elapsed` is set once the response is closed. """
def __init__( self, stream: SyncByteStream, response: Response, start: float ) -> None: self._stream = stream self._response = response self._start = start
def __iter__(self) -> typing.Iterator[bytes]: for chunk in self._stream: yield chunk
def close(self) -> None: elapsed = time.perf_counter() - self._start self._response.elapsed = datetime.timedelta(seconds=elapsed) self._stream.close()
class BoundAsyncStream(AsyncByteStream): """ An async byte stream that is bound to a given response instance, and that ensures the `response.elapsed` is set once the response is closed. """
def __init__( self, stream: AsyncByteStream, response: Response, start: float ) -> None: self._stream = stream self._response = response self._start = start
async def __aiter__(self) -> typing.AsyncIterator[bytes]: async for chunk in self._stream: yield chunk
async def aclose(self) -> None: elapsed = time.perf_counter() - self._start self._response.elapsed = datetime.timedelta(seconds=elapsed) await self._stream.aclose()
EventHook = typing.Callable[..., typing.Any]
class BaseClient: def __init__( self, *, auth: AuthTypes | None = None, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, follow_redirects: bool = False, max_redirects: int = DEFAULT_MAX_REDIRECTS, event_hooks: None | (typing.Mapping[str, list[EventHook]]) = None, base_url: URL | str = "", trust_env: bool = True, default_encoding: str | typing.Callable[[bytes], str] = "utf-8", ) -> None: event_hooks = {} if event_hooks is None else event_hooks
self._base_url = self._enforce_trailing_slash(URL(base_url))
self._auth = self._build_auth(auth) self._params = QueryParams(params) self.headers = Headers(headers) self._cookies = Cookies(cookies) self._timeout = Timeout(timeout) self.follow_redirects = follow_redirects self.max_redirects = max_redirects self._event_hooks = { "request": list(event_hooks.get("request", [])), "response": list(event_hooks.get("response", [])), } self._trust_env = trust_env self._default_encoding = default_encoding self._state = ClientState.UNOPENED
@property def is_closed(self) -> bool: """ Check if the client being closed """ return self._state == ClientState.CLOSED
@property def trust_env(self) -> bool: return self._trust_env
def _enforce_trailing_slash(self, url: URL) -> URL: if url.raw_path.endswith(b"/"): return url return url.copy_with(raw_path=url.raw_path + b"/")
def _get_proxy_map( self, proxy: ProxyTypes | None, allow_env_proxies: bool ) -> dict[str, Proxy | None]: if proxy is None: if allow_env_proxies: return { key: None if url is None else Proxy(url=url) for key, url in get_environment_proxies().items() } return {} else: proxy = Proxy(url=proxy) if isinstance(proxy, (str, URL)) else proxy return {"all://": proxy}
@property def timeout(self) -> Timeout: return self._timeout
@timeout.setter def timeout(self, timeout: TimeoutTypes) -> None: self._timeout = Timeout(timeout)
@property def event_hooks(self) -> dict[str, list[EventHook]]: return self._event_hooks
@event_hooks.setter def event_hooks(self, event_hooks: dict[str, list[EventHook]]) -> None: self._event_hooks = { "request": list(event_hooks.get("request", [])), "response": list(event_hooks.get("response", [])), }
@property def auth(self) -> Auth | None: """ Authentication class used when none is passed at the request-level.
See also [Authentication][0].
[0]: /quickstart/#authentication """ return self._auth
@auth.setter def auth(self, auth: AuthTypes) -> None: self._auth = self._build_auth(auth)
@property def base_url(self) -> URL: """ Base URL to use when sending requests with relative URLs. """ return self._base_url
@base_url.setter def base_url(self, url: URL | str) -> None: self._base_url = self._enforce_trailing_slash(URL(url))
@property def headers(self) -> Headers: """ HTTP headers to include when sending requests. """ return self._headers
@headers.setter def headers(self, headers: HeaderTypes) -> None: client_headers = Headers( { b"Accept": b"*/*", b"Accept-Encoding": ACCEPT_ENCODING.encode("ascii"), b"Connection": b"keep-alive", b"User-Agent": USER_AGENT.encode("ascii"), } ) client_headers.update(headers) self._headers = client_headers
@property def cookies(self) -> Cookies: """ Cookie values to include when sending requests. """ return self._cookies
@cookies.setter def cookies(self, cookies: CookieTypes) -> None: self._cookies = Cookies(cookies)
@property def params(self) -> QueryParams: """ Query parameters to include in the URL when sending requests. """ return self._params
@params.setter def params(self, params: QueryParamTypes) -> None: self._params = QueryParams(params)
def build_request( self, method: str, url: URL | str, *, content: RequestContent | None = None, data: RequestData | None = None, files: RequestFiles | None = None, json: typing.Any | None = None, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, extensions: RequestExtensions | None = None, ) -> Request: """ Build and return a request instance.
* The `params`, `headers` and `cookies` arguments are merged with any values set on the client. * The `url` argument is merged with any `base_url` set on the client.
See also: [Request instances][0]
[0]: /advanced/clients/#request-instances """ url = self._merge_url(url) headers = self._merge_headers(headers) cookies = self._merge_cookies(cookies) params = self._merge_queryparams(params) extensions = {} if extensions is None else extensions if "timeout" not in extensions: timeout = ( self.timeout if isinstance(timeout, UseClientDefault) else Timeout(timeout) ) extensions = dict(**extensions, timeout=timeout.as_dict()) return Request( method, url, content=content, data=data, files=files, json=json, params=params, headers=headers, cookies=cookies, extensions=extensions, )
def _merge_url(self, url: URL | str) -> URL: """ Merge a URL argument together with any 'base_url' on the client, to create the URL used for the outgoing request. """ merge_url = URL(url) if merge_url.is_relative_url: # To merge URLs we always append to the base URL. To get this # behaviour correct we always ensure the base URL ends in a '/' # separator, and strip any leading '/' from the merge URL. # # So, eg... # # >>> client = Client(base_url="https://www.example.com/subpath") # >>> client.base_url # URL('https://www.example.com/subpath/') # >>> client.build_request("GET", "/path").url # URL('https://www.example.com/subpath/path') merge_raw_path = self.base_url.raw_path + merge_url.raw_path.lstrip(b"/") return self.base_url.copy_with(raw_path=merge_raw_path) return merge_url
def _merge_cookies(self, cookies: CookieTypes | None = None) -> CookieTypes | None: """ Merge a cookies argument together with any cookies on the client, to create the cookies used for the outgoing request. """ if cookies or self.cookies: merged_cookies = Cookies(self.cookies) merged_cookies.update(cookies) return merged_cookies return cookies
def _merge_headers(self, headers: HeaderTypes | None = None) -> HeaderTypes | None: """ Merge a headers argument together with any headers on the client, to create the headers used for the outgoing request. """ merged_headers = Headers(self.headers) merged_headers.update(headers) return merged_headers
def _merge_queryparams( self, params: QueryParamTypes | None = None ) -> QueryParamTypes | None: """ Merge a queryparams argument together with any queryparams on the client, to create the queryparams used for the outgoing request. """ if params or self.params: merged_queryparams = QueryParams(self.params) return merged_queryparams.merge(params) return params
def _build_auth(self, auth: AuthTypes | None) -> Auth | None: if auth is None: return None elif isinstance(auth, tuple): return BasicAuth(username=auth[0], password=auth[1]) elif isinstance(auth, Auth): return auth elif callable(auth): return FunctionAuth(func=auth) else: raise TypeError(f'Invalid "auth" argument: {auth!r}')
def _build_request_auth( self, request: Request, auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, ) -> Auth: auth = ( self._auth if isinstance(auth, UseClientDefault) else self._build_auth(auth) )
if auth is not None: return auth
username, password = request.url.username, request.url.password if username or password: return BasicAuth(username=username, password=password)
return Auth()
def _build_redirect_request(self, request: Request, response: Response) -> Request: """ Given a request and a redirect response, return a new request that should be used to effect the redirect. """ method = self._redirect_method(request, response) url = self._redirect_url(request, response) headers = self._redirect_headers(request, url, method) stream = self._redirect_stream(request, method) cookies = Cookies(self.cookies) return Request( method=method, url=url, headers=headers, cookies=cookies, stream=stream, extensions=request.extensions, )
def _redirect_method(self, request: Request, response: Response) -> str: """ When being redirected we may want to change the method of the request based on certain specs or browser behavior. """ method = request.method
# https://tools.ietf.org/html/rfc7231#section-6.4.4 if response.status_code == codes.SEE_OTHER and method != "HEAD": method = "GET"
# Do what the browsers do, despite standards... # Turn 302s into GETs. if response.status_code == codes.FOUND and method != "HEAD": method = "GET"
# If a POST is responded to with a 301, turn it into a GET. # This bizarre behaviour is explained in 'requests' issue 1704. if response.status_code == codes.MOVED_PERMANENTLY and method == "POST": method = "GET"
return method
def _redirect_url(self, request: Request, response: Response) -> URL: """ Return the URL for the redirect to follow. """ location = response.headers["Location"]
try: url = URL(location) except InvalidURL as exc: raise RemoteProtocolError( f"Invalid URL in location header: {exc}.", request=request ) from None
# Handle malformed 'Location' headers that are "absolute" form, have no host. # See: https://github.com/encode/httpx/issues/771 if url.scheme and not url.host: url = url.copy_with(host=request.url.host)
# Facilitate relative 'Location' headers, as allowed by RFC 7231. # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource') if url.is_relative_url: url = request.url.join(url)
# Attach previous fragment if needed (RFC 7231 7.1.2) if request.url.fragment and not url.fragment: url = url.copy_with(fragment=request.url.fragment)
return url
def _redirect_headers(self, request: Request, url: URL, method: str) -> Headers: """ Return the headers that should be used for the redirect request. """ headers = Headers(request.headers)
if not _same_origin(url, request.url): if not _is_https_redirect(request.url, url): # Strip Authorization headers when responses are redirected # away from the origin. (Except for direct HTTP to HTTPS redirects.) headers.pop("Authorization", None)
# Update the Host header. headers["Host"] = url.netloc.decode("ascii")
if method != request.method and method == "GET": # If we've switch to a 'GET' request, then strip any headers which # are only relevant to the request body. headers.pop("Content-Length", None) headers.pop("Transfer-Encoding", None)
# We should use the client cookie store to determine any cookie header, # rather than whatever was on the original outgoing request. headers.pop("Cookie", None)
return headers
def _redirect_stream( self, request: Request, method: str ) -> SyncByteStream | AsyncByteStream | None: """ Return the body that should be used for the redirect request. """ if method != request.method and method == "GET": return None
return request.stream
def _set_timeout(self, request: Request) -> None: if "timeout" not in request.extensions: timeout = ( self.timeout if isinstance(self.timeout, UseClientDefault) else Timeout(self.timeout) ) request.extensions = dict(**request.extensions, timeout=timeout.as_dict())
class Client(BaseClient): """ An HTTP client, with connection pooling, HTTP/2, redirects, cookie persistence, etc.
It can be shared between threads.
Usage:
```python >>> client = httpx.Client() >>> response = client.get('https://example.org') ```
**Parameters:**
* **auth** - *(optional)* An authentication class to use when sending requests. * **params** - *(optional)* Query parameters to include in request URLs, as a string, dictionary, or sequence of two-tuples. * **headers** - *(optional)* Dictionary of HTTP headers to include when sending requests. * **cookies** - *(optional)* Dictionary of Cookie items to include when sending requests. * **verify** - *(optional)* Either `True` to use an SSL context with the default CA bundle, `False` to disable verification, or an instance of `ssl.SSLContext` to use a custom context. * **http2** - *(optional)* A boolean indicating if HTTP/2 support should be enabled. Defaults to `False`. * **proxy** - *(optional)* A proxy URL where all the traffic should be routed. * **timeout** - *(optional)* The timeout configuration to use when sending requests. * **limits** - *(optional)* The limits configuration to use. * **max_redirects** - *(optional)* The maximum number of redirect responses that should be followed. * **base_url** - *(optional)* A URL to use as the base when building request URLs. * **transport** - *(optional)* A transport class to use for sending requests over the network. * **trust_env** - *(optional)* Enables or disables usage of environment variables for configuration. * **default_encoding** - *(optional)* The default encoding to use for decoding response text, if no charset information is included in a response Content-Type header. Set to a callable for automatic character set detection. Default: "utf-8". """
def __init__( self, *, auth: AuthTypes | None = None, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, verify: ssl.SSLContext | str | bool = True, cert: CertTypes | None = None, trust_env: bool = True, http1: bool = True, http2: bool = False, proxy: ProxyTypes | None = None, mounts: None | (typing.Mapping[str, BaseTransport | None]) = None, timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, follow_redirects: bool = False, limits: Limits = DEFAULT_LIMITS, max_redirects: int = DEFAULT_MAX_REDIRECTS, event_hooks: None | (typing.Mapping[str, list[EventHook]]) = None, base_url: URL | str = "", transport: BaseTransport | None = None, default_encoding: str | typing.Callable[[bytes], str] = "utf-8", ) -> None: super().__init__( auth=auth, params=params, headers=headers, cookies=cookies, timeout=timeout, follow_redirects=follow_redirects, max_redirects=max_redirects, event_hooks=event_hooks, base_url=base_url, trust_env=trust_env, default_encoding=default_encoding, )
if http2: try: import h2 # noqa except ImportError: # pragma: no cover raise ImportError( "Using http2=True, but the 'h2' package is not installed. " "Make sure to install httpx using `pip install httpx[http2]`." ) from None
allow_env_proxies = trust_env and transport is None proxy_map = self._get_proxy_map(proxy, allow_env_proxies)
self._transport = self._init_transport( verify=verify, cert=cert, trust_env=trust_env, http1=http1, http2=http2, limits=limits, transport=transport, ) self._mounts: dict[URLPattern, BaseTransport | None] = { URLPattern(key): None if proxy is None else self._init_proxy_transport( proxy, verify=verify, cert=cert, trust_env=trust_env, http1=http1, http2=http2, limits=limits, ) for key, proxy in proxy_map.items() } if mounts is not None: self._mounts.update( {URLPattern(key): transport for key, transport in mounts.items()} )
self._mounts = dict(sorted(self._mounts.items()))
def _init_transport( self, verify: ssl.SSLContext | str | bool = True, cert: CertTypes | None = None, trust_env: bool = True, http1: bool = True, http2: bool = False, limits: Limits = DEFAULT_LIMITS, transport: BaseTransport | None = None, ) -> BaseTransport: if transport is not None: return transport
return HTTPTransport( verify=verify, cert=cert, trust_env=trust_env, http1=http1, http2=http2, limits=limits, )
def _init_proxy_transport( self, proxy: Proxy, verify: ssl.SSLContext | str | bool = True, cert: CertTypes | None = None, trust_env: bool = True, http1: bool = True, http2: bool = False, limits: Limits = DEFAULT_LIMITS, ) -> BaseTransport: return HTTPTransport( verify=verify, cert=cert, trust_env=trust_env, http1=http1, http2=http2, limits=limits, proxy=proxy, )
def _transport_for_url(self, url: URL) -> BaseTransport: """ Returns the transport instance that should be used for a given URL. This will either be the standard connection pool, or a proxy. """ for pattern, transport in self._mounts.items(): if pattern.matches(url): return self._transport if transport is None else transport
return self._transport
def request( self, method: str, url: URL | str, *, content: RequestContent | None = None, data: RequestData | None = None, files: RequestFiles | None = None, json: typing.Any | None = None, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, extensions: RequestExtensions | None = None, ) -> Response: """ Build and send a request.
Equivalent to:
```python request = client.build_request(...) response = client.send(request, ...) ```
See `Client.build_request()`, `Client.send()` and [Merging of configuration][0] for how the various parameters are merged with client-level configuration.
[0]: /advanced/clients/#merging-of-configuration """ if cookies is not None: message = ( "Setting per-request cookies=<...> is being deprecated, because " "the expected behaviour on cookie persistence is ambiguous. Set " "cookies directly on the client instance instead." ) warnings.warn(message, DeprecationWarning, stacklevel=2)
request = self.build_request( method=method, url=url, content=content, data=data, files=files, json=json, params=params, headers=headers, cookies=cookies, timeout=timeout, extensions=extensions, ) return self.send(request, auth=auth, follow_redirects=follow_redirects)
@contextmanager def stream( self, method: str, url: URL | str, *, content: RequestContent | None = None, data: RequestData | None = None, files: RequestFiles | None = None, json: typing.Any | None = None, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, extensions: RequestExtensions | None = None, ) -> typing.Iterator[Response]: """ Alternative to `httpx.request()` that streams the response body instead of loading it into memory at once.
**Parameters**: See `httpx.request`.
See also: [Streaming Responses][0]
[0]: /quickstart#streaming-responses """ request = self.build_request( method=method, url=url, content=content, data=data, files=files, json=json, params=params, headers=headers, cookies=cookies, timeout=timeout, extensions=extensions, ) response = self.send( request=request, auth=auth, follow_redirects=follow_redirects, stream=True, ) try: yield response finally: response.close()
def send( self, request: Request, *, stream: bool = False, auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, ) -> Response: """ Send a request.
The request is sent as-is, unmodified.
Typically you'll want to build one with `Client.build_request()` so that any client-level configuration is merged into the request, but passing an explicit `httpx.Request()` is supported as well.
See also: [Request instances][0]
[0]: /advanced/clients/#request-instances """ if self._state == ClientState.CLOSED: raise RuntimeError("Cannot send a request, as the client has been closed.")
self._state = ClientState.OPENED follow_redirects = ( self.follow_redirects if isinstance(follow_redirects, UseClientDefault) else follow_redirects )
self._set_timeout(request)
auth = self._build_request_auth(request, auth)
response = self._send_handling_auth( request, auth=auth, follow_redirects=follow_redirects, history=[], ) try: if not stream: response.read()
return response
except BaseException as exc: response.close() raise exc
def _send_handling_auth( self, request: Request, auth: Auth, follow_redirects: bool, history: list[Response], ) -> Response: auth_flow = auth.sync_auth_flow(request) try: request = next(auth_flow)
while True: response = self._send_handling_redirects( request, follow_redirects=follow_redirects, history=history, ) try: try: next_request = auth_flow.send(response) except StopIteration: return response
response.history = list(history) response.read() request = next_request history.append(response)
except BaseException as exc: response.close() raise exc finally: auth_flow.close()
def _send_handling_redirects( self, request: Request, follow_redirects: bool, history: list[Response], ) -> Response: while True: if len(history) > self.max_redirects: raise TooManyRedirects( "Exceeded maximum allowed redirects.", request=request )
for hook in self._event_hooks["request"]: hook(request)
response = self._send_single_request(request) try: for hook in self._event_hooks["response"]: hook(response) response.history = list(history)
if not response.has_redirect_location: return response
request = self._build_redirect_request(request, response) history = history + [response]
if follow_redirects: response.read() else: response.next_request = request return response
except BaseException as exc: response.close() raise exc
def _send_single_request(self, request: Request) -> Response: """ Sends a single request, without handling any redirections. """ transport = self._transport_for_url(request.url) start = time.perf_counter()
if not isinstance(request.stream, SyncByteStream): raise RuntimeError( "Attempted to send an async request with a sync Client instance." )
with request_context(request=request): response = transport.handle_request(request)
assert isinstance(response.stream, SyncByteStream)
response.request = request response.stream = BoundSyncStream( response.stream, response=response, start=start ) self.cookies.extract_cookies(response) response.default_encoding = self._default_encoding
logger.info( 'HTTP Request: %s %s "%s %d %s"', request.method, request.url, response.http_version, response.status_code, response.reason_phrase, )
return response
def get( self, url: URL | str, *, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, extensions: RequestExtensions | None = None, ) -> Response: """ Send a `GET` request.
**Parameters**: See `httpx.request`. """ return self.request( "GET", url, params=params, headers=headers, cookies=cookies, auth=auth, follow_redirects=follow_redirects, timeout=timeout, extensions=extensions, )
def options( self, url: URL | str, *, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, extensions: RequestExtensions | None = None, ) -> Response: """ Send an `OPTIONS` request.
**Parameters**: See `httpx.request`. """ return self.request( "OPTIONS", url, params=params, headers=headers, cookies=cookies, auth=auth, follow_redirects=follow_redirects, timeout=timeout, extensions=extensions, )
def head( self, url: URL | str, *, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, extensions: RequestExtensions | None = None, ) -> Response: """ Send a `HEAD` request.
**Parameters**: See `httpx.request`. """ return self.request( "HEAD", url, params=params, headers=headers, cookies=cookies, auth=auth, follow_redirects=follow_redirects, timeout=timeout, extensions=extensions, )
def post( self, url: URL | str, *, content: RequestContent | None = None, data: RequestData | None = None, files: RequestFiles | None = None, json: typing.Any | None = None, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, extensions: RequestExtensions | None = None, ) -> Response: """ Send a `POST` request.
**Parameters**: See `httpx.request`. """ return self.request( "POST", url, content=content, data=data, files=files, json=json, params=params, headers=headers, cookies=cookies, auth=auth, follow_redirects=follow_redirects, timeout=timeout, extensions=extensions, )
def put( self, url: URL | str, *, content: RequestContent | None = None, data: RequestData | None = None, files: RequestFiles | None = None, json: typing.Any | None = None, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, extensions: RequestExtensions | None = None, ) -> Response: """ Send a `PUT` request.
**Parameters**: See `httpx.request`. """ return self.request( "PUT", url, content=content, data=data, files=files, json=json, params=params, headers=headers, cookies=cookies, auth=auth, follow_redirects=follow_redirects, timeout=timeout, extensions=extensions, )
def patch( self, url: URL | str, *, content: RequestContent | None = None, data: RequestData | None = None, files: RequestFiles | None = None, json: typing.Any | None = None, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, extensions: RequestExtensions | None = None, ) -> Response: """ Send a `PATCH` request.
**Parameters**: See `httpx.request`. """ return self.request( "PATCH", url, content=content, data=data, files=files, json=json, params=params, headers=headers, cookies=cookies, auth=auth, follow_redirects=follow_redirects, timeout=timeout, extensions=extensions, )
def delete( self, url: URL | str, *, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, extensions: RequestExtensions | None = None, ) -> Response: """ Send a `DELETE` request.
**Parameters**: See `httpx.request`. """ return self.request( "DELETE", url, params=params, headers=headers, cookies=cookies, auth=auth, follow_redirects=follow_redirects, timeout=timeout, extensions=extensions, )
def close(self) -> None: """ Close transport and proxies. """ if self._state != ClientState.CLOSED: self._state = ClientState.CLOSED
self._transport.close() for transport in self._mounts.values(): if transport is not None: transport.close()
def __enter__(self: T) -> T: if self._state != ClientState.UNOPENED: msg = { ClientState.OPENED: "Cannot open a client instance more than once.", ClientState.CLOSED: ( "Cannot reopen a client instance, once it has been closed." ), }[self._state] raise RuntimeError(msg)
self._state = ClientState.OPENED
self._transport.__enter__() for transport in self._mounts.values(): if transport is not None: transport.__enter__() return self
def __exit__( self, exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, traceback: TracebackType | None = None, ) -> None: self._state = ClientState.CLOSED
self._transport.__exit__(exc_type, exc_value, traceback) for transport in self._mounts.values(): if transport is not None: transport.__exit__(exc_type, exc_value, traceback)
class AsyncClient(BaseClient): """ An asynchronous HTTP client, with connection pooling, HTTP/2, redirects, cookie persistence, etc.
It can be shared between tasks.
Usage:
```python >>> async with httpx.AsyncClient() as client: >>> response = await client.get('https://example.org') ```
**Parameters:**
* **auth** - *(optional)* An authentication class to use when sending requests. * **params** - *(optional)* Query parameters to include in request URLs, as a string, dictionary, or sequence of two-tuples. * **headers** - *(optional)* Dictionary of HTTP headers to include when sending requests. * **cookies** - *(optional)* Dictionary of Cookie items to include when sending requests. * **verify** - *(optional)* Either `True` to use an SSL context with the default CA bundle, `False` to disable verification, or an instance of `ssl.SSLContext` to use a custom context. * **http2** - *(optional)* A boolean indicating if HTTP/2 support should be enabled. Defaults to `False`. * **proxy** - *(optional)* A proxy URL where all the traffic should be routed. * **timeout** - *(optional)* The timeout configuration to use when sending requests. * **limits** - *(optional)* The limits configuration to use. * **max_redirects** - *(optional)* The maximum number of redirect responses that should be followed. * **base_url** - *(optional)* A URL to use as the base when building request URLs. * **transport** - *(optional)* A transport class to use for sending requests over the network. * **trust_env** - *(optional)* Enables or disables usage of environment variables for configuration. * **default_encoding** - *(optional)* The default encoding to use for decoding response text, if no charset information is included in a response Content-Type header. Set to a callable for automatic character set detection. Default: "utf-8". """
def __init__( self, *, auth: AuthTypes | None = None, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, verify: ssl.SSLContext | str | bool = True, cert: CertTypes | None = None, http1: bool = True, http2: bool = False, proxy: ProxyTypes | None = None, mounts: None | (typing.Mapping[str, AsyncBaseTransport | None]) = None, timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, follow_redirects: bool = False, limits: Limits = DEFAULT_LIMITS, max_redirects: int = DEFAULT_MAX_REDIRECTS, event_hooks: None | (typing.Mapping[str, list[EventHook]]) = None, base_url: URL | str = "", transport: AsyncBaseTransport | None = None, trust_env: bool = True, default_encoding: str | typing.Callable[[bytes], str] = "utf-8", ) -> None: super().__init__( auth=auth, params=params, headers=headers, cookies=cookies, timeout=timeout, follow_redirects=follow_redirects, max_redirects=max_redirects, event_hooks=event_hooks, base_url=base_url, trust_env=trust_env, default_encoding=default_encoding, )
if http2: try: import h2 # noqa except ImportError: # pragma: no cover raise ImportError( "Using http2=True, but the 'h2' package is not installed. " "Make sure to install httpx using `pip install httpx[http2]`." ) from None
allow_env_proxies = trust_env and transport is None proxy_map = self._get_proxy_map(proxy, allow_env_proxies)
self._transport = self._init_transport( verify=verify, cert=cert, trust_env=trust_env, http1=http1, http2=http2, limits=limits, transport=transport, )
self._mounts: dict[URLPattern, AsyncBaseTransport | None] = { URLPattern(key): None if proxy is None else self._init_proxy_transport( proxy, verify=verify, cert=cert, trust_env=trust_env, http1=http1, http2=http2, limits=limits, ) for key, proxy in proxy_map.items() } if mounts is not None: self._mounts.update( {URLPattern(key): transport for key, transport in mounts.items()} ) self._mounts = dict(sorted(self._mounts.items()))
def _init_transport( self, verify: ssl.SSLContext | str | bool = True, cert: CertTypes | None = None, trust_env: bool = True, http1: bool = True, http2: bool = False, limits: Limits = DEFAULT_LIMITS, transport: AsyncBaseTransport | None = None, ) -> AsyncBaseTransport: if transport is not None: return transport
return AsyncHTTPTransport( verify=verify, cert=cert, trust_env=trust_env, http1=http1, http2=http2, limits=limits, )
def _init_proxy_transport( self, proxy: Proxy, verify: ssl.SSLContext | str | bool = True, cert: CertTypes | None = None, trust_env: bool = True, http1: bool = True, http2: bool = False, limits: Limits = DEFAULT_LIMITS, ) -> AsyncBaseTransport: return AsyncHTTPTransport( verify=verify, cert=cert, trust_env=trust_env, http1=http1, http2=http2, limits=limits, proxy=proxy, )
def _transport_for_url(self, url: URL) -> AsyncBaseTransport: """ Returns the transport instance that should be used for a given URL. This will either be the standard connection pool, or a proxy. """ for pattern, transport in self._mounts.items(): if pattern.matches(url): return self._transport if transport is None else transport
return self._transport
async def request( self, method: str, url: URL | str, *, content: RequestContent | None = None, data: RequestData | None = None, files: RequestFiles | None = None, json: typing.Any | None = None, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, extensions: RequestExtensions | None = None, ) -> Response: """ Build and send a request.
Equivalent to:
```python request = client.build_request(...) response = await client.send(request, ...) ```
See `AsyncClient.build_request()`, `AsyncClient.send()` and [Merging of configuration][0] for how the various parameters are merged with client-level configuration.
[0]: /advanced/clients/#merging-of-configuration """
if cookies is not None: # pragma: no cover message = ( "Setting per-request cookies=<...> is being deprecated, because " "the expected behaviour on cookie persistence is ambiguous. Set " "cookies directly on the client instance instead." ) warnings.warn(message, DeprecationWarning, stacklevel=2)
request = self.build_request( method=method, url=url, content=content, data=data, files=files, json=json, params=params, headers=headers, cookies=cookies, timeout=timeout, extensions=extensions, ) return await self.send(request, auth=auth, follow_redirects=follow_redirects)
@asynccontextmanager async def stream( self, method: str, url: URL | str, *, content: RequestContent | None = None, data: RequestData | None = None, files: RequestFiles | None = None, json: typing.Any | None = None, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, extensions: RequestExtensions | None = None, ) -> typing.AsyncIterator[Response]: """ Alternative to `httpx.request()` that streams the response body instead of loading it into memory at once.
**Parameters**: See `httpx.request`.
See also: [Streaming Responses][0]
[0]: /quickstart#streaming-responses """ request = self.build_request( method=method, url=url, content=content, data=data, files=files, json=json, params=params, headers=headers, cookies=cookies, timeout=timeout, extensions=extensions, ) response = await self.send( request=request, auth=auth, follow_redirects=follow_redirects, stream=True, ) try: yield response finally: await response.aclose()
async def send( self, request: Request, *, stream: bool = False, auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, ) -> Response: """ Send a request.
The request is sent as-is, unmodified.
Typically you'll want to build one with `AsyncClient.build_request()` so that any client-level configuration is merged into the request, but passing an explicit `httpx.Request()` is supported as well.
See also: [Request instances][0]
[0]: /advanced/clients/#request-instances """ if self._state == ClientState.CLOSED: raise RuntimeError("Cannot send a request, as the client has been closed.")
self._state = ClientState.OPENED follow_redirects = ( self.follow_redirects if isinstance(follow_redirects, UseClientDefault) else follow_redirects )
self._set_timeout(request)
auth = self._build_request_auth(request, auth)
response = await self._send_handling_auth( request, auth=auth, follow_redirects=follow_redirects, history=[], ) try: if not stream: await response.aread()
return response
except BaseException as exc: await response.aclose() raise exc
async def _send_handling_auth( self, request: Request, auth: Auth, follow_redirects: bool, history: list[Response], ) -> Response: auth_flow = auth.async_auth_flow(request) try: request = await auth_flow.__anext__()
while True: response = await self._send_handling_redirects( request, follow_redirects=follow_redirects, history=history, ) try: try: next_request = await auth_flow.asend(response) except StopAsyncIteration: return response
response.history = list(history) await response.aread() request = next_request history.append(response)
except BaseException as exc: await response.aclose() raise exc finally: await auth_flow.aclose()
async def _send_handling_redirects( self, request: Request, follow_redirects: bool, history: list[Response], ) -> Response: while True: if len(history) > self.max_redirects: raise TooManyRedirects( "Exceeded maximum allowed redirects.", request=request )
for hook in self._event_hooks["request"]: await hook(request)
response = await self._send_single_request(request) try: for hook in self._event_hooks["response"]: await hook(response)
response.history = list(history)
if not response.has_redirect_location: return response
request = self._build_redirect_request(request, response) history = history + [response]
if follow_redirects: await response.aread() else: response.next_request = request return response
except BaseException as exc: await response.aclose() raise exc
async def _send_single_request(self, request: Request) -> Response: """ Sends a single request, without handling any redirections. """ transport = self._transport_for_url(request.url) start = time.perf_counter()
if not isinstance(request.stream, AsyncByteStream): raise RuntimeError( "Attempted to send an sync request with an AsyncClient instance." )
with request_context(request=request): response = await transport.handle_async_request(request)
assert isinstance(response.stream, AsyncByteStream) response.request = request response.stream = BoundAsyncStream( response.stream, response=response, start=start ) self.cookies.extract_cookies(response) response.default_encoding = self._default_encoding
logger.info( 'HTTP Request: %s %s "%s %d %s"', request.method, request.url, response.http_version, response.status_code, response.reason_phrase, )
return response
async def get( self, url: URL | str, *, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, extensions: RequestExtensions | None = None, ) -> Response: """ Send a `GET` request.
**Parameters**: See `httpx.request`. """ return await self.request( "GET", url, params=params, headers=headers, cookies=cookies, auth=auth, follow_redirects=follow_redirects, timeout=timeout, extensions=extensions, )
async def options( self, url: URL | str, *, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, extensions: RequestExtensions | None = None, ) -> Response: """ Send an `OPTIONS` request.
**Parameters**: See `httpx.request`. """ return await self.request( "OPTIONS", url, params=params, headers=headers, cookies=cookies, auth=auth, follow_redirects=follow_redirects, timeout=timeout, extensions=extensions, )
async def head( self, url: URL | str, *, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, extensions: RequestExtensions | None = None, ) -> Response: """ Send a `HEAD` request.
**Parameters**: See `httpx.request`. """ return await self.request( "HEAD", url, params=params, headers=headers, cookies=cookies, auth=auth, follow_redirects=follow_redirects, timeout=timeout, extensions=extensions, )
async def post( self, url: URL | str, *, content: RequestContent | None = None, data: RequestData | None = None, files: RequestFiles | None = None, json: typing.Any | None = None, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, extensions: RequestExtensions | None = None, ) -> Response: """ Send a `POST` request.
**Parameters**: See `httpx.request`. """ return await self.request( "POST", url, content=content, data=data, files=files, json=json, params=params, headers=headers, cookies=cookies, auth=auth, follow_redirects=follow_redirects, timeout=timeout, extensions=extensions, )
async def put( self, url: URL | str, *, content: RequestContent | None = None, data: RequestData | None = None, files: RequestFiles | None = None, json: typing.Any | None = None, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, extensions: RequestExtensions | None = None, ) -> Response: """ Send a `PUT` request.
**Parameters**: See `httpx.request`. """ return await self.request( "PUT", url, content=content, data=data, files=files, json=json, params=params, headers=headers, cookies=cookies, auth=auth, follow_redirects=follow_redirects, timeout=timeout, extensions=extensions, )
async def patch( self, url: URL | str, *, content: RequestContent | None = None, data: RequestData | None = None, files: RequestFiles | None = None, json: typing.Any | None = None, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, extensions: RequestExtensions | None = None, ) -> Response: """ Send a `PATCH` request.
**Parameters**: See `httpx.request`. """ return await self.request( "PATCH", url, content=content, data=data, files=files, json=json, params=params, headers=headers, cookies=cookies, auth=auth, follow_redirects=follow_redirects, timeout=timeout, extensions=extensions, )
async def delete( self, url: URL | str, *, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, extensions: RequestExtensions | None = None, ) -> Response: """ Send a `DELETE` request.
**Parameters**: See `httpx.request`. """ return await self.request( "DELETE", url, params=params, headers=headers, cookies=cookies, auth=auth, follow_redirects=follow_redirects, timeout=timeout, extensions=extensions, )
async def aclose(self) -> None: """ Close transport and proxies. """ if self._state != ClientState.CLOSED: self._state = ClientState.CLOSED
await self._transport.aclose() for proxy in self._mounts.values(): if proxy is not None: await proxy.aclose()
async def __aenter__(self: U) -> U: if self._state != ClientState.UNOPENED: msg = { ClientState.OPENED: "Cannot open a client instance more than once.", ClientState.CLOSED: ( "Cannot reopen a client instance, once it has been closed." ), }[self._state] raise RuntimeError(msg)
self._state = ClientState.OPENED
await self._transport.__aenter__() for proxy in self._mounts.values(): if proxy is not None: await proxy.__aenter__() return self
async def __aexit__( self, exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, traceback: TracebackType | None = None, ) -> None: self._state = ClientState.CLOSED
await self._transport.__aexit__(exc_type, exc_value, traceback) for proxy in self._mounts.values(): if proxy is not None: await proxy.__aexit__(exc_type, exc_value, traceback)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248from __future__ import annotations
import osimport typing
from ._models import Headersfrom ._types import CertTypes, HeaderTypes, TimeoutTypesfrom ._urls import URL
if typing.TYPE_CHECKING: import ssl # pragma: no cover
__all__ = ["Limits", "Proxy", "Timeout", "create_ssl_context"]
class UnsetType: pass # pragma: no cover
UNSET = UnsetType()
def create_ssl_context( verify: ssl.SSLContext | str | bool = True, cert: CertTypes | None = None, trust_env: bool = True,) -> ssl.SSLContext: import ssl import warnings
import certifi
if verify is True: if trust_env and os.environ.get("SSL_CERT_FILE"): # pragma: nocover ctx = ssl.create_default_context(cafile=os.environ["SSL_CERT_FILE"]) elif trust_env and os.environ.get("SSL_CERT_DIR"): # pragma: nocover ctx = ssl.create_default_context(capath=os.environ["SSL_CERT_DIR"]) else: # Default case... ctx = ssl.create_default_context(cafile=certifi.where()) elif verify is False: ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE elif isinstance(verify, str): # pragma: nocover message = ( "`verify=<str>` is deprecated. " "Use `verify=ssl.create_default_context(cafile=...)` " "or `verify=ssl.create_default_context(capath=...)` instead." ) warnings.warn(message, DeprecationWarning) if os.path.isdir(verify): return ssl.create_default_context(capath=verify) return ssl.create_default_context(cafile=verify) else: ctx = verify
if cert: # pragma: nocover message = ( "`cert=...` is deprecated. Use `verify=<ssl_context>` instead," "with `.load_cert_chain()` to configure the certificate chain." ) warnings.warn(message, DeprecationWarning) if isinstance(cert, str): ctx.load_cert_chain(cert) else: ctx.load_cert_chain(*cert)
return ctx
class Timeout: """ Timeout configuration.
**Usage**:
Timeout(None) # No timeouts. Timeout(5.0) # 5s timeout on all operations. Timeout(None, connect=5.0) # 5s timeout on connect, no other timeouts. Timeout(5.0, connect=10.0) # 10s timeout on connect. 5s timeout elsewhere. Timeout(5.0, pool=None) # No timeout on acquiring connection from pool. # 5s timeout elsewhere. """
def __init__( self, timeout: TimeoutTypes | UnsetType = UNSET, *, connect: None | float | UnsetType = UNSET, read: None | float | UnsetType = UNSET, write: None | float | UnsetType = UNSET, pool: None | float | UnsetType = UNSET, ) -> None: if isinstance(timeout, Timeout): # Passed as a single explicit Timeout. assert connect is UNSET assert read is UNSET assert write is UNSET assert pool is UNSET self.connect = timeout.connect # type: typing.Optional[float] self.read = timeout.read # type: typing.Optional[float] self.write = timeout.write # type: typing.Optional[float] self.pool = timeout.pool # type: typing.Optional[float] elif isinstance(timeout, tuple): # Passed as a tuple. self.connect = timeout[0] self.read = timeout[1] self.write = None if len(timeout) < 3 else timeout[2] self.pool = None if len(timeout) < 4 else timeout[3] elif not ( isinstance(connect, UnsetType) or isinstance(read, UnsetType) or isinstance(write, UnsetType) or isinstance(pool, UnsetType) ): self.connect = connect self.read = read self.write = write self.pool = pool else: if isinstance(timeout, UnsetType): raise ValueError( "httpx.Timeout must either include a default, or set all " "four parameters explicitly." ) self.connect = timeout if isinstance(connect, UnsetType) else connect self.read = timeout if isinstance(read, UnsetType) else read self.write = timeout if isinstance(write, UnsetType) else write self.pool = timeout if isinstance(pool, UnsetType) else pool
def as_dict(self) -> dict[str, float | None]: return { "connect": self.connect, "read": self.read, "write": self.write, "pool": self.pool, }
def __eq__(self, other: typing.Any) -> bool: return ( isinstance(other, self.__class__) and self.connect == other.connect and self.read == other.read and self.write == other.write and self.pool == other.pool )
def __repr__(self) -> str: class_name = self.__class__.__name__ if len({self.connect, self.read, self.write, self.pool}) == 1: return f"{class_name}(timeout={self.connect})" return ( f"{class_name}(connect={self.connect}, " f"read={self.read}, write={self.write}, pool={self.pool})" )
class Limits: """ Configuration for limits to various client behaviors.
**Parameters:**
* **max_connections** - The maximum number of concurrent connections that may be established. * **max_keepalive_connections** - Allow the connection pool to maintain keep-alive connections below this point. Should be less than or equal to `max_connections`. * **keepalive_expiry** - Time limit on idle keep-alive connections in seconds. """
def __init__( self, *, max_connections: int | None = None, max_keepalive_connections: int | None = None, keepalive_expiry: float | None = 5.0, ) -> None: self.max_connections = max_connections self.max_keepalive_connections = max_keepalive_connections self.keepalive_expiry = keepalive_expiry
def __eq__(self, other: typing.Any) -> bool: return ( isinstance(other, self.__class__) and self.max_connections == other.max_connections and self.max_keepalive_connections == other.max_keepalive_connections and self.keepalive_expiry == other.keepalive_expiry )
def __repr__(self) -> str: class_name = self.__class__.__name__ return ( f"{class_name}(max_connections={self.max_connections}, " f"max_keepalive_connections={self.max_keepalive_connections}, " f"keepalive_expiry={self.keepalive_expiry})" )
class Proxy: def __init__( self, url: URL | str, *, ssl_context: ssl.SSLContext | None = None, auth: tuple[str, str] | None = None, headers: HeaderTypes | None = None, ) -> None: url = URL(url) headers = Headers(headers)
if url.scheme not in ("http", "https", "socks5", "socks5h"): raise ValueError(f"Unknown scheme for proxy URL {url!r}")
if url.username or url.password: # Remove any auth credentials from the URL. auth = (url.username, url.password) url = url.copy_with(username=None, password=None)
self.url = url self.auth = auth self.headers = headers self.ssl_context = ssl_context
@property def raw_auth(self) -> tuple[bytes, bytes] | None: # The proxy authentication as raw bytes. return ( None if self.auth is None else (self.auth[0].encode("utf-8"), self.auth[1].encode("utf-8")) )
def __repr__(self) -> str: # The authentication is represented with the password component masked. auth = (self.auth[0], "********") if self.auth else None
# Build a nice concise representation. url_str = f"{str(self.url)!r}" auth_str = f", auth={auth!r}" if auth else "" headers_str = f", headers={dict(self.headers)!r}" if self.headers else "" return f"Proxy({url_str}{auth_str}{headers_str})"
DEFAULT_TIMEOUT_CONFIG = Timeout(timeout=5.0)DEFAULT_LIMITS = Limits(max_connections=100, max_keepalive_connections=20)DEFAULT_MAX_REDIRECTS = 20123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240from __future__ import annotations
import inspectimport warningsfrom json import dumps as json_dumpsfrom typing import ( Any, AsyncIterable, AsyncIterator, Iterable, Iterator, Mapping,)from urllib.parse import urlencode
from ._exceptions import StreamClosed, StreamConsumedfrom ._multipart import MultipartStreamfrom ._types import ( AsyncByteStream, RequestContent, RequestData, RequestFiles, ResponseContent, SyncByteStream,)from ._utils import peek_filelike_length, primitive_value_to_str
__all__ = ["ByteStream"]
class ByteStream(AsyncByteStream, SyncByteStream): def __init__(self, stream: bytes) -> None: self._stream = stream
def __iter__(self) -> Iterator[bytes]: yield self._stream
async def __aiter__(self) -> AsyncIterator[bytes]: yield self._stream
class IteratorByteStream(SyncByteStream): CHUNK_SIZE = 65_536
def __init__(self, stream: Iterable[bytes]) -> None: self._stream = stream self._is_stream_consumed = False self._is_generator = inspect.isgenerator(stream)
def __iter__(self) -> Iterator[bytes]: if self._is_stream_consumed and self._is_generator: raise StreamConsumed()
self._is_stream_consumed = True if hasattr(self._stream, "read"): # File-like interfaces should use 'read' directly. chunk = self._stream.read(self.CHUNK_SIZE) while chunk: yield chunk chunk = self._stream.read(self.CHUNK_SIZE) else: # Otherwise iterate. for part in self._stream: yield part
class AsyncIteratorByteStream(AsyncByteStream): CHUNK_SIZE = 65_536
def __init__(self, stream: AsyncIterable[bytes]) -> None: self._stream = stream self._is_stream_consumed = False self._is_generator = inspect.isasyncgen(stream)
async def __aiter__(self) -> AsyncIterator[bytes]: if self._is_stream_consumed and self._is_generator: raise StreamConsumed()
self._is_stream_consumed = True if hasattr(self._stream, "aread"): # File-like interfaces should use 'aread' directly. chunk = await self._stream.aread(self.CHUNK_SIZE) while chunk: yield chunk chunk = await self._stream.aread(self.CHUNK_SIZE) else: # Otherwise iterate. async for part in self._stream: yield part
class UnattachedStream(AsyncByteStream, SyncByteStream): """ If a request or response is serialized using pickle, then it is no longer attached to a stream for I/O purposes. Any stream operations should result in `httpx.StreamClosed`. """
def __iter__(self) -> Iterator[bytes]: raise StreamClosed()
async def __aiter__(self) -> AsyncIterator[bytes]: raise StreamClosed() yield b"" # pragma: no cover
def encode_content( content: str | bytes | Iterable[bytes] | AsyncIterable[bytes],) -> tuple[dict[str, str], SyncByteStream | AsyncByteStream]: if isinstance(content, (bytes, str)): body = content.encode("utf-8") if isinstance(content, str) else content content_length = len(body) headers = {"Content-Length": str(content_length)} if body else {} return headers, ByteStream(body)
elif isinstance(content, Iterable) and not isinstance(content, dict): # `not isinstance(content, dict)` is a bit oddly specific, but it # catches a case that's easy for users to make in error, and would # otherwise pass through here, like any other bytes-iterable, # because `dict` happens to be iterable. See issue #2491. content_length_or_none = peek_filelike_length(content)
if content_length_or_none is None: headers = {"Transfer-Encoding": "chunked"} else: headers = {"Content-Length": str(content_length_or_none)} return headers, IteratorByteStream(content) # type: ignore
elif isinstance(content, AsyncIterable): headers = {"Transfer-Encoding": "chunked"} return headers, AsyncIteratorByteStream(content)
raise TypeError(f"Unexpected type for 'content', {type(content)!r}")
def encode_urlencoded_data( data: RequestData,) -> tuple[dict[str, str], ByteStream]: plain_data = [] for key, value in data.items(): if isinstance(value, (list, tuple)): plain_data.extend([(key, primitive_value_to_str(item)) for item in value]) else: plain_data.append((key, primitive_value_to_str(value))) body = urlencode(plain_data, doseq=True).encode("utf-8") content_length = str(len(body)) content_type = "application/x-www-form-urlencoded" headers = {"Content-Length": content_length, "Content-Type": content_type} return headers, ByteStream(body)
def encode_multipart_data( data: RequestData, files: RequestFiles, boundary: bytes | None) -> tuple[dict[str, str], MultipartStream]: multipart = MultipartStream(data=data, files=files, boundary=boundary) headers = multipart.get_headers() return headers, multipart
def encode_text(text: str) -> tuple[dict[str, str], ByteStream]: body = text.encode("utf-8") content_length = str(len(body)) content_type = "text/plain; charset=utf-8" headers = {"Content-Length": content_length, "Content-Type": content_type} return headers, ByteStream(body)
def encode_html(html: str) -> tuple[dict[str, str], ByteStream]: body = html.encode("utf-8") content_length = str(len(body)) content_type = "text/html; charset=utf-8" headers = {"Content-Length": content_length, "Content-Type": content_type} return headers, ByteStream(body)
def encode_json(json: Any) -> tuple[dict[str, str], ByteStream]: body = json_dumps( json, ensure_ascii=False, separators=(",", ":"), allow_nan=False ).encode("utf-8") content_length = str(len(body)) content_type = "application/json" headers = {"Content-Length": content_length, "Content-Type": content_type} return headers, ByteStream(body)
def encode_request( content: RequestContent | None = None, data: RequestData | None = None, files: RequestFiles | None = None, json: Any | None = None, boundary: bytes | None = None,) -> tuple[dict[str, str], SyncByteStream | AsyncByteStream]: """ Handles encoding the given `content`, `data`, `files`, and `json`, returning a two-tuple of (<headers>, <stream>). """ if data is not None and not isinstance(data, Mapping): # We prefer to separate `content=<bytes|str|byte iterator|bytes aiterator>` # for raw request content, and `data=<form data>` for url encoded or # multipart form content. # # However for compat with requests, we *do* still support # `data=<bytes...>` usages. We deal with that case here, treating it # as if `content=<...>` had been supplied instead. message = "Use 'content=<...>' to upload raw bytes/text content." warnings.warn(message, DeprecationWarning, stacklevel=2) return encode_content(data)
if content is not None: return encode_content(content) elif files: return encode_multipart_data(data or {}, files, boundary) elif data: return encode_urlencoded_data(data) elif json is not None: return encode_json(json)
return {}, ByteStream(b"")
def encode_response( content: ResponseContent | None = None, text: str | None = None, html: str | None = None, json: Any | None = None,) -> tuple[dict[str, str], SyncByteStream | AsyncByteStream]: """ Handles encoding the given `content`, returning a two-tuple of (<headers>, <stream>). """ if content is not None: return encode_content(content) elif text is not None: return encode_text(text) elif html is not None: return encode_html(html) elif json is not None: return encode_json(json)
return {}, ByteStream(b"")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393"""Handlers for Content-Encoding.
See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding"""
from __future__ import annotations
import codecsimport ioimport typingimport zlib
from ._exceptions import DecodingError
# Brotli support is optionaltry: # The C bindings in `brotli` are recommended for CPython. import brotliexcept ImportError: # pragma: no cover try: # The CFFI bindings in `brotlicffi` are recommended for PyPy # and other environments. import brotlicffi as brotli except ImportError: brotli = None
# Zstandard support is optionaltry: import zstandardexcept ImportError: # pragma: no cover zstandard = None # type: ignore
class ContentDecoder: def decode(self, data: bytes) -> bytes: raise NotImplementedError() # pragma: no cover
def flush(self) -> bytes: raise NotImplementedError() # pragma: no cover
class IdentityDecoder(ContentDecoder): """ Handle unencoded data. """
def decode(self, data: bytes) -> bytes: return data
def flush(self) -> bytes: return b""
class DeflateDecoder(ContentDecoder): """ Handle 'deflate' decoding.
See: https://stackoverflow.com/questions/1838699 """
def __init__(self) -> None: self.first_attempt = True self.decompressor = zlib.decompressobj()
def decode(self, data: bytes) -> bytes: was_first_attempt = self.first_attempt self.first_attempt = False try: return self.decompressor.decompress(data) except zlib.error as exc: if was_first_attempt: self.decompressor = zlib.decompressobj(-zlib.MAX_WBITS) return self.decode(data) raise DecodingError(str(exc)) from exc
def flush(self) -> bytes: try: return self.decompressor.flush() except zlib.error as exc: # pragma: no cover raise DecodingError(str(exc)) from exc
class GZipDecoder(ContentDecoder): """ Handle 'gzip' decoding.
See: https://stackoverflow.com/questions/1838699 """
def __init__(self) -> None: self.decompressor = zlib.decompressobj(zlib.MAX_WBITS | 16)
def decode(self, data: bytes) -> bytes: try: return self.decompressor.decompress(data) except zlib.error as exc: raise DecodingError(str(exc)) from exc
def flush(self) -> bytes: try: return self.decompressor.flush() except zlib.error as exc: # pragma: no cover raise DecodingError(str(exc)) from exc
class BrotliDecoder(ContentDecoder): """ Handle 'brotli' decoding.
Requires `pip install brotlipy`. See: https://brotlipy.readthedocs.io/ or `pip install brotli`. See https://github.com/google/brotli Supports both 'brotlipy' and 'Brotli' packages since they share an import name. The top branches are for 'brotlipy' and bottom branches for 'Brotli' """
def __init__(self) -> None: if brotli is None: # pragma: no cover raise ImportError( "Using 'BrotliDecoder', but neither of the 'brotlicffi' or 'brotli' " "packages have been installed. " "Make sure to install httpx using `pip install httpx[brotli]`." ) from None
self.decompressor = brotli.Decompressor() self.seen_data = False self._decompress: typing.Callable[[bytes], bytes] if hasattr(self.decompressor, "decompress"): # The 'brotlicffi' package. self._decompress = self.decompressor.decompress # pragma: no cover else: # The 'brotli' package. self._decompress = self.decompressor.process # pragma: no cover
def decode(self, data: bytes) -> bytes: if not data: return b"" self.seen_data = True try: return self._decompress(data) except brotli.error as exc: raise DecodingError(str(exc)) from exc
def flush(self) -> bytes: if not self.seen_data: return b"" try: if hasattr(self.decompressor, "finish"): # Only available in the 'brotlicffi' package.
# As the decompressor decompresses eagerly, this # will never actually emit any data. However, it will potentially throw # errors if a truncated or damaged data stream has been used. self.decompressor.finish() # pragma: no cover return b"" except brotli.error as exc: # pragma: no cover raise DecodingError(str(exc)) from exc
class ZStandardDecoder(ContentDecoder): """ Handle 'zstd' RFC 8878 decoding.
Requires `pip install zstandard`. Can be installed as a dependency of httpx using `pip install httpx[zstd]`. """
# inspired by the ZstdDecoder implementation in urllib3 def __init__(self) -> None: if zstandard is None: # pragma: no cover raise ImportError( "Using 'ZStandardDecoder', ..." "Make sure to install httpx using `pip install httpx[zstd]`." ) from None
self.decompressor = zstandard.ZstdDecompressor().decompressobj() self.seen_data = False
def decode(self, data: bytes) -> bytes: assert zstandard is not None self.seen_data = True output = io.BytesIO() try: output.write(self.decompressor.decompress(data)) while self.decompressor.eof and self.decompressor.unused_data: unused_data = self.decompressor.unused_data self.decompressor = zstandard.ZstdDecompressor().decompressobj() output.write(self.decompressor.decompress(unused_data)) except zstandard.ZstdError as exc: raise DecodingError(str(exc)) from exc return output.getvalue()
def flush(self) -> bytes: if not self.seen_data: return b"" ret = self.decompressor.flush() # note: this is a no-op if not self.decompressor.eof: raise DecodingError("Zstandard data is incomplete") # pragma: no cover return bytes(ret)
class MultiDecoder(ContentDecoder): """ Handle the case where multiple encodings have been applied. """
def __init__(self, children: typing.Sequence[ContentDecoder]) -> None: """ 'children' should be a sequence of decoders in the order in which each was applied. """ # Note that we reverse the order for decoding. self.children = list(reversed(children))
def decode(self, data: bytes) -> bytes: for child in self.children: data = child.decode(data) return data
def flush(self) -> bytes: data = b"" for child in self.children: data = child.decode(data) + child.flush() return data
class ByteChunker: """ Handles returning byte content in fixed-size chunks. """
def __init__(self, chunk_size: int | None = None) -> None: self._buffer = io.BytesIO() self._chunk_size = chunk_size
def decode(self, content: bytes) -> list[bytes]: if self._chunk_size is None: return [content] if content else []
self._buffer.write(content) if self._buffer.tell() >= self._chunk_size: value = self._buffer.getvalue() chunks = [ value[i : i + self._chunk_size] for i in range(0, len(value), self._chunk_size) ] if len(chunks[-1]) == self._chunk_size: self._buffer.seek(0) self._buffer.truncate() return chunks else: self._buffer.seek(0) self._buffer.write(chunks[-1]) self._buffer.truncate() return chunks[:-1] else: return []
def flush(self) -> list[bytes]: value = self._buffer.getvalue() self._buffer.seek(0) self._buffer.truncate() return [value] if value else []
class TextChunker: """ Handles returning text content in fixed-size chunks. """
def __init__(self, chunk_size: int | None = None) -> None: self._buffer = io.StringIO() self._chunk_size = chunk_size
def decode(self, content: str) -> list[str]: if self._chunk_size is None: return [content] if content else []
self._buffer.write(content) if self._buffer.tell() >= self._chunk_size: value = self._buffer.getvalue() chunks = [ value[i : i + self._chunk_size] for i in range(0, len(value), self._chunk_size) ] if len(chunks[-1]) == self._chunk_size: self._buffer.seek(0) self._buffer.truncate() return chunks else: self._buffer.seek(0) self._buffer.write(chunks[-1]) self._buffer.truncate() return chunks[:-1] else: return []
def flush(self) -> list[str]: value = self._buffer.getvalue() self._buffer.seek(0) self._buffer.truncate() return [value] if value else []
class TextDecoder: """ Handles incrementally decoding bytes into text """
def __init__(self, encoding: str = "utf-8") -> None: self.decoder = codecs.getincrementaldecoder(encoding)(errors="replace")
def decode(self, data: bytes) -> str: return self.decoder.decode(data)
def flush(self) -> str: return self.decoder.decode(b"", True)
class LineDecoder: """ Handles incrementally reading lines from text.
Has the same behaviour as the stdllib splitlines, but handling the input iteratively. """
def __init__(self) -> None: self.buffer: list[str] = [] self.trailing_cr: bool = False
def decode(self, text: str) -> list[str]: # See https://docs.python.org/3/library/stdtypes.html#str.splitlines NEWLINE_CHARS = "\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029"
# We always push a trailing `\r` into the next decode iteration. if self.trailing_cr: text = "\r" + text self.trailing_cr = False if text.endswith("\r"): self.trailing_cr = True text = text[:-1]
if not text: # NOTE: the edge case input of empty text doesn't occur in practice, # because other httpx internals filter out this value return [] # pragma: no cover
trailing_newline = text[-1] in NEWLINE_CHARS lines = text.splitlines()
if len(lines) == 1 and not trailing_newline: # No new lines, buffer the input and continue. self.buffer.append(lines[0]) return []
if self.buffer: # Include any existing buffer in the first portion of the # splitlines result. lines = ["".join(self.buffer) + lines[0]] + lines[1:] self.buffer = []
if not trailing_newline: # If the last segment of splitlines is not newline terminated, # then drop it from our output and start a new buffer. self.buffer = [lines.pop()]
return lines
def flush(self) -> list[str]: if not self.buffer and not self.trailing_cr: return []
lines = ["".join(self.buffer)] self.buffer = [] self.trailing_cr = False return lines
SUPPORTED_DECODERS = { "identity": IdentityDecoder, "gzip": GZipDecoder, "deflate": DeflateDecoder, "br": BrotliDecoder, "zstd": ZStandardDecoder,}
if brotli is None: SUPPORTED_DECODERS.pop("br") # pragma: no coverif zstandard is None: SUPPORTED_DECODERS.pop("zstd") # pragma: no cover123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379"""Our exception hierarchy:
* HTTPError x RequestError + TransportError - TimeoutException · ConnectTimeout · ReadTimeout · WriteTimeout · PoolTimeout - NetworkError · ConnectError · ReadError · WriteError · CloseError - ProtocolError · LocalProtocolError · RemoteProtocolError - ProxyError - UnsupportedProtocol + DecodingError + TooManyRedirects x HTTPStatusError* InvalidURL* CookieConflict* StreamError x StreamConsumed x StreamClosed x ResponseNotRead x RequestNotRead"""
from __future__ import annotations
import contextlibimport typing
if typing.TYPE_CHECKING: from ._models import Request, Response # pragma: no cover
__all__ = [ "CloseError", "ConnectError", "ConnectTimeout", "CookieConflict", "DecodingError", "HTTPError", "HTTPStatusError", "InvalidURL", "LocalProtocolError", "NetworkError", "PoolTimeout", "ProtocolError", "ProxyError", "ReadError", "ReadTimeout", "RemoteProtocolError", "RequestError", "RequestNotRead", "ResponseNotRead", "StreamClosed", "StreamConsumed", "StreamError", "TimeoutException", "TooManyRedirects", "TransportError", "UnsupportedProtocol", "WriteError", "WriteTimeout",]
class HTTPError(Exception): """ Base class for `RequestError` and `HTTPStatusError`.
Useful for `try...except` blocks when issuing a request, and then calling `.raise_for_status()`.
For example:
``` try: response = httpx.get("https://www.example.com") response.raise_for_status() except httpx.HTTPError as exc: print(f"HTTP Exception for {exc.request.url} - {exc}") ``` """
def __init__(self, message: str) -> None: super().__init__(message) self._request: Request | None = None
@property def request(self) -> Request: if self._request is None: raise RuntimeError("The .request property has not been set.") return self._request
@request.setter def request(self, request: Request) -> None: self._request = request
class RequestError(HTTPError): """ Base class for all exceptions that may occur when issuing a `.request()`. """
def __init__(self, message: str, *, request: Request | None = None) -> None: super().__init__(message) # At the point an exception is raised we won't typically have a request # instance to associate it with. # # The 'request_context' context manager is used within the Client and # Response methods in order to ensure that any raised exceptions # have a `.request` property set on them. self._request = request
class TransportError(RequestError): """ Base class for all exceptions that occur at the level of the Transport API. """
# Timeout exceptions...
class TimeoutException(TransportError): """ The base class for timeout errors.
An operation has timed out. """
class ConnectTimeout(TimeoutException): """ Timed out while connecting to the host. """
class ReadTimeout(TimeoutException): """ Timed out while receiving data from the host. """
class WriteTimeout(TimeoutException): """ Timed out while sending data to the host. """
class PoolTimeout(TimeoutException): """ Timed out waiting to acquire a connection from the pool. """
# Core networking exceptions...
class NetworkError(TransportError): """ The base class for network-related errors.
An error occurred while interacting with the network. """
class ReadError(NetworkError): """ Failed to receive data from the network. """
class WriteError(NetworkError): """ Failed to send data through the network. """
class ConnectError(NetworkError): """ Failed to establish a connection. """
class CloseError(NetworkError): """ Failed to close a connection. """
# Other transport exceptions...
class ProxyError(TransportError): """ An error occurred while establishing a proxy connection. """
class UnsupportedProtocol(TransportError): """ Attempted to make a request to an unsupported protocol.
For example issuing a request to `ftp://www.example.com`. """
class ProtocolError(TransportError): """ The protocol was violated. """
class LocalProtocolError(ProtocolError): """ A protocol was violated by the client.
For example if the user instantiated a `Request` instance explicitly, failed to include the mandatory `Host:` header, and then issued it directly using `client.send()`. """
class RemoteProtocolError(ProtocolError): """ The protocol was violated by the server.
For example, returning malformed HTTP. """
# Other request exceptions...
class DecodingError(RequestError): """ Decoding of the response failed, due to a malformed encoding. """
class TooManyRedirects(RequestError): """ Too many redirects. """
# Client errors
class HTTPStatusError(HTTPError): """ The response had an error HTTP status of 4xx or 5xx.
May be raised when calling `response.raise_for_status()` """
def __init__(self, message: str, *, request: Request, response: Response) -> None: super().__init__(message) self.request = request self.response = response
class InvalidURL(Exception): """ URL is improperly formed or cannot be parsed. """
def __init__(self, message: str) -> None: super().__init__(message)
class CookieConflict(Exception): """ Attempted to lookup a cookie by name, but multiple cookies existed.
Can occur when calling `response.cookies.get(...)`. """
def __init__(self, message: str) -> None: super().__init__(message)
# Stream exceptions...
# These may occur as the result of a programming error, by accessing# the request/response stream in an invalid manner.
class StreamError(RuntimeError): """ The base class for stream exceptions.
The developer made an error in accessing the request stream in an invalid way. """
def __init__(self, message: str) -> None: super().__init__(message)
class StreamConsumed(StreamError): """ Attempted to read or stream content, but the content has already been streamed. """
def __init__(self) -> None: message = ( "Attempted to read or stream some content, but the content has " "already been streamed. For requests, this could be due to passing " "a generator as request content, and then receiving a redirect " "response or a secondary request as part of an authentication flow." "For responses, this could be due to attempting to stream the response " "content more than once." ) super().__init__(message)
class StreamClosed(StreamError): """ Attempted to read or stream response content, but the request has been closed. """
def __init__(self) -> None: message = ( "Attempted to read or stream content, but the stream has " "been closed." ) super().__init__(message)
class ResponseNotRead(StreamError): """ Attempted to access streaming response content, without having called `read()`. """
def __init__(self) -> None: message = ( "Attempted to access streaming response content," " without having called `read()`." ) super().__init__(message)
class RequestNotRead(StreamError): """ Attempted to access streaming request content, without having called `read()`. """
def __init__(self) -> None: message = ( "Attempted to access streaming request content," " without having called `read()`." ) super().__init__(message)
@contextlib.contextmanagerdef request_context( request: Request | None = None,) -> typing.Iterator[None]: """ A context manager that can be used to attach the given request context to any `RequestError` exceptions that are raised within the block. """ try: yield except RequestError as exc: if request is not None: exc.request = request raise exc123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506from __future__ import annotations
import functoolsimport jsonimport sysimport typing
import clickimport pygments.lexersimport pygments.utilimport rich.consoleimport rich.markupimport rich.progressimport rich.syntaximport rich.table
from ._client import Clientfrom ._exceptions import RequestErrorfrom ._models import Responsefrom ._status_codes import codes
if typing.TYPE_CHECKING: import httpcore # pragma: no cover
def print_help() -> None: console = rich.console.Console()
console.print("[bold]HTTPX :butterfly:", justify="center") console.print() console.print("A next generation HTTP client.", justify="center") console.print() console.print( "Usage: [bold]httpx[/bold] [cyan]<URL> [OPTIONS][/cyan] ", justify="left" ) console.print()
table = rich.table.Table.grid(padding=1, pad_edge=True) table.add_column("Parameter", no_wrap=True, justify="left", style="bold") table.add_column("Description") table.add_row( "-m, --method [cyan]METHOD", "Request method, such as GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD.\n" "[Default: GET, or POST if a request body is included]", ) table.add_row( "-p, --params [cyan]<NAME VALUE> ...", "Query parameters to include in the request URL.", ) table.add_row( "-c, --content [cyan]TEXT", "Byte content to include in the request body." ) table.add_row( "-d, --data [cyan]<NAME VALUE> ...", "Form data to include in the request body." ) table.add_row( "-f, --files [cyan]<NAME FILENAME> ...", "Form files to include in the request body.", ) table.add_row("-j, --json [cyan]TEXT", "JSON data to include in the request body.") table.add_row( "-h, --headers [cyan]<NAME VALUE> ...", "Include additional HTTP headers in the request.", ) table.add_row( "--cookies [cyan]<NAME VALUE> ...", "Cookies to include in the request." ) table.add_row( "--auth [cyan]<USER PASS>", "Username and password to include in the request. Specify '-' for the password" " to use a password prompt. Note that using --verbose/-v will expose" " the Authorization header, including the password encoding" " in a trivially reversible format.", )
table.add_row( "--proxy [cyan]URL", "Send the request via a proxy. Should be the URL giving the proxy address.", )
table.add_row( "--timeout [cyan]FLOAT", "Timeout value to use for network operations, such as establishing the" " connection, reading some data, etc... [Default: 5.0]", )
table.add_row("--follow-redirects", "Automatically follow redirects.") table.add_row("--no-verify", "Disable SSL verification.") table.add_row( "--http2", "Send the request using HTTP/2, if the remote server supports it." )
table.add_row( "--download [cyan]FILE", "Save the response content as a file, rather than displaying it.", )
table.add_row("-v, --verbose", "Verbose output. Show request as well as response.") table.add_row("--help", "Show this message and exit.") console.print(table)
def get_lexer_for_response(response: Response) -> str: content_type = response.headers.get("Content-Type") if content_type is not None: mime_type, _, _ = content_type.partition(";") try: return typing.cast( str, pygments.lexers.get_lexer_for_mimetype(mime_type.strip()).name ) except pygments.util.ClassNotFound: # pragma: no cover pass return "" # pragma: no cover
def format_request_headers(request: httpcore.Request, http2: bool = False) -> str: version = "HTTP/2" if http2 else "HTTP/1.1" headers = [ (name.lower() if http2 else name, value) for name, value in request.headers ] method = request.method.decode("ascii") target = request.url.target.decode("ascii") lines = [f"{method} {target} {version}"] + [ f"{name.decode('ascii')}: {value.decode('ascii')}" for name, value in headers ] return "\n".join(lines)
def format_response_headers( http_version: bytes, status: int, reason_phrase: bytes | None, headers: list[tuple[bytes, bytes]],) -> str: version = http_version.decode("ascii") reason = ( codes.get_reason_phrase(status) if reason_phrase is None else reason_phrase.decode("ascii") ) lines = [f"{version} {status} {reason}"] + [ f"{name.decode('ascii')}: {value.decode('ascii')}" for name, value in headers ] return "\n".join(lines)
def print_request_headers(request: httpcore.Request, http2: bool = False) -> None: console = rich.console.Console() http_text = format_request_headers(request, http2=http2) syntax = rich.syntax.Syntax(http_text, "http", theme="ansi_dark", word_wrap=True) console.print(syntax) syntax = rich.syntax.Syntax("", "http", theme="ansi_dark", word_wrap=True) console.print(syntax)
def print_response_headers( http_version: bytes, status: int, reason_phrase: bytes | None, headers: list[tuple[bytes, bytes]],) -> None: console = rich.console.Console() http_text = format_response_headers(http_version, status, reason_phrase, headers) syntax = rich.syntax.Syntax(http_text, "http", theme="ansi_dark", word_wrap=True) console.print(syntax) syntax = rich.syntax.Syntax("", "http", theme="ansi_dark", word_wrap=True) console.print(syntax)
def print_response(response: Response) -> None: console = rich.console.Console() lexer_name = get_lexer_for_response(response) if lexer_name: if lexer_name.lower() == "json": try: data = response.json() text = json.dumps(data, indent=4) except ValueError: # pragma: no cover text = response.text else: text = response.text
syntax = rich.syntax.Syntax(text, lexer_name, theme="ansi_dark", word_wrap=True) console.print(syntax) else: console.print(f"<{len(response.content)} bytes of binary data>")
_PCTRTT = typing.Tuple[typing.Tuple[str, str], ...]_PCTRTTT = typing.Tuple[_PCTRTT, ...]_PeerCertRetDictType = typing.Dict[str, typing.Union[str, _PCTRTTT, _PCTRTT]]
def format_certificate(cert: _PeerCertRetDictType) -> str: # pragma: no cover lines = [] for key, value in cert.items(): if isinstance(value, (list, tuple)): lines.append(f"* {key}:") for item in value: if key in ("subject", "issuer"): for sub_item in item: lines.append(f"* {sub_item[0]}: {sub_item[1]!r}") elif isinstance(item, tuple) and len(item) == 2: lines.append(f"* {item[0]}: {item[1]!r}") else: lines.append(f"* {item!r}") else: lines.append(f"* {key}: {value!r}") return "\n".join(lines)
def trace( name: str, info: typing.Mapping[str, typing.Any], verbose: bool = False) -> None: console = rich.console.Console() if name == "connection.connect_tcp.started" and verbose: host = info["host"] console.print(f"* Connecting to {host!r}") elif name == "connection.connect_tcp.complete" and verbose: stream = info["return_value"] server_addr = stream.get_extra_info("server_addr") console.print(f"* Connected to {server_addr[0]!r} on port {server_addr[1]}") elif name == "connection.start_tls.complete" and verbose: # pragma: no cover stream = info["return_value"] ssl_object = stream.get_extra_info("ssl_object") version = ssl_object.version() cipher = ssl_object.cipher() server_cert = ssl_object.getpeercert() alpn = ssl_object.selected_alpn_protocol() console.print(f"* SSL established using {version!r} / {cipher[0]!r}") console.print(f"* Selected ALPN protocol: {alpn!r}") if server_cert: console.print("* Server certificate:") console.print(format_certificate(server_cert)) elif name == "http11.send_request_headers.started" and verbose: request = info["request"] print_request_headers(request, http2=False) elif name == "http2.send_request_headers.started" and verbose: # pragma: no cover request = info["request"] print_request_headers(request, http2=True) elif name == "http11.receive_response_headers.complete": http_version, status, reason_phrase, headers = info["return_value"] print_response_headers(http_version, status, reason_phrase, headers) elif name == "http2.receive_response_headers.complete": # pragma: no cover status, headers = info["return_value"] http_version = b"HTTP/2" reason_phrase = None print_response_headers(http_version, status, reason_phrase, headers)
def download_response(response: Response, download: typing.BinaryIO) -> None: console = rich.console.Console() console.print() content_length = response.headers.get("Content-Length") with rich.progress.Progress( "[progress.description]{task.description}", "[progress.percentage]{task.percentage:>3.0f}%", rich.progress.BarColumn(bar_width=None), rich.progress.DownloadColumn(), rich.progress.TransferSpeedColumn(), ) as progress: description = f"Downloading [bold]{rich.markup.escape(download.name)}" download_task = progress.add_task( description, total=int(content_length or 0), start=content_length is not None, ) for chunk in response.iter_bytes(): download.write(chunk) progress.update(download_task, completed=response.num_bytes_downloaded)
def validate_json( ctx: click.Context, param: click.Option | click.Parameter, value: typing.Any,) -> typing.Any: if value is None: return None
try: return json.loads(value) except json.JSONDecodeError: # pragma: no cover raise click.BadParameter("Not valid JSON")
def validate_auth( ctx: click.Context, param: click.Option | click.Parameter, value: typing.Any,) -> typing.Any: if value == (None, None): return None
username, password = value if password == "-": # pragma: no cover password = click.prompt("Password", hide_input=True) return (username, password)
def handle_help( ctx: click.Context, param: click.Option | click.Parameter, value: typing.Any,) -> None: if not value or ctx.resilient_parsing: return
print_help() ctx.exit()
@click.command(add_help_option=False)@click.argument("url", type=str)@click.option( "--method", "-m", "method", type=str, help=( "Request method, such as GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD. " "[Default: GET, or POST if a request body is included]" ),)@click.option( "--params", "-p", "params", type=(str, str), multiple=True, help="Query parameters to include in the request URL.",)@click.option( "--content", "-c", "content", type=str, help="Byte content to include in the request body.",)@click.option( "--data", "-d", "data", type=(str, str), multiple=True, help="Form data to include in the request body.",)@click.option( "--files", "-f", "files", type=(str, click.File(mode="rb")), multiple=True, help="Form files to include in the request body.",)@click.option( "--json", "-j", "json", type=str, callback=validate_json, help="JSON data to include in the request body.",)@click.option( "--headers", "-h", "headers", type=(str, str), multiple=True, help="Include additional HTTP headers in the request.",)@click.option( "--cookies", "cookies", type=(str, str), multiple=True, help="Cookies to include in the request.",)@click.option( "--auth", "auth", type=(str, str), default=(None, None), callback=validate_auth, help=( "Username and password to include in the request. " "Specify '-' for the password to use a password prompt. " "Note that using --verbose/-v will expose the Authorization header, " "including the password encoding in a trivially reversible format." ),)@click.option( "--proxy", "proxy", type=str, default=None, help="Send the request via a proxy. Should be the URL giving the proxy address.",)@click.option( "--timeout", "timeout", type=float, default=5.0, help=( "Timeout value to use for network operations, such as establishing the " "connection, reading some data, etc... [Default: 5.0]" ),)@click.option( "--follow-redirects", "follow_redirects", is_flag=True, default=False, help="Automatically follow redirects.",)@click.option( "--no-verify", "verify", is_flag=True, default=True, help="Disable SSL verification.",)@click.option( "--http2", "http2", type=bool, is_flag=True, default=False, help="Send the request using HTTP/2, if the remote server supports it.",)@click.option( "--download", type=click.File("wb"), help="Save the response content as a file, rather than displaying it.",)@click.option( "--verbose", "-v", type=bool, is_flag=True, default=False, help="Verbose. Show request as well as response.",)@click.option( "--help", is_flag=True, is_eager=True, expose_value=False, callback=handle_help, help="Show this message and exit.",)def main( url: str, method: str, params: list[tuple[str, str]], content: str, data: list[tuple[str, str]], files: list[tuple[str, click.File]], json: str, headers: list[tuple[str, str]], cookies: list[tuple[str, str]], auth: tuple[str, str] | None, proxy: str, timeout: float, follow_redirects: bool, verify: bool, http2: bool, download: typing.BinaryIO | None, verbose: bool,) -> None: """ An HTTP command line client. Sends a request and displays the response. """ if not method: method = "POST" if content or data or files or json else "GET"
try: with Client(proxy=proxy, timeout=timeout, http2=http2, verify=verify) as client: with client.stream( method, url, params=list(params), content=content, data=dict(data), files=files, # type: ignore json=json, headers=headers, cookies=dict(cookies), auth=auth, follow_redirects=follow_redirects, extensions={"trace": functools.partial(trace, verbose=verbose)}, ) as response: if download is not None: download_response(response, download) else: response.read() if response.content: print_response(response)
except RequestError as exc: console = rich.console.Console() console.print(f"[red]{type(exc).__name__}[/red]: {exc}") sys.exit(1)
sys.exit(0 if response.is_success else 1)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277from __future__ import annotations
import codecsimport datetimeimport email.messageimport json as jsonlibimport reimport typingimport urllib.requestfrom collections.abc import Mappingfrom http.cookiejar import Cookie, CookieJar
from ._content import ByteStream, UnattachedStream, encode_request, encode_responsefrom ._decoders import ( SUPPORTED_DECODERS, ByteChunker, ContentDecoder, IdentityDecoder, LineDecoder, MultiDecoder, TextChunker, TextDecoder,)from ._exceptions import ( CookieConflict, HTTPStatusError, RequestNotRead, ResponseNotRead, StreamClosed, StreamConsumed, request_context,)from ._multipart import get_multipart_boundary_from_content_typefrom ._status_codes import codesfrom ._types import ( AsyncByteStream, CookieTypes, HeaderTypes, QueryParamTypes, RequestContent, RequestData, RequestExtensions, RequestFiles, ResponseContent, ResponseExtensions, SyncByteStream,)from ._urls import URLfrom ._utils import to_bytes_or_str, to_str
__all__ = ["Cookies", "Headers", "Request", "Response"]
SENSITIVE_HEADERS = {"authorization", "proxy-authorization"}
def _is_known_encoding(encoding: str) -> bool: """ Return `True` if `encoding` is a known codec. """ try: codecs.lookup(encoding) except LookupError: return False return True
def _normalize_header_key(key: str | bytes, encoding: str | None = None) -> bytes: """ Coerce str/bytes into a strictly byte-wise HTTP header key. """ return key if isinstance(key, bytes) else key.encode(encoding or "ascii")
def _normalize_header_value(value: str | bytes, encoding: str | None = None) -> bytes: """ Coerce str/bytes into a strictly byte-wise HTTP header value. """ if isinstance(value, bytes): return value if not isinstance(value, str): raise TypeError(f"Header value must be str or bytes, not {type(value)}") return value.encode(encoding or "ascii")
def _parse_content_type_charset(content_type: str) -> str | None: # We used to use `cgi.parse_header()` here, but `cgi` became a dead battery. # See: https://peps.python.org/pep-0594/#cgi msg = email.message.Message() msg["content-type"] = content_type return msg.get_content_charset(failobj=None)
def _parse_header_links(value: str) -> list[dict[str, str]]: """ Returns a list of parsed link headers, for more info see: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link The generic syntax of those is: Link: < uri-reference >; param1=value1; param2="value2" So for instance: Link; '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;' would return [ {"url": "http:/.../front.jpeg", "type": "image/jpeg"}, {"url": "http://.../back.jpeg"}, ] :param value: HTTP Link entity-header field :return: list of parsed link headers """ links: list[dict[str, str]] = [] replace_chars = " '\"" value = value.strip(replace_chars) if not value: return links for val in re.split(", *<", value): try: url, params = val.split(";", 1) except ValueError: url, params = val, "" link = {"url": url.strip("<> '\"")} for param in params.split(";"): try: key, value = param.split("=") except ValueError: break link[key.strip(replace_chars)] = value.strip(replace_chars) links.append(link) return links
def _obfuscate_sensitive_headers( items: typing.Iterable[tuple[typing.AnyStr, typing.AnyStr]],) -> typing.Iterator[tuple[typing.AnyStr, typing.AnyStr]]: for k, v in items: if to_str(k.lower()) in SENSITIVE_HEADERS: v = to_bytes_or_str("[secure]", match_type_of=v) yield k, v
class Headers(typing.MutableMapping[str, str]): """ HTTP headers, as a case-insensitive multi-dict. """
def __init__( self, headers: HeaderTypes | None = None, encoding: str | None = None, ) -> None: self._list = [] # type: typing.List[typing.Tuple[bytes, bytes, bytes]]
if isinstance(headers, Headers): self._list = list(headers._list) elif isinstance(headers, Mapping): for k, v in headers.items(): bytes_key = _normalize_header_key(k, encoding) bytes_value = _normalize_header_value(v, encoding) self._list.append((bytes_key, bytes_key.lower(), bytes_value)) elif headers is not None: for k, v in headers: bytes_key = _normalize_header_key(k, encoding) bytes_value = _normalize_header_value(v, encoding) self._list.append((bytes_key, bytes_key.lower(), bytes_value))
self._encoding = encoding
@property def encoding(self) -> str: """ Header encoding is mandated as ascii, but we allow fallbacks to utf-8 or iso-8859-1. """ if self._encoding is None: for encoding in ["ascii", "utf-8"]: for key, value in self.raw: try: key.decode(encoding) value.decode(encoding) except UnicodeDecodeError: break else: # The else block runs if 'break' did not occur, meaning # all values fitted the encoding. self._encoding = encoding break else: # The ISO-8859-1 encoding covers all 256 code points in a byte, # so will never raise decode errors. self._encoding = "iso-8859-1" return self._encoding
@encoding.setter def encoding(self, value: str) -> None: self._encoding = value
@property def raw(self) -> list[tuple[bytes, bytes]]: """ Returns a list of the raw header items, as byte pairs. """ return [(raw_key, value) for raw_key, _, value in self._list]
def keys(self) -> typing.KeysView[str]: return {key.decode(self.encoding): None for _, key, value in self._list}.keys()
def values(self) -> typing.ValuesView[str]: values_dict: dict[str, str] = {} for _, key, value in self._list: str_key = key.decode(self.encoding) str_value = value.decode(self.encoding) if str_key in values_dict: values_dict[str_key] += f", {str_value}" else: values_dict[str_key] = str_value return values_dict.values()
def items(self) -> typing.ItemsView[str, str]: """ Return `(key, value)` items of headers. Concatenate headers into a single comma separated value when a key occurs multiple times. """ values_dict: dict[str, str] = {} for _, key, value in self._list: str_key = key.decode(self.encoding) str_value = value.decode(self.encoding) if str_key in values_dict: values_dict[str_key] += f", {str_value}" else: values_dict[str_key] = str_value return values_dict.items()
def multi_items(self) -> list[tuple[str, str]]: """ Return a list of `(key, value)` pairs of headers. Allow multiple occurrences of the same key without concatenating into a single comma separated value. """ return [ (key.decode(self.encoding), value.decode(self.encoding)) for _, key, value in self._list ]
def get(self, key: str, default: typing.Any = None) -> typing.Any: """ Return a header value. If multiple occurrences of the header occur then concatenate them together with commas. """ try: return self[key] except KeyError: return default
def get_list(self, key: str, split_commas: bool = False) -> list[str]: """ Return a list of all header values for a given key. If `split_commas=True` is passed, then any comma separated header values are split into multiple return strings. """ get_header_key = key.lower().encode(self.encoding)
values = [ item_value.decode(self.encoding) for _, item_key, item_value in self._list if item_key.lower() == get_header_key ]
if not split_commas: return values
split_values = [] for value in values: split_values.extend([item.strip() for item in value.split(",")]) return split_values
def update(self, headers: HeaderTypes | None = None) -> None: # type: ignore headers = Headers(headers) for key in headers.keys(): if key in self: self.pop(key) self._list.extend(headers._list)
def copy(self) -> Headers: return Headers(self, encoding=self.encoding)
def __getitem__(self, key: str) -> str: """ Return a single header value.
If there are multiple headers with the same key, then we concatenate them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2 """ normalized_key = key.lower().encode(self.encoding)
items = [ header_value.decode(self.encoding) for _, header_key, header_value in self._list if header_key == normalized_key ]
if items: return ", ".join(items)
raise KeyError(key)
def __setitem__(self, key: str, value: str) -> None: """ Set the header `key` to `value`, removing any duplicate entries. Retains insertion order. """ set_key = key.encode(self._encoding or "utf-8") set_value = value.encode(self._encoding or "utf-8") lookup_key = set_key.lower()
found_indexes = [ idx for idx, (_, item_key, _) in enumerate(self._list) if item_key == lookup_key ]
for idx in reversed(found_indexes[1:]): del self._list[idx]
if found_indexes: idx = found_indexes[0] self._list[idx] = (set_key, lookup_key, set_value) else: self._list.append((set_key, lookup_key, set_value))
def __delitem__(self, key: str) -> None: """ Remove the header `key`. """ del_key = key.lower().encode(self.encoding)
pop_indexes = [ idx for idx, (_, item_key, _) in enumerate(self._list) if item_key.lower() == del_key ]
if not pop_indexes: raise KeyError(key)
for idx in reversed(pop_indexes): del self._list[idx]
def __contains__(self, key: typing.Any) -> bool: header_key = key.lower().encode(self.encoding) return header_key in [key for _, key, _ in self._list]
def __iter__(self) -> typing.Iterator[typing.Any]: return iter(self.keys())
def __len__(self) -> int: return len(self._list)
def __eq__(self, other: typing.Any) -> bool: try: other_headers = Headers(other) except ValueError: return False
self_list = [(key, value) for _, key, value in self._list] other_list = [(key, value) for _, key, value in other_headers._list] return sorted(self_list) == sorted(other_list)
def __repr__(self) -> str: class_name = self.__class__.__name__
encoding_str = "" if self.encoding != "ascii": encoding_str = f", encoding={self.encoding!r}"
as_list = list(_obfuscate_sensitive_headers(self.multi_items())) as_dict = dict(as_list)
no_duplicate_keys = len(as_dict) == len(as_list) if no_duplicate_keys: return f"{class_name}({as_dict!r}{encoding_str})" return f"{class_name}({as_list!r}{encoding_str})"
class Request: def __init__( self, method: str, url: URL | str, *, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, content: RequestContent | None = None, data: RequestData | None = None, files: RequestFiles | None = None, json: typing.Any | None = None, stream: SyncByteStream | AsyncByteStream | None = None, extensions: RequestExtensions | None = None, ) -> None: self.method = method.upper() self.url = URL(url) if params is None else URL(url, params=params) self.headers = Headers(headers) self.extensions = {} if extensions is None else dict(extensions)
if cookies: Cookies(cookies).set_cookie_header(self)
if stream is None: content_type: str | None = self.headers.get("content-type") headers, stream = encode_request( content=content, data=data, files=files, json=json, boundary=get_multipart_boundary_from_content_type( content_type=content_type.encode(self.headers.encoding) if content_type else None ), ) self._prepare(headers) self.stream = stream # Load the request body, except for streaming content. if isinstance(stream, ByteStream): self.read() else: # There's an important distinction between `Request(content=...)`, # and `Request(stream=...)`. # # Using `content=...` implies automatically populated `Host` and content # headers, of either `Content-Length: ...` or `Transfer-Encoding: chunked`. # # Using `stream=...` will not automatically include *any* # auto-populated headers. # # As an end-user you don't really need `stream=...`. It's only # useful when: # # * Preserving the request stream when copying requests, eg for redirects. # * Creating request instances on the *server-side* of the transport API. self.stream = stream
def _prepare(self, default_headers: dict[str, str]) -> None: for key, value in default_headers.items(): # Ignore Transfer-Encoding if the Content-Length has been set explicitly. if key.lower() == "transfer-encoding" and "Content-Length" in self.headers: continue self.headers.setdefault(key, value)
auto_headers: list[tuple[bytes, bytes]] = []
has_host = "Host" in self.headers has_content_length = ( "Content-Length" in self.headers or "Transfer-Encoding" in self.headers )
if not has_host and self.url.host: auto_headers.append((b"Host", self.url.netloc)) if not has_content_length and self.method in ("POST", "PUT", "PATCH"): auto_headers.append((b"Content-Length", b"0"))
self.headers = Headers(auto_headers + self.headers.raw)
@property def content(self) -> bytes: if not hasattr(self, "_content"): raise RequestNotRead() return self._content
def read(self) -> bytes: """ Read and return the request content. """ if not hasattr(self, "_content"): assert isinstance(self.stream, typing.Iterable) self._content = b"".join(self.stream) if not isinstance(self.stream, ByteStream): # If a streaming request has been read entirely into memory, then # we can replace the stream with a raw bytes implementation, # to ensure that any non-replayable streams can still be used. self.stream = ByteStream(self._content) return self._content
async def aread(self) -> bytes: """ Read and return the request content. """ if not hasattr(self, "_content"): assert isinstance(self.stream, typing.AsyncIterable) self._content = b"".join([part async for part in self.stream]) if not isinstance(self.stream, ByteStream): # If a streaming request has been read entirely into memory, then # we can replace the stream with a raw bytes implementation, # to ensure that any non-replayable streams can still be used. self.stream = ByteStream(self._content) return self._content
def __repr__(self) -> str: class_name = self.__class__.__name__ url = str(self.url) return f"<{class_name}({self.method!r}, {url!r})>"
def __getstate__(self) -> dict[str, typing.Any]: return { name: value for name, value in self.__dict__.items() if name not in ["extensions", "stream"] }
def __setstate__(self, state: dict[str, typing.Any]) -> None: for name, value in state.items(): setattr(self, name, value) self.extensions = {} self.stream = UnattachedStream()
class Response: def __init__( self, status_code: int, *, headers: HeaderTypes | None = None, content: ResponseContent | None = None, text: str | None = None, html: str | None = None, json: typing.Any = None, stream: SyncByteStream | AsyncByteStream | None = None, request: Request | None = None, extensions: ResponseExtensions | None = None, history: list[Response] | None = None, default_encoding: str | typing.Callable[[bytes], str] = "utf-8", ) -> None: self.status_code = status_code self.headers = Headers(headers)
self._request: Request | None = request
# When follow_redirects=False and a redirect is received, # the client will set `response.next_request`. self.next_request: Request | None = None
self.extensions = {} if extensions is None else dict(extensions) self.history = [] if history is None else list(history)
self.is_closed = False self.is_stream_consumed = False
self.default_encoding = default_encoding
if stream is None: headers, stream = encode_response(content, text, html, json) self._prepare(headers) self.stream = stream if isinstance(stream, ByteStream): # Load the response body, except for streaming content. self.read() else: # There's an important distinction between `Response(content=...)`, # and `Response(stream=...)`. # # Using `content=...` implies automatically populated content headers, # of either `Content-Length: ...` or `Transfer-Encoding: chunked`. # # Using `stream=...` will not automatically include any content headers. # # As an end-user you don't really need `stream=...`. It's only # useful when creating response instances having received a stream # from the transport API. self.stream = stream
self._num_bytes_downloaded = 0
def _prepare(self, default_headers: dict[str, str]) -> None: for key, value in default_headers.items(): # Ignore Transfer-Encoding if the Content-Length has been set explicitly. if key.lower() == "transfer-encoding" and "content-length" in self.headers: continue self.headers.setdefault(key, value)
@property def elapsed(self) -> datetime.timedelta: """ Returns the time taken for the complete request/response cycle to complete. """ if not hasattr(self, "_elapsed"): raise RuntimeError( "'.elapsed' may only be accessed after the response " "has been read or closed." ) return self._elapsed
@elapsed.setter def elapsed(self, elapsed: datetime.timedelta) -> None: self._elapsed = elapsed
@property def request(self) -> Request: """ Returns the request instance associated to the current response. """ if self._request is None: raise RuntimeError( "The request instance has not been set on this response." ) return self._request
@request.setter def request(self, value: Request) -> None: self._request = value
@property def http_version(self) -> str: try: http_version: bytes = self.extensions["http_version"] except KeyError: return "HTTP/1.1" else: return http_version.decode("ascii", errors="ignore")
@property def reason_phrase(self) -> str: try: reason_phrase: bytes = self.extensions["reason_phrase"] except KeyError: return codes.get_reason_phrase(self.status_code) else: return reason_phrase.decode("ascii", errors="ignore")
@property def url(self) -> URL: """ Returns the URL for which the request was made. """ return self.request.url
@property def content(self) -> bytes: if not hasattr(self, "_content"): raise ResponseNotRead() return self._content
@property def text(self) -> str: if not hasattr(self, "_text"): content = self.content if not content: self._text = "" else: decoder = TextDecoder(encoding=self.encoding or "utf-8") self._text = "".join([decoder.decode(self.content), decoder.flush()]) return self._text
@property def encoding(self) -> str | None: """ Return an encoding to use for decoding the byte content into text. The priority for determining this is given by...
* `.encoding = <>` has been set explicitly. * The encoding as specified by the charset parameter in the Content-Type header. * The encoding as determined by `default_encoding`, which may either be a string like "utf-8" indicating the encoding to use, or may be a callable which enables charset autodetection. """ if not hasattr(self, "_encoding"): encoding = self.charset_encoding if encoding is None or not _is_known_encoding(encoding): if isinstance(self.default_encoding, str): encoding = self.default_encoding elif hasattr(self, "_content"): encoding = self.default_encoding(self._content) self._encoding = encoding or "utf-8" return self._encoding
@encoding.setter def encoding(self, value: str) -> None: """ Set the encoding to use for decoding the byte content into text.
If the `text` attribute has been accessed, attempting to set the encoding will throw a ValueError. """ if hasattr(self, "_text"): raise ValueError( "Setting encoding after `text` has been accessed is not allowed." ) self._encoding = value
@property def charset_encoding(self) -> str | None: """ Return the encoding, as specified by the Content-Type header. """ content_type = self.headers.get("Content-Type") if content_type is None: return None
return _parse_content_type_charset(content_type)
def _get_content_decoder(self) -> ContentDecoder: """ Returns a decoder instance which can be used to decode the raw byte content, depending on the Content-Encoding used in the response. """ if not hasattr(self, "_decoder"): decoders: list[ContentDecoder] = [] values = self.headers.get_list("content-encoding", split_commas=True) for value in values: value = value.strip().lower() try: decoder_cls = SUPPORTED_DECODERS[value] decoders.append(decoder_cls()) except KeyError: continue
if len(decoders) == 1: self._decoder = decoders[0] elif len(decoders) > 1: self._decoder = MultiDecoder(children=decoders) else: self._decoder = IdentityDecoder()
return self._decoder
@property def is_informational(self) -> bool: """ A property which is `True` for 1xx status codes, `False` otherwise. """ return codes.is_informational(self.status_code)
@property def is_success(self) -> bool: """ A property which is `True` for 2xx status codes, `False` otherwise. """ return codes.is_success(self.status_code)
@property def is_redirect(self) -> bool: """ A property which is `True` for 3xx status codes, `False` otherwise.
Note that not all responses with a 3xx status code indicate a URL redirect.
Use `response.has_redirect_location` to determine responses with a properly formed URL redirection. """ return codes.is_redirect(self.status_code)
@property def is_client_error(self) -> bool: """ A property which is `True` for 4xx status codes, `False` otherwise. """ return codes.is_client_error(self.status_code)
@property def is_server_error(self) -> bool: """ A property which is `True` for 5xx status codes, `False` otherwise. """ return codes.is_server_error(self.status_code)
@property def is_error(self) -> bool: """ A property which is `True` for 4xx and 5xx status codes, `False` otherwise. """ return codes.is_error(self.status_code)
@property def has_redirect_location(self) -> bool: """ Returns True for 3xx responses with a properly formed URL redirection, `False` otherwise. """ return ( self.status_code in ( # 301 (Cacheable redirect. Method may change to GET.) codes.MOVED_PERMANENTLY, # 302 (Uncacheable redirect. Method may change to GET.) codes.FOUND, # 303 (Client should make a GET or HEAD request.) codes.SEE_OTHER, # 307 (Equiv. 302, but retain method) codes.TEMPORARY_REDIRECT, # 308 (Equiv. 301, but retain method) codes.PERMANENT_REDIRECT, ) and "Location" in self.headers )
def raise_for_status(self) -> Response: """ Raise the `HTTPStatusError` if one occurred. """ request = self._request if request is None: raise RuntimeError( "Cannot call `raise_for_status` as the request " "instance has not been set on this response." )
if self.is_success: return self
if self.has_redirect_location: message = ( "{error_type} '{0.status_code} {0.reason_phrase}' for url '{0.url}'\n" "Redirect location: '{0.headers[location]}'\n" "For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/{0.status_code}" ) else: message = ( "{error_type} '{0.status_code} {0.reason_phrase}' for url '{0.url}'\n" "For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/{0.status_code}" )
status_class = self.status_code // 100 error_types = { 1: "Informational response", 3: "Redirect response", 4: "Client error", 5: "Server error", } error_type = error_types.get(status_class, "Invalid status code") message = message.format(self, error_type=error_type) raise HTTPStatusError(message, request=request, response=self)
def json(self, **kwargs: typing.Any) -> typing.Any: return jsonlib.loads(self.content, **kwargs)
@property def cookies(self) -> Cookies: if not hasattr(self, "_cookies"): self._cookies = Cookies() self._cookies.extract_cookies(self) return self._cookies
@property def links(self) -> dict[str | None, dict[str, str]]: """ Returns the parsed header links of the response, if any """ header = self.headers.get("link") if header is None: return {}
return { (link.get("rel") or link.get("url")): link for link in _parse_header_links(header) }
@property def num_bytes_downloaded(self) -> int: return self._num_bytes_downloaded
def __repr__(self) -> str: return f"<Response [{self.status_code} {self.reason_phrase}]>"
def __getstate__(self) -> dict[str, typing.Any]: return { name: value for name, value in self.__dict__.items() if name not in ["extensions", "stream", "is_closed", "_decoder"] }
def __setstate__(self, state: dict[str, typing.Any]) -> None: for name, value in state.items(): setattr(self, name, value) self.is_closed = True self.extensions = {} self.stream = UnattachedStream()
def read(self) -> bytes: """ Read and return the response content. """ if not hasattr(self, "_content"): self._content = b"".join(self.iter_bytes()) return self._content
def iter_bytes(self, chunk_size: int | None = None) -> typing.Iterator[bytes]: """ A byte-iterator over the decoded response content. This allows us to handle gzip, deflate, brotli, and zstd encoded responses. """ if hasattr(self, "_content"): chunk_size = len(self._content) if chunk_size is None else chunk_size for i in range(0, len(self._content), max(chunk_size, 1)): yield self._content[i : i + chunk_size] else: decoder = self._get_content_decoder() chunker = ByteChunker(chunk_size=chunk_size) with request_context(request=self._request): for raw_bytes in self.iter_raw(): decoded = decoder.decode(raw_bytes) for chunk in chunker.decode(decoded): yield chunk decoded = decoder.flush() for chunk in chunker.decode(decoded): yield chunk # pragma: no cover for chunk in chunker.flush(): yield chunk
def iter_text(self, chunk_size: int | None = None) -> typing.Iterator[str]: """ A str-iterator over the decoded response content that handles both gzip, deflate, etc but also detects the content's string encoding. """ decoder = TextDecoder(encoding=self.encoding or "utf-8") chunker = TextChunker(chunk_size=chunk_size) with request_context(request=self._request): for byte_content in self.iter_bytes(): text_content = decoder.decode(byte_content) for chunk in chunker.decode(text_content): yield chunk text_content = decoder.flush() for chunk in chunker.decode(text_content): yield chunk # pragma: no cover for chunk in chunker.flush(): yield chunk
def iter_lines(self) -> typing.Iterator[str]: decoder = LineDecoder() with request_context(request=self._request): for text in self.iter_text(): for line in decoder.decode(text): yield line for line in decoder.flush(): yield line
def iter_raw(self, chunk_size: int | None = None) -> typing.Iterator[bytes]: """ A byte-iterator over the raw response content. """ if self.is_stream_consumed: raise StreamConsumed() if self.is_closed: raise StreamClosed() if not isinstance(self.stream, SyncByteStream): raise RuntimeError("Attempted to call a sync iterator on an async stream.")
self.is_stream_consumed = True self._num_bytes_downloaded = 0 chunker = ByteChunker(chunk_size=chunk_size)
with request_context(request=self._request): for raw_stream_bytes in self.stream: self._num_bytes_downloaded += len(raw_stream_bytes) for chunk in chunker.decode(raw_stream_bytes): yield chunk
for chunk in chunker.flush(): yield chunk
self.close()
def close(self) -> None: """ Close the response and release the connection. Automatically called if the response body is read to completion. """ if not isinstance(self.stream, SyncByteStream): raise RuntimeError("Attempted to call an sync close on an async stream.")
if not self.is_closed: self.is_closed = True with request_context(request=self._request): self.stream.close()
async def aread(self) -> bytes: """ Read and return the response content. """ if not hasattr(self, "_content"): self._content = b"".join([part async for part in self.aiter_bytes()]) return self._content
async def aiter_bytes( self, chunk_size: int | None = None ) -> typing.AsyncIterator[bytes]: """ A byte-iterator over the decoded response content. This allows us to handle gzip, deflate, brotli, and zstd encoded responses. """ if hasattr(self, "_content"): chunk_size = len(self._content) if chunk_size is None else chunk_size for i in range(0, len(self._content), max(chunk_size, 1)): yield self._content[i : i + chunk_size] else: decoder = self._get_content_decoder() chunker = ByteChunker(chunk_size=chunk_size) with request_context(request=self._request): async for raw_bytes in self.aiter_raw(): decoded = decoder.decode(raw_bytes) for chunk in chunker.decode(decoded): yield chunk decoded = decoder.flush() for chunk in chunker.decode(decoded): yield chunk # pragma: no cover for chunk in chunker.flush(): yield chunk
async def aiter_text( self, chunk_size: int | None = None ) -> typing.AsyncIterator[str]: """ A str-iterator over the decoded response content that handles both gzip, deflate, etc but also detects the content's string encoding. """ decoder = TextDecoder(encoding=self.encoding or "utf-8") chunker = TextChunker(chunk_size=chunk_size) with request_context(request=self._request): async for byte_content in self.aiter_bytes(): text_content = decoder.decode(byte_content) for chunk in chunker.decode(text_content): yield chunk text_content = decoder.flush() for chunk in chunker.decode(text_content): yield chunk # pragma: no cover for chunk in chunker.flush(): yield chunk
async def aiter_lines(self) -> typing.AsyncIterator[str]: decoder = LineDecoder() with request_context(request=self._request): async for text in self.aiter_text(): for line in decoder.decode(text): yield line for line in decoder.flush(): yield line
async def aiter_raw( self, chunk_size: int | None = None ) -> typing.AsyncIterator[bytes]: """ A byte-iterator over the raw response content. """ if self.is_stream_consumed: raise StreamConsumed() if self.is_closed: raise StreamClosed() if not isinstance(self.stream, AsyncByteStream): raise RuntimeError("Attempted to call an async iterator on an sync stream.")
self.is_stream_consumed = True self._num_bytes_downloaded = 0 chunker = ByteChunker(chunk_size=chunk_size)
with request_context(request=self._request): async for raw_stream_bytes in self.stream: self._num_bytes_downloaded += len(raw_stream_bytes) for chunk in chunker.decode(raw_stream_bytes): yield chunk
for chunk in chunker.flush(): yield chunk
await self.aclose()
async def aclose(self) -> None: """ Close the response and release the connection. Automatically called if the response body is read to completion. """ if not isinstance(self.stream, AsyncByteStream): raise RuntimeError("Attempted to call an async close on an sync stream.")
if not self.is_closed: self.is_closed = True with request_context(request=self._request): await self.stream.aclose()
class Cookies(typing.MutableMapping[str, str]): """ HTTP Cookies, as a mutable mapping. """
def __init__(self, cookies: CookieTypes | None = None) -> None: if cookies is None or isinstance(cookies, dict): self.jar = CookieJar() if isinstance(cookies, dict): for key, value in cookies.items(): self.set(key, value) elif isinstance(cookies, list): self.jar = CookieJar() for key, value in cookies: self.set(key, value) elif isinstance(cookies, Cookies): self.jar = CookieJar() for cookie in cookies.jar: self.jar.set_cookie(cookie) else: self.jar = cookies
def extract_cookies(self, response: Response) -> None: """ Loads any cookies based on the response `Set-Cookie` headers. """ urllib_response = self._CookieCompatResponse(response) urllib_request = self._CookieCompatRequest(response.request)
self.jar.extract_cookies(urllib_response, urllib_request) # type: ignore
def set_cookie_header(self, request: Request) -> None: """ Sets an appropriate 'Cookie:' HTTP header on the `Request`. """ urllib_request = self._CookieCompatRequest(request) self.jar.add_cookie_header(urllib_request)
def set(self, name: str, value: str, domain: str = "", path: str = "/") -> None: """ Set a cookie value by name. May optionally include domain and path. """ kwargs = { "version": 0, "name": name, "value": value, "port": None, "port_specified": False, "domain": domain, "domain_specified": bool(domain), "domain_initial_dot": domain.startswith("."), "path": path, "path_specified": bool(path), "secure": False, "expires": None, "discard": True, "comment": None, "comment_url": None, "rest": {"HttpOnly": None}, "rfc2109": False, } cookie = Cookie(**kwargs) # type: ignore self.jar.set_cookie(cookie)
def get( # type: ignore self, name: str, default: str | None = None, domain: str | None = None, path: str | None = None, ) -> str | None: """ Get a cookie by name. May optionally include domain and path in order to specify exactly which cookie to retrieve. """ value = None for cookie in self.jar: if cookie.name == name: if domain is None or cookie.domain == domain: if path is None or cookie.path == path: if value is not None: message = f"Multiple cookies exist with name={name}" raise CookieConflict(message) value = cookie.value
if value is None: return default return value
def delete( self, name: str, domain: str | None = None, path: str | None = None, ) -> None: """ Delete a cookie by name. May optionally include domain and path in order to specify exactly which cookie to delete. """ if domain is not None and path is not None: return self.jar.clear(domain, path, name)
remove = [ cookie for cookie in self.jar if cookie.name == name and (domain is None or cookie.domain == domain) and (path is None or cookie.path == path) ]
for cookie in remove: self.jar.clear(cookie.domain, cookie.path, cookie.name)
def clear(self, domain: str | None = None, path: str | None = None) -> None: """ Delete all cookies. Optionally include a domain and path in order to only delete a subset of all the cookies. """ args = [] if domain is not None: args.append(domain) if path is not None: assert domain is not None args.append(path) self.jar.clear(*args)
def update(self, cookies: CookieTypes | None = None) -> None: # type: ignore cookies = Cookies(cookies) for cookie in cookies.jar: self.jar.set_cookie(cookie)
def __setitem__(self, name: str, value: str) -> None: return self.set(name, value)
def __getitem__(self, name: str) -> str: value = self.get(name) if value is None: raise KeyError(name) return value
def __delitem__(self, name: str) -> None: return self.delete(name)
def __len__(self) -> int: return len(self.jar)
def __iter__(self) -> typing.Iterator[str]: return (cookie.name for cookie in self.jar)
def __bool__(self) -> bool: for _ in self.jar: return True return False
def __repr__(self) -> str: cookies_repr = ", ".join( [ f"<Cookie {cookie.name}={cookie.value} for {cookie.domain} />" for cookie in self.jar ] )
return f"<Cookies[{cookies_repr}]>"
class _CookieCompatRequest(urllib.request.Request): """ Wraps a `Request` instance up in a compatibility interface suitable for use with `CookieJar` operations. """
def __init__(self, request: Request) -> None: super().__init__( url=str(request.url), headers=dict(request.headers), method=request.method, ) self.request = request
def add_unredirected_header(self, key: str, value: str) -> None: super().add_unredirected_header(key, value) self.request.headers[key] = value
class _CookieCompatResponse: """ Wraps a `Request` instance up in a compatibility interface suitable for use with `CookieJar` operations. """
def __init__(self, response: Response) -> None: self.response = response
def info(self) -> email.message.Message: info = email.message.Message() for key, value in self.response.headers.multi_items(): # Note that setting `info[key]` here is an "append" operation, # not a "replace" operation. # https://docs.python.org/3/library/email.compat32-message.html#email.message.Message.__setitem__ info[key] = value return info123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300from __future__ import annotations
import ioimport mimetypesimport osimport reimport typingfrom pathlib import Path
from ._types import ( AsyncByteStream, FileContent, FileTypes, RequestData, RequestFiles, SyncByteStream,)from ._utils import ( peek_filelike_length, primitive_value_to_str, to_bytes,)
_HTML5_FORM_ENCODING_REPLACEMENTS = {'"': "%22", "\\": "\\\\"}_HTML5_FORM_ENCODING_REPLACEMENTS.update( {chr(c): "%{:02X}".format(c) for c in range(0x1F + 1) if c != 0x1B})_HTML5_FORM_ENCODING_RE = re.compile( r"|".join([re.escape(c) for c in _HTML5_FORM_ENCODING_REPLACEMENTS.keys()]))
def _format_form_param(name: str, value: str) -> bytes: """ Encode a name/value pair within a multipart form. """
def replacer(match: typing.Match[str]) -> str: return _HTML5_FORM_ENCODING_REPLACEMENTS[match.group(0)]
value = _HTML5_FORM_ENCODING_RE.sub(replacer, value) return f'{name}="{value}"'.encode()
def _guess_content_type(filename: str | None) -> str | None: """ Guesses the mimetype based on a filename. Defaults to `application/octet-stream`.
Returns `None` if `filename` is `None` or empty. """ if filename: return mimetypes.guess_type(filename)[0] or "application/octet-stream" return None
def get_multipart_boundary_from_content_type( content_type: bytes | None,) -> bytes | None: if not content_type or not content_type.startswith(b"multipart/form-data"): return None # parse boundary according to # https://www.rfc-editor.org/rfc/rfc2046#section-5.1.1 if b";" in content_type: for section in content_type.split(b";"): if section.strip().lower().startswith(b"boundary="): return section.strip()[len(b"boundary=") :].strip(b'"') return None
class DataField: """ A single form field item, within a multipart form field. """
def __init__(self, name: str, value: str | bytes | int | float | None) -> None: if not isinstance(name, str): raise TypeError( f"Invalid type for name. Expected str, got {type(name)}: {name!r}" ) if value is not None and not isinstance(value, (str, bytes, int, float)): raise TypeError( "Invalid type for value. Expected primitive type," f" got {type(value)}: {value!r}" ) self.name = name self.value: str | bytes = ( value if isinstance(value, bytes) else primitive_value_to_str(value) )
def render_headers(self) -> bytes: if not hasattr(self, "_headers"): name = _format_form_param("name", self.name) self._headers = b"".join( [b"Content-Disposition: form-data; ", name, b"\r\n\r\n"] )
return self._headers
def render_data(self) -> bytes: if not hasattr(self, "_data"): self._data = to_bytes(self.value)
return self._data
def get_length(self) -> int: headers = self.render_headers() data = self.render_data() return len(headers) + len(data)
def render(self) -> typing.Iterator[bytes]: yield self.render_headers() yield self.render_data()
class FileField: """ A single file field item, within a multipart form field. """
CHUNK_SIZE = 64 * 1024
def __init__(self, name: str, value: FileTypes) -> None: self.name = name
fileobj: FileContent
headers: dict[str, str] = {} content_type: str | None = None
# This large tuple based API largely mirror's requests' API # It would be good to think of better APIs for this that we could # include in httpx 2.0 since variable length tuples(especially of 4 elements) # are quite unwieldly if isinstance(value, tuple): if len(value) == 2: # neither the 3rd parameter (content_type) nor the 4th (headers) # was included filename, fileobj = value elif len(value) == 3: filename, fileobj, content_type = value else: # all 4 parameters included filename, fileobj, content_type, headers = value # type: ignore else: filename = Path(str(getattr(value, "name", "upload"))).name fileobj = value
if content_type is None: content_type = _guess_content_type(filename)
has_content_type_header = any("content-type" in key.lower() for key in headers) if content_type is not None and not has_content_type_header: # note that unlike requests, we ignore the content_type provided in the 3rd # tuple element if it is also included in the headers requests does # the opposite (it overwrites the headerwith the 3rd tuple element) headers["Content-Type"] = content_type
if isinstance(fileobj, io.StringIO): raise TypeError( "Multipart file uploads require 'io.BytesIO', not 'io.StringIO'." ) if isinstance(fileobj, io.TextIOBase): raise TypeError( "Multipart file uploads must be opened in binary mode, not text mode." )
self.filename = filename self.file = fileobj self.headers = headers
def get_length(self) -> int | None: headers = self.render_headers()
if isinstance(self.file, (str, bytes)): return len(headers) + len(to_bytes(self.file))
file_length = peek_filelike_length(self.file)
# If we can't determine the filesize without reading it into memory, # then return `None` here, to indicate an unknown file length. if file_length is None: return None
return len(headers) + file_length
def render_headers(self) -> bytes: if not hasattr(self, "_headers"): parts = [ b"Content-Disposition: form-data; ", _format_form_param("name", self.name), ] if self.filename: filename = _format_form_param("filename", self.filename) parts.extend([b"; ", filename]) for header_name, header_value in self.headers.items(): key, val = f"\r\n{header_name}: ".encode(), header_value.encode() parts.extend([key, val]) parts.append(b"\r\n\r\n") self._headers = b"".join(parts)
return self._headers
def render_data(self) -> typing.Iterator[bytes]: if isinstance(self.file, (str, bytes)): yield to_bytes(self.file) return
if hasattr(self.file, "seek"): try: self.file.seek(0) except io.UnsupportedOperation: pass
chunk = self.file.read(self.CHUNK_SIZE) while chunk: yield to_bytes(chunk) chunk = self.file.read(self.CHUNK_SIZE)
def render(self) -> typing.Iterator[bytes]: yield self.render_headers() yield from self.render_data()
class MultipartStream(SyncByteStream, AsyncByteStream): """ Request content as streaming multipart encoded form data. """
def __init__( self, data: RequestData, files: RequestFiles, boundary: bytes | None = None, ) -> None: if boundary is None: boundary = os.urandom(16).hex().encode("ascii")
self.boundary = boundary self.content_type = "multipart/form-data; boundary=%s" % boundary.decode( "ascii" ) self.fields = list(self._iter_fields(data, files))
def _iter_fields( self, data: RequestData, files: RequestFiles ) -> typing.Iterator[FileField | DataField]: for name, value in data.items(): if isinstance(value, (tuple, list)): for item in value: yield DataField(name=name, value=item) else: yield DataField(name=name, value=value)
file_items = files.items() if isinstance(files, typing.Mapping) else files for name, value in file_items: yield FileField(name=name, value=value)
def iter_chunks(self) -> typing.Iterator[bytes]: for field in self.fields: yield b"--%s\r\n" % self.boundary yield from field.render() yield b"\r\n" yield b"--%s--\r\n" % self.boundary
def get_content_length(self) -> int | None: """ Return the length of the multipart encoded content, or `None` if any of the files have a length that cannot be determined upfront. """ boundary_length = len(self.boundary) length = 0
for field in self.fields: field_length = field.get_length() if field_length is None: return None
length += 2 + boundary_length + 2 # b"--{boundary}\r\n" length += field_length length += 2 # b"\r\n"
length += 2 + boundary_length + 4 # b"--{boundary}--\r\n" return length
# Content stream interface.
def get_headers(self) -> dict[str, str]: content_length = self.get_content_length() content_type = self.content_type if content_length is None: return {"Transfer-Encoding": "chunked", "Content-Type": content_type} return {"Content-Length": str(content_length), "Content-Type": content_type}
def __iter__(self) -> typing.Iterator[bytes]: for chunk in self.iter_chunks(): yield chunk
async def __aiter__(self) -> typing.AsyncIterator[bytes]: for chunk in self.iter_chunks(): yield chunk123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162from __future__ import annotations
from enum import IntEnum
__all__ = ["codes"]
class codes(IntEnum): """HTTP status codes and reason phrases
Status codes from the following RFCs are all observed:
* RFC 7231: Hypertext Transfer Protocol (HTTP/1.1), obsoletes 2616 * RFC 6585: Additional HTTP Status Codes * RFC 3229: Delta encoding in HTTP * RFC 4918: HTTP Extensions for WebDAV, obsoletes 2518 * RFC 5842: Binding Extensions to WebDAV * RFC 7238: Permanent Redirect * RFC 2295: Transparent Content Negotiation in HTTP * RFC 2774: An HTTP Extension Framework * RFC 7540: Hypertext Transfer Protocol Version 2 (HTTP/2) * RFC 2324: Hyper Text Coffee Pot Control Protocol (HTCPCP/1.0) * RFC 7725: An HTTP Status Code to Report Legal Obstacles * RFC 8297: An HTTP Status Code for Indicating Hints * RFC 8470: Using Early Data in HTTP """
def __new__(cls, value: int, phrase: str = "") -> codes: obj = int.__new__(cls, value) obj._value_ = value
obj.phrase = phrase # type: ignore[attr-defined] return obj
def __str__(self) -> str: return str(self.value)
@classmethod def get_reason_phrase(cls, value: int) -> str: try: return codes(value).phrase # type: ignore except ValueError: return ""
@classmethod def is_informational(cls, value: int) -> bool: """ Returns `True` for 1xx status codes, `False` otherwise. """ return 100 <= value <= 199
@classmethod def is_success(cls, value: int) -> bool: """ Returns `True` for 2xx status codes, `False` otherwise. """ return 200 <= value <= 299
@classmethod def is_redirect(cls, value: int) -> bool: """ Returns `True` for 3xx status codes, `False` otherwise. """ return 300 <= value <= 399
@classmethod def is_client_error(cls, value: int) -> bool: """ Returns `True` for 4xx status codes, `False` otherwise. """ return 400 <= value <= 499
@classmethod def is_server_error(cls, value: int) -> bool: """ Returns `True` for 5xx status codes, `False` otherwise. """ return 500 <= value <= 599
@classmethod def is_error(cls, value: int) -> bool: """ Returns `True` for 4xx or 5xx status codes, `False` otherwise. """ return 400 <= value <= 599
# informational CONTINUE = 100, "Continue" SWITCHING_PROTOCOLS = 101, "Switching Protocols" PROCESSING = 102, "Processing" EARLY_HINTS = 103, "Early Hints"
# success OK = 200, "OK" CREATED = 201, "Created" ACCEPTED = 202, "Accepted" NON_AUTHORITATIVE_INFORMATION = 203, "Non-Authoritative Information" NO_CONTENT = 204, "No Content" RESET_CONTENT = 205, "Reset Content" PARTIAL_CONTENT = 206, "Partial Content" MULTI_STATUS = 207, "Multi-Status" ALREADY_REPORTED = 208, "Already Reported" IM_USED = 226, "IM Used"
# redirection MULTIPLE_CHOICES = 300, "Multiple Choices" MOVED_PERMANENTLY = 301, "Moved Permanently" FOUND = 302, "Found" SEE_OTHER = 303, "See Other" NOT_MODIFIED = 304, "Not Modified" USE_PROXY = 305, "Use Proxy" TEMPORARY_REDIRECT = 307, "Temporary Redirect" PERMANENT_REDIRECT = 308, "Permanent Redirect"
# client error BAD_REQUEST = 400, "Bad Request" UNAUTHORIZED = 401, "Unauthorized" PAYMENT_REQUIRED = 402, "Payment Required" FORBIDDEN = 403, "Forbidden" NOT_FOUND = 404, "Not Found" METHOD_NOT_ALLOWED = 405, "Method Not Allowed" NOT_ACCEPTABLE = 406, "Not Acceptable" PROXY_AUTHENTICATION_REQUIRED = 407, "Proxy Authentication Required" REQUEST_TIMEOUT = 408, "Request Timeout" CONFLICT = 409, "Conflict" GONE = 410, "Gone" LENGTH_REQUIRED = 411, "Length Required" PRECONDITION_FAILED = 412, "Precondition Failed" REQUEST_ENTITY_TOO_LARGE = 413, "Request Entity Too Large" REQUEST_URI_TOO_LONG = 414, "Request-URI Too Long" UNSUPPORTED_MEDIA_TYPE = 415, "Unsupported Media Type" REQUESTED_RANGE_NOT_SATISFIABLE = 416, "Requested Range Not Satisfiable" EXPECTATION_FAILED = 417, "Expectation Failed" IM_A_TEAPOT = 418, "I'm a teapot" MISDIRECTED_REQUEST = 421, "Misdirected Request" UNPROCESSABLE_ENTITY = 422, "Unprocessable Entity" LOCKED = 423, "Locked" FAILED_DEPENDENCY = 424, "Failed Dependency" TOO_EARLY = 425, "Too Early" UPGRADE_REQUIRED = 426, "Upgrade Required" PRECONDITION_REQUIRED = 428, "Precondition Required" TOO_MANY_REQUESTS = 429, "Too Many Requests" REQUEST_HEADER_FIELDS_TOO_LARGE = 431, "Request Header Fields Too Large" UNAVAILABLE_FOR_LEGAL_REASONS = 451, "Unavailable For Legal Reasons"
# server errors INTERNAL_SERVER_ERROR = 500, "Internal Server Error" NOT_IMPLEMENTED = 501, "Not Implemented" BAD_GATEWAY = 502, "Bad Gateway" SERVICE_UNAVAILABLE = 503, "Service Unavailable" GATEWAY_TIMEOUT = 504, "Gateway Timeout" HTTP_VERSION_NOT_SUPPORTED = 505, "HTTP Version Not Supported" VARIANT_ALSO_NEGOTIATES = 506, "Variant Also Negotiates" INSUFFICIENT_STORAGE = 507, "Insufficient Storage" LOOP_DETECTED = 508, "Loop Detected" NOT_EXTENDED = 510, "Not Extended" NETWORK_AUTHENTICATION_REQUIRED = 511, "Network Authentication Required"
# Include lower-case styles for `requests` compatibility.for code in codes: setattr(codes, code._name_.lower(), int(code))123456789101112131415from .asgi import *from .base import *from .default import *from .mock import *from .wsgi import *
__all__ = [ "ASGITransport", "AsyncBaseTransport", "BaseTransport", "AsyncHTTPTransport", "HTTPTransport", "MockTransport", "WSGITransport",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187from __future__ import annotations
import typing
from .._models import Request, Responsefrom .._types import AsyncByteStreamfrom .base import AsyncBaseTransport
if typing.TYPE_CHECKING: # pragma: no cover import asyncio
import trio
Event = typing.Union[asyncio.Event, trio.Event]
_Message = typing.MutableMapping[str, typing.Any]_Receive = typing.Callable[[], typing.Awaitable[_Message]]_Send = typing.Callable[ [typing.MutableMapping[str, typing.Any]], typing.Awaitable[None]]_ASGIApp = typing.Callable[ [typing.MutableMapping[str, typing.Any], _Receive, _Send], typing.Awaitable[None]]
__all__ = ["ASGITransport"]
def is_running_trio() -> bool: try: # sniffio is a dependency of trio.
# See https://github.com/python-trio/trio/issues/2802 import sniffio
if sniffio.current_async_library() == "trio": return True except ImportError: # pragma: nocover pass
return False
def create_event() -> Event: if is_running_trio(): import trio
return trio.Event()
import asyncio
return asyncio.Event()
class ASGIResponseStream(AsyncByteStream): def __init__(self, body: list[bytes]) -> None: self._body = body
async def __aiter__(self) -> typing.AsyncIterator[bytes]: yield b"".join(self._body)
class ASGITransport(AsyncBaseTransport): """ A custom AsyncTransport that handles sending requests directly to an ASGI app.
```python transport = httpx.ASGITransport( app=app, root_path="/submount", client=("1.2.3.4", 123) ) client = httpx.AsyncClient(transport=transport) ```
Arguments:
* `app` - The ASGI application. * `raise_app_exceptions` - Boolean indicating if exceptions in the application should be raised. Default to `True`. Can be set to `False` for use cases such as testing the content of a client 500 response. * `root_path` - The root path on which the ASGI application should be mounted. * `client` - A two-tuple indicating the client IP and port of incoming requests. ``` """
def __init__( self, app: _ASGIApp, raise_app_exceptions: bool = True, root_path: str = "", client: tuple[str, int] = ("127.0.0.1", 123), ) -> None: self.app = app self.raise_app_exceptions = raise_app_exceptions self.root_path = root_path self.client = client
async def handle_async_request( self, request: Request, ) -> Response: assert isinstance(request.stream, AsyncByteStream)
# ASGI scope. scope = { "type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": request.method, "headers": [(k.lower(), v) for (k, v) in request.headers.raw], "scheme": request.url.scheme, "path": request.url.path, "raw_path": request.url.raw_path.split(b"?")[0], "query_string": request.url.query, "server": (request.url.host, request.url.port), "client": self.client, "root_path": self.root_path, }
# Request. request_body_chunks = request.stream.__aiter__() request_complete = False
# Response. status_code = None response_headers = None body_parts = [] response_started = False response_complete = create_event()
# ASGI callables.
async def receive() -> dict[str, typing.Any]: nonlocal request_complete
if request_complete: await response_complete.wait() return {"type": "http.disconnect"}
try: body = await request_body_chunks.__anext__() except StopAsyncIteration: request_complete = True return {"type": "http.request", "body": b"", "more_body": False} return {"type": "http.request", "body": body, "more_body": True}
async def send(message: typing.MutableMapping[str, typing.Any]) -> None: nonlocal status_code, response_headers, response_started
if message["type"] == "http.response.start": assert not response_started
status_code = message["status"] response_headers = message.get("headers", []) response_started = True
elif message["type"] == "http.response.body": assert not response_complete.is_set() body = message.get("body", b"") more_body = message.get("more_body", False)
if body and request.method != "HEAD": body_parts.append(body)
if not more_body: response_complete.set()
try: await self.app(scope, receive, send) except Exception: # noqa: PIE-786 if self.raise_app_exceptions: raise
response_complete.set() if status_code is None: status_code = 500 if response_headers is None: response_headers = {}
assert response_complete.is_set() assert status_code is not None assert response_headers is not None
stream = ASGIResponseStream(body_parts)
return Response(status_code, headers=response_headers, stream=stream)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586from __future__ import annotations
import typingfrom types import TracebackType
from .._models import Request, Response
T = typing.TypeVar("T", bound="BaseTransport")A = typing.TypeVar("A", bound="AsyncBaseTransport")
__all__ = ["AsyncBaseTransport", "BaseTransport"]
class BaseTransport: def __enter__(self: T) -> T: return self
def __exit__( self, exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, traceback: TracebackType | None = None, ) -> None: self.close()
def handle_request(self, request: Request) -> Response: """ Send a single HTTP request and return a response.
Developers shouldn't typically ever need to call into this API directly, since the Client class provides all the higher level user-facing API niceties.
In order to properly release any network resources, the response stream should *either* be consumed immediately, with a call to `response.stream.read()`, or else the `handle_request` call should be followed with a try/finally block to ensuring the stream is always closed.
Example usage:
with httpx.HTTPTransport() as transport: req = httpx.Request( method=b"GET", url=(b"https", b"www.example.com", 443, b"/"), headers=[(b"Host", b"www.example.com")], ) resp = transport.handle_request(req) body = resp.stream.read() print(resp.status_code, resp.headers, body)
Takes a `Request` instance as the only argument.
Returns a `Response` instance. """ raise NotImplementedError( "The 'handle_request' method must be implemented." ) # pragma: no cover
def close(self) -> None: pass
class AsyncBaseTransport: async def __aenter__(self: A) -> A: return self
async def __aexit__( self, exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, traceback: TracebackType | None = None, ) -> None: await self.aclose()
async def handle_async_request( self, request: Request, ) -> Response: raise NotImplementedError( "The 'handle_async_request' method must be implemented." ) # pragma: no cover
async def aclose(self) -> None: pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406"""Custom transports, with nicely configured defaults.
The following additional keyword arguments are currently supported by httpcore...
* uds: str* local_address: str* retries: int
Example usages...
# Disable HTTP/2 on a single specific domain.mounts = { "all://": httpx.HTTPTransport(http2=True), "all://*example.org": httpx.HTTPTransport()}
# Using advanced httpcore configuration, with connection retries.transport = httpx.HTTPTransport(retries=1)client = httpx.Client(transport=transport)
# Using advanced httpcore configuration, with unix domain sockets.transport = httpx.HTTPTransport(uds="socket.uds")client = httpx.Client(transport=transport)"""
from __future__ import annotations
import contextlibimport typingfrom types import TracebackType
if typing.TYPE_CHECKING: import ssl # pragma: no cover
import httpx # pragma: no cover
from .._config import DEFAULT_LIMITS, Limits, Proxy, create_ssl_contextfrom .._exceptions import ( ConnectError, ConnectTimeout, LocalProtocolError, NetworkError, PoolTimeout, ProtocolError, ProxyError, ReadError, ReadTimeout, RemoteProtocolError, TimeoutException, UnsupportedProtocol, WriteError, WriteTimeout,)from .._models import Request, Responsefrom .._types import AsyncByteStream, CertTypes, ProxyTypes, SyncByteStreamfrom .._urls import URLfrom .base import AsyncBaseTransport, BaseTransport
T = typing.TypeVar("T", bound="HTTPTransport")A = typing.TypeVar("A", bound="AsyncHTTPTransport")
SOCKET_OPTION = typing.Union[ typing.Tuple[int, int, int], typing.Tuple[int, int, typing.Union[bytes, bytearray]], typing.Tuple[int, int, None, int],]
__all__ = ["AsyncHTTPTransport", "HTTPTransport"]
HTTPCORE_EXC_MAP: dict[type[Exception], type[httpx.HTTPError]] = {}
def _load_httpcore_exceptions() -> dict[type[Exception], type[httpx.HTTPError]]: import httpcore
return { httpcore.TimeoutException: TimeoutException, httpcore.ConnectTimeout: ConnectTimeout, httpcore.ReadTimeout: ReadTimeout, httpcore.WriteTimeout: WriteTimeout, httpcore.PoolTimeout: PoolTimeout, httpcore.NetworkError: NetworkError, httpcore.ConnectError: ConnectError, httpcore.ReadError: ReadError, httpcore.WriteError: WriteError, httpcore.ProxyError: ProxyError, httpcore.UnsupportedProtocol: UnsupportedProtocol, httpcore.ProtocolError: ProtocolError, httpcore.LocalProtocolError: LocalProtocolError, httpcore.RemoteProtocolError: RemoteProtocolError, }
@contextlib.contextmanagerdef map_httpcore_exceptions() -> typing.Iterator[None]: global HTTPCORE_EXC_MAP if len(HTTPCORE_EXC_MAP) == 0: HTTPCORE_EXC_MAP = _load_httpcore_exceptions() try: yield except Exception as exc: mapped_exc = None
for from_exc, to_exc in HTTPCORE_EXC_MAP.items(): if not isinstance(exc, from_exc): continue # We want to map to the most specific exception we can find. # Eg if `exc` is an `httpcore.ReadTimeout`, we want to map to # `httpx.ReadTimeout`, not just `httpx.TimeoutException`. if mapped_exc is None or issubclass(to_exc, mapped_exc): mapped_exc = to_exc
if mapped_exc is None: # pragma: no cover raise
message = str(exc) raise mapped_exc(message) from exc
class ResponseStream(SyncByteStream): def __init__(self, httpcore_stream: typing.Iterable[bytes]) -> None: self._httpcore_stream = httpcore_stream
def __iter__(self) -> typing.Iterator[bytes]: with map_httpcore_exceptions(): for part in self._httpcore_stream: yield part
def close(self) -> None: if hasattr(self._httpcore_stream, "close"): self._httpcore_stream.close()
class HTTPTransport(BaseTransport): def __init__( self, verify: ssl.SSLContext | str | bool = True, cert: CertTypes | None = None, trust_env: bool = True, http1: bool = True, http2: bool = False, limits: Limits = DEFAULT_LIMITS, proxy: ProxyTypes | None = None, uds: str | None = None, local_address: str | None = None, retries: int = 0, socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> None: import httpcore
proxy = Proxy(url=proxy) if isinstance(proxy, (str, URL)) else proxy ssl_context = create_ssl_context(verify=verify, cert=cert, trust_env=trust_env)
if proxy is None: self._pool = httpcore.ConnectionPool( ssl_context=ssl_context, max_connections=limits.max_connections, max_keepalive_connections=limits.max_keepalive_connections, keepalive_expiry=limits.keepalive_expiry, http1=http1, http2=http2, uds=uds, local_address=local_address, retries=retries, socket_options=socket_options, ) elif proxy.url.scheme in ("http", "https"): self._pool = httpcore.HTTPProxy( proxy_url=httpcore.URL( scheme=proxy.url.raw_scheme, host=proxy.url.raw_host, port=proxy.url.port, target=proxy.url.raw_path, ), proxy_auth=proxy.raw_auth, proxy_headers=proxy.headers.raw, ssl_context=ssl_context, proxy_ssl_context=proxy.ssl_context, max_connections=limits.max_connections, max_keepalive_connections=limits.max_keepalive_connections, keepalive_expiry=limits.keepalive_expiry, http1=http1, http2=http2, socket_options=socket_options, ) elif proxy.url.scheme in ("socks5", "socks5h"): try: import socksio # noqa except ImportError: # pragma: no cover raise ImportError( "Using SOCKS proxy, but the 'socksio' package is not installed. " "Make sure to install httpx using `pip install httpx[socks]`." ) from None
self._pool = httpcore.SOCKSProxy( proxy_url=httpcore.URL( scheme=proxy.url.raw_scheme, host=proxy.url.raw_host, port=proxy.url.port, target=proxy.url.raw_path, ), proxy_auth=proxy.raw_auth, ssl_context=ssl_context, max_connections=limits.max_connections, max_keepalive_connections=limits.max_keepalive_connections, keepalive_expiry=limits.keepalive_expiry, http1=http1, http2=http2, ) else: # pragma: no cover raise ValueError( "Proxy protocol must be either 'http', 'https', 'socks5', or 'socks5h'," f" but got {proxy.url.scheme!r}." )
def __enter__(self: T) -> T: # Use generics for subclass support. self._pool.__enter__() return self
def __exit__( self, exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, traceback: TracebackType | None = None, ) -> None: with map_httpcore_exceptions(): self._pool.__exit__(exc_type, exc_value, traceback)
def handle_request( self, request: Request, ) -> Response: assert isinstance(request.stream, SyncByteStream) import httpcore
req = httpcore.Request( method=request.method, url=httpcore.URL( scheme=request.url.raw_scheme, host=request.url.raw_host, port=request.url.port, target=request.url.raw_path, ), headers=request.headers.raw, content=request.stream, extensions=request.extensions, ) with map_httpcore_exceptions(): resp = self._pool.handle_request(req)
assert isinstance(resp.stream, typing.Iterable)
return Response( status_code=resp.status, headers=resp.headers, stream=ResponseStream(resp.stream), extensions=resp.extensions, )
def close(self) -> None: self._pool.close()
class AsyncResponseStream(AsyncByteStream): def __init__(self, httpcore_stream: typing.AsyncIterable[bytes]) -> None: self._httpcore_stream = httpcore_stream
async def __aiter__(self) -> typing.AsyncIterator[bytes]: with map_httpcore_exceptions(): async for part in self._httpcore_stream: yield part
async def aclose(self) -> None: if hasattr(self._httpcore_stream, "aclose"): await self._httpcore_stream.aclose()
class AsyncHTTPTransport(AsyncBaseTransport): def __init__( self, verify: ssl.SSLContext | str | bool = True, cert: CertTypes | None = None, trust_env: bool = True, http1: bool = True, http2: bool = False, limits: Limits = DEFAULT_LIMITS, proxy: ProxyTypes | None = None, uds: str | None = None, local_address: str | None = None, retries: int = 0, socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> None: import httpcore
proxy = Proxy(url=proxy) if isinstance(proxy, (str, URL)) else proxy ssl_context = create_ssl_context(verify=verify, cert=cert, trust_env=trust_env)
if proxy is None: self._pool = httpcore.AsyncConnectionPool( ssl_context=ssl_context, max_connections=limits.max_connections, max_keepalive_connections=limits.max_keepalive_connections, keepalive_expiry=limits.keepalive_expiry, http1=http1, http2=http2, uds=uds, local_address=local_address, retries=retries, socket_options=socket_options, ) elif proxy.url.scheme in ("http", "https"): self._pool = httpcore.AsyncHTTPProxy( proxy_url=httpcore.URL( scheme=proxy.url.raw_scheme, host=proxy.url.raw_host, port=proxy.url.port, target=proxy.url.raw_path, ), proxy_auth=proxy.raw_auth, proxy_headers=proxy.headers.raw, proxy_ssl_context=proxy.ssl_context, ssl_context=ssl_context, max_connections=limits.max_connections, max_keepalive_connections=limits.max_keepalive_connections, keepalive_expiry=limits.keepalive_expiry, http1=http1, http2=http2, socket_options=socket_options, ) elif proxy.url.scheme in ("socks5", "socks5h"): try: import socksio # noqa except ImportError: # pragma: no cover raise ImportError( "Using SOCKS proxy, but the 'socksio' package is not installed. " "Make sure to install httpx using `pip install httpx[socks]`." ) from None
self._pool = httpcore.AsyncSOCKSProxy( proxy_url=httpcore.URL( scheme=proxy.url.raw_scheme, host=proxy.url.raw_host, port=proxy.url.port, target=proxy.url.raw_path, ), proxy_auth=proxy.raw_auth, ssl_context=ssl_context, max_connections=limits.max_connections, max_keepalive_connections=limits.max_keepalive_connections, keepalive_expiry=limits.keepalive_expiry, http1=http1, http2=http2, ) else: # pragma: no cover raise ValueError( "Proxy protocol must be either 'http', 'https', 'socks5', or 'socks5h'," " but got {proxy.url.scheme!r}." )
async def __aenter__(self: A) -> A: # Use generics for subclass support. await self._pool.__aenter__() return self
async def __aexit__( self, exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, traceback: TracebackType | None = None, ) -> None: with map_httpcore_exceptions(): await self._pool.__aexit__(exc_type, exc_value, traceback)
async def handle_async_request( self, request: Request, ) -> Response: assert isinstance(request.stream, AsyncByteStream) import httpcore
req = httpcore.Request( method=request.method, url=httpcore.URL( scheme=request.url.raw_scheme, host=request.url.raw_host, port=request.url.port, target=request.url.raw_path, ), headers=request.headers.raw, content=request.stream, extensions=request.extensions, ) with map_httpcore_exceptions(): resp = await self._pool.handle_async_request(req)
assert isinstance(resp.stream, typing.AsyncIterable)
return Response( status_code=resp.status, headers=resp.headers, stream=AsyncResponseStream(resp.stream), extensions=resp.extensions, )
async def aclose(self) -> None: await self._pool.aclose()12345678910111213141516171819202122232425262728293031323334353637383940414243from __future__ import annotations
import typing
from .._models import Request, Responsefrom .base import AsyncBaseTransport, BaseTransport
SyncHandler = typing.Callable[[Request], Response]AsyncHandler = typing.Callable[[Request], typing.Coroutine[None, None, Response]]
__all__ = ["MockTransport"]
class MockTransport(AsyncBaseTransport, BaseTransport): def __init__(self, handler: SyncHandler | AsyncHandler) -> None: self.handler = handler
def handle_request( self, request: Request, ) -> Response: request.read() response = self.handler(request) if not isinstance(response, Response): # pragma: no cover raise TypeError("Cannot use an async handler in a sync Client") return response
async def handle_async_request( self, request: Request, ) -> Response: await request.aread() response = self.handler(request)
# Allow handler to *optionally* be an `async` function. # If it is, then the `response` variable need to be awaited to actually # return the result.
if not isinstance(response, Response): response = await response
return response123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149from __future__ import annotations
import ioimport itertoolsimport sysimport typing
from .._models import Request, Responsefrom .._types import SyncByteStreamfrom .base import BaseTransport
if typing.TYPE_CHECKING: from _typeshed import OptExcInfo # pragma: no cover from _typeshed.wsgi import WSGIApplication # pragma: no cover
_T = typing.TypeVar("_T")
__all__ = ["WSGITransport"]
def _skip_leading_empty_chunks(body: typing.Iterable[_T]) -> typing.Iterable[_T]: body = iter(body) for chunk in body: if chunk: return itertools.chain([chunk], body) return []
class WSGIByteStream(SyncByteStream): def __init__(self, result: typing.Iterable[bytes]) -> None: self._close = getattr(result, "close", None) self._result = _skip_leading_empty_chunks(result)
def __iter__(self) -> typing.Iterator[bytes]: for part in self._result: yield part
def close(self) -> None: if self._close is not None: self._close()
class WSGITransport(BaseTransport): """ A custom transport that handles sending requests directly to an WSGI app. The simplest way to use this functionality is to use the `app` argument.
``` client = httpx.Client(app=app) ```
Alternatively, you can setup the transport instance explicitly. This allows you to include any additional configuration arguments specific to the WSGITransport class:
``` transport = httpx.WSGITransport( app=app, script_name="/submount", remote_addr="1.2.3.4" ) client = httpx.Client(transport=transport) ```
Arguments:
* `app` - The WSGI application. * `raise_app_exceptions` - Boolean indicating if exceptions in the application should be raised. Default to `True`. Can be set to `False` for use cases such as testing the content of a client 500 response. * `script_name` - The root path on which the WSGI application should be mounted. * `remote_addr` - A string indicating the client IP of incoming requests. ``` """
def __init__( self, app: WSGIApplication, raise_app_exceptions: bool = True, script_name: str = "", remote_addr: str = "127.0.0.1", wsgi_errors: typing.TextIO | None = None, ) -> None: self.app = app self.raise_app_exceptions = raise_app_exceptions self.script_name = script_name self.remote_addr = remote_addr self.wsgi_errors = wsgi_errors
def handle_request(self, request: Request) -> Response: request.read() wsgi_input = io.BytesIO(request.content)
port = request.url.port or {"http": 80, "https": 443}[request.url.scheme] environ = { "wsgi.version": (1, 0), "wsgi.url_scheme": request.url.scheme, "wsgi.input": wsgi_input, "wsgi.errors": self.wsgi_errors or sys.stderr, "wsgi.multithread": True, "wsgi.multiprocess": False, "wsgi.run_once": False, "REQUEST_METHOD": request.method, "SCRIPT_NAME": self.script_name, "PATH_INFO": request.url.path, "QUERY_STRING": request.url.query.decode("ascii"), "SERVER_NAME": request.url.host, "SERVER_PORT": str(port), "SERVER_PROTOCOL": "HTTP/1.1", "REMOTE_ADDR": self.remote_addr, } for header_key, header_value in request.headers.raw: key = header_key.decode("ascii").upper().replace("-", "_") if key not in ("CONTENT_TYPE", "CONTENT_LENGTH"): key = "HTTP_" + key environ[key] = header_value.decode("ascii")
seen_status = None seen_response_headers = None seen_exc_info = None
def start_response( status: str, response_headers: list[tuple[str, str]], exc_info: OptExcInfo | None = None, ) -> typing.Callable[[bytes], typing.Any]: nonlocal seen_status, seen_response_headers, seen_exc_info seen_status = status seen_response_headers = response_headers seen_exc_info = exc_info return lambda _: None
result = self.app(environ, start_response)
stream = WSGIByteStream(result)
assert seen_status is not None assert seen_response_headers is not None if seen_exc_info and seen_exc_info[0] and self.raise_app_exceptions: raise seen_exc_info[1]
status_code = int(seen_status.split()[0]) headers = [ (key.encode("ascii"), value.encode("ascii")) for key, value in seen_response_headers ]
return Response(status_code, headers=headers, stream=stream)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114"""Type definitions for type checking purposes."""
from http.cookiejar import CookieJarfrom typing import ( IO, TYPE_CHECKING, Any, AsyncIterable, AsyncIterator, Callable, Dict, Iterable, Iterator, List, Mapping, Optional, Sequence, Tuple, Union,)
if TYPE_CHECKING: # pragma: no cover from ._auth import Auth # noqa: F401 from ._config import Proxy, Timeout # noqa: F401 from ._models import Cookies, Headers, Request # noqa: F401 from ._urls import URL, QueryParams # noqa: F401
PrimitiveData = Optional[Union[str, int, float, bool]]
URLTypes = Union["URL", str]
QueryParamTypes = Union[ "QueryParams", Mapping[str, Union[PrimitiveData, Sequence[PrimitiveData]]], List[Tuple[str, PrimitiveData]], Tuple[Tuple[str, PrimitiveData], ...], str, bytes,]
HeaderTypes = Union[ "Headers", Mapping[str, str], Mapping[bytes, bytes], Sequence[Tuple[str, str]], Sequence[Tuple[bytes, bytes]],]
CookieTypes = Union["Cookies", CookieJar, Dict[str, str], List[Tuple[str, str]]]
TimeoutTypes = Union[ Optional[float], Tuple[Optional[float], Optional[float], Optional[float], Optional[float]], "Timeout",]ProxyTypes = Union["URL", str, "Proxy"]CertTypes = Union[str, Tuple[str, str], Tuple[str, str, str]]
AuthTypes = Union[ Tuple[Union[str, bytes], Union[str, bytes]], Callable[["Request"], "Request"], "Auth",]
RequestContent = Union[str, bytes, Iterable[bytes], AsyncIterable[bytes]]ResponseContent = Union[str, bytes, Iterable[bytes], AsyncIterable[bytes]]ResponseExtensions = Mapping[str, Any]
RequestData = Mapping[str, Any]
FileContent = Union[IO[bytes], bytes, str]FileTypes = Union[ # file (or bytes) FileContent, # (filename, file (or bytes)) Tuple[Optional[str], FileContent], # (filename, file (or bytes), content_type) Tuple[Optional[str], FileContent, Optional[str]], # (filename, file (or bytes), content_type, headers) Tuple[Optional[str], FileContent, Optional[str], Mapping[str, str]],]RequestFiles = Union[Mapping[str, FileTypes], Sequence[Tuple[str, FileTypes]]]
RequestExtensions = Mapping[str, Any]
__all__ = ["AsyncByteStream", "SyncByteStream"]
class SyncByteStream: def __iter__(self) -> Iterator[bytes]: raise NotImplementedError( "The '__iter__' method must be implemented." ) # pragma: no cover yield b"" # pragma: no cover
def close(self) -> None: """ Subclasses can override this method to release any network resources after a request/response cycle is complete. """
class AsyncByteStream: async def __aiter__(self) -> AsyncIterator[bytes]: raise NotImplementedError( "The '__aiter__' method must be implemented." ) # pragma: no cover yield b"" # pragma: no cover
async def aclose(self) -> None: pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527"""An implementation of `urlparse` that provides URL validation and normalizationas described by RFC3986.
We rely on this implementation rather than the one in Python's stdlib, because:
* It provides more complete URL validation.* It properly differentiates between an empty querystring and an absent querystring, to distinguish URLs with a trailing '?'.* It handles scheme, hostname, port, and path normalization.* It supports IDNA hostnames, normalizing them to their encoded form.* The API supports passing individual components, as well as the complete URL string.
Previously we relied on the excellent `rfc3986` package to handle URL parsing andvalidation, but this module provides a simpler alternative, with less indirectionrequired."""
from __future__ import annotations
import ipaddressimport reimport typing
import idna
from ._exceptions import InvalidURL
MAX_URL_LENGTH = 65536
# https://datatracker.ietf.org/doc/html/rfc3986.html#section-2.3UNRESERVED_CHARACTERS = ( "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~")SUB_DELIMS = "!$&'()*+,;="
PERCENT_ENCODED_REGEX = re.compile("%[A-Fa-f0-9]{2}")
# https://url.spec.whatwg.org/#percent-encoded-bytes
# The fragment percent-encode set is the C0 control percent-encode set# and U+0020 SPACE, U+0022 ("), U+003C (<), U+003E (>), and U+0060 (`).FRAG_SAFE = "".join( [chr(i) for i in range(0x20, 0x7F) if i not in (0x20, 0x22, 0x3C, 0x3E, 0x60)])
# The query percent-encode set is the C0 control percent-encode set# and U+0020 SPACE, U+0022 ("), U+0023 (#), U+003C (<), and U+003E (>).QUERY_SAFE = "".join( [chr(i) for i in range(0x20, 0x7F) if i not in (0x20, 0x22, 0x23, 0x3C, 0x3E)])
# The path percent-encode set is the query percent-encode set# and U+003F (?), U+0060 (`), U+007B ({), and U+007D (}).PATH_SAFE = "".join( [ chr(i) for i in range(0x20, 0x7F) if i not in (0x20, 0x22, 0x23, 0x3C, 0x3E) + (0x3F, 0x60, 0x7B, 0x7D) ])
# The userinfo percent-encode set is the path percent-encode set# and U+002F (/), U+003A (:), U+003B (;), U+003D (=), U+0040 (@),# U+005B ([) to U+005E (^), inclusive, and U+007C (|).USERNAME_SAFE = "".join( [ chr(i) for i in range(0x20, 0x7F) if i not in (0x20, 0x22, 0x23, 0x3C, 0x3E) + (0x3F, 0x60, 0x7B, 0x7D) + (0x2F, 0x3A, 0x3B, 0x3D, 0x40, 0x5B, 0x5C, 0x5D, 0x5E, 0x7C) ])PASSWORD_SAFE = "".join( [ chr(i) for i in range(0x20, 0x7F) if i not in (0x20, 0x22, 0x23, 0x3C, 0x3E) + (0x3F, 0x60, 0x7B, 0x7D) + (0x2F, 0x3A, 0x3B, 0x3D, 0x40, 0x5B, 0x5C, 0x5D, 0x5E, 0x7C) ])# Note... The terminology 'userinfo' percent-encode set in the WHATWG document# is used for the username and password quoting. For the joint userinfo component# we remove U+003A (:) from the safe set.USERINFO_SAFE = "".join( [ chr(i) for i in range(0x20, 0x7F) if i not in (0x20, 0x22, 0x23, 0x3C, 0x3E) + (0x3F, 0x60, 0x7B, 0x7D) + (0x2F, 0x3B, 0x3D, 0x40, 0x5B, 0x5C, 0x5D, 0x5E, 0x7C) ])
# {scheme}: (optional)# //{authority} (optional)# {path}# ?{query} (optional)# #{fragment} (optional)URL_REGEX = re.compile( ( r"(?:(?P<scheme>{scheme}):)?" r"(?://(?P<authority>{authority}))?" r"(?P<path>{path})" r"(?:\?(?P<query>{query}))?" r"(?:#(?P<fragment>{fragment}))?" ).format( scheme="([a-zA-Z][a-zA-Z0-9+.-]*)?", authority="[^/?#]*", path="[^?#]*", query="[^#]*", fragment=".*", ))
# {userinfo}@ (optional)# {host}# :{port} (optional)AUTHORITY_REGEX = re.compile( ( r"(?:(?P<userinfo>{userinfo})@)?" r"(?P<host>{host})" r":?(?P<port>{port})?" ).format( userinfo=".*", # Any character sequence. host="(\\[.*\\]|[^:@]*)", # Either any character sequence excluding ':' or '@', # or an IPv6 address enclosed within square brackets. port=".*", # Any character sequence. ))
# If we call urlparse with an individual component, then we need to regex# validate that component individually.# Note that we're duplicating the same strings as above. Shock! Horror!!COMPONENT_REGEX = { "scheme": re.compile("([a-zA-Z][a-zA-Z0-9+.-]*)?"), "authority": re.compile("[^/?#]*"), "path": re.compile("[^?#]*"), "query": re.compile("[^#]*"), "fragment": re.compile(".*"), "userinfo": re.compile("[^@]*"), "host": re.compile("(\\[.*\\]|[^:]*)"), "port": re.compile(".*"),}
# We use these simple regexs as a first pass before handing off to# the stdlib 'ipaddress' module for IP address validation.IPv4_STYLE_HOSTNAME = re.compile(r"^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$")IPv6_STYLE_HOSTNAME = re.compile(r"^\[.*\]$")
class ParseResult(typing.NamedTuple): scheme: str userinfo: str host: str port: int | None path: str query: str | None fragment: str | None
@property def authority(self) -> str: return "".join( [ f"{self.userinfo}@" if self.userinfo else "", f"[{self.host}]" if ":" in self.host else self.host, f":{self.port}" if self.port is not None else "", ] )
@property def netloc(self) -> str: return "".join( [ f"[{self.host}]" if ":" in self.host else self.host, f":{self.port}" if self.port is not None else "", ] )
def copy_with(self, **kwargs: str | None) -> ParseResult: if not kwargs: return self
defaults = { "scheme": self.scheme, "authority": self.authority, "path": self.path, "query": self.query, "fragment": self.fragment, } defaults.update(kwargs) return urlparse("", **defaults)
def __str__(self) -> str: authority = self.authority return "".join( [ f"{self.scheme}:" if self.scheme else "", f"//{authority}" if authority else "", self.path, f"?{self.query}" if self.query is not None else "", f"#{self.fragment}" if self.fragment is not None else "", ] )
def urlparse(url: str = "", **kwargs: str | None) -> ParseResult: # Initial basic checks on allowable URLs. # ---------------------------------------
# Hard limit the maximum allowable URL length. if len(url) > MAX_URL_LENGTH: raise InvalidURL("URL too long")
# If a URL includes any ASCII control characters including \t, \r, \n, # then treat it as invalid. if any(char.isascii() and not char.isprintable() for char in url): char = next(char for char in url if char.isascii() and not char.isprintable()) idx = url.find(char) error = ( f"Invalid non-printable ASCII character in URL, {char!r} at position {idx}." ) raise InvalidURL(error)
# Some keyword arguments require special handling. # ------------------------------------------------
# Coerce "port" to a string, if it is provided as an integer. if "port" in kwargs: port = kwargs["port"] kwargs["port"] = str(port) if isinstance(port, int) else port
# Replace "netloc" with "host and "port". if "netloc" in kwargs: netloc = kwargs.pop("netloc") or "" kwargs["host"], _, kwargs["port"] = netloc.partition(":")
# Replace "username" and/or "password" with "userinfo". if "username" in kwargs or "password" in kwargs: username = quote(kwargs.pop("username", "") or "", safe=USERNAME_SAFE) password = quote(kwargs.pop("password", "") or "", safe=PASSWORD_SAFE) kwargs["userinfo"] = f"{username}:{password}" if password else username
# Replace "raw_path" with "path" and "query". if "raw_path" in kwargs: raw_path = kwargs.pop("raw_path") or "" kwargs["path"], seperator, kwargs["query"] = raw_path.partition("?") if not seperator: kwargs["query"] = None
# Ensure that IPv6 "host" addresses are always escaped with "[...]". if "host" in kwargs: host = kwargs.get("host") or "" if ":" in host and not (host.startswith("[") and host.endswith("]")): kwargs["host"] = f"[{host}]"
# If any keyword arguments are provided, ensure they are valid. # -------------------------------------------------------------
for key, value in kwargs.items(): if value is not None: if len(value) > MAX_URL_LENGTH: raise InvalidURL(f"URL component '{key}' too long")
# If a component includes any ASCII control characters including \t, \r, \n, # then treat it as invalid. if any(char.isascii() and not char.isprintable() for char in value): char = next( char for char in value if char.isascii() and not char.isprintable() ) idx = value.find(char) error = ( f"Invalid non-printable ASCII character in URL {key} component, " f"{char!r} at position {idx}." ) raise InvalidURL(error)
# Ensure that keyword arguments match as a valid regex. if not COMPONENT_REGEX[key].fullmatch(value): raise InvalidURL(f"Invalid URL component '{key}'")
# The URL_REGEX will always match, but may have empty components. url_match = URL_REGEX.match(url) assert url_match is not None url_dict = url_match.groupdict()
# * 'scheme', 'authority', and 'path' may be empty strings. # * 'query' may be 'None', indicating no trailing "?" portion. # Any string including the empty string, indicates a trailing "?". # * 'fragment' may be 'None', indicating no trailing "#" portion. # Any string including the empty string, indicates a trailing "#". scheme = kwargs.get("scheme", url_dict["scheme"]) or "" authority = kwargs.get("authority", url_dict["authority"]) or "" path = kwargs.get("path", url_dict["path"]) or "" query = kwargs.get("query", url_dict["query"]) frag = kwargs.get("fragment", url_dict["fragment"])
# The AUTHORITY_REGEX will always match, but may have empty components. authority_match = AUTHORITY_REGEX.match(authority) assert authority_match is not None authority_dict = authority_match.groupdict()
# * 'userinfo' and 'host' may be empty strings. # * 'port' may be 'None'. userinfo = kwargs.get("userinfo", authority_dict["userinfo"]) or "" host = kwargs.get("host", authority_dict["host"]) or "" port = kwargs.get("port", authority_dict["port"])
# Normalize and validate each component. # We end up with a parsed representation of the URL, # with components that are plain ASCII bytestrings. parsed_scheme: str = scheme.lower() parsed_userinfo: str = quote(userinfo, safe=USERINFO_SAFE) parsed_host: str = encode_host(host) parsed_port: int | None = normalize_port(port, scheme)
has_scheme = parsed_scheme != "" has_authority = ( parsed_userinfo != "" or parsed_host != "" or parsed_port is not None ) validate_path(path, has_scheme=has_scheme, has_authority=has_authority) if has_scheme or has_authority: path = normalize_path(path)
parsed_path: str = quote(path, safe=PATH_SAFE) parsed_query: str | None = None if query is None else quote(query, safe=QUERY_SAFE) parsed_frag: str | None = None if frag is None else quote(frag, safe=FRAG_SAFE)
# The parsed ASCII bytestrings are our canonical form. # All properties of the URL are derived from these. return ParseResult( parsed_scheme, parsed_userinfo, parsed_host, parsed_port, parsed_path, parsed_query, parsed_frag, )
def encode_host(host: str) -> str: if not host: return ""
elif IPv4_STYLE_HOSTNAME.match(host): # Validate IPv4 hostnames like #.#.#.# # # From https://datatracker.ietf.org/doc/html/rfc3986/#section-3.2.2 # # IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet try: ipaddress.IPv4Address(host) except ipaddress.AddressValueError: raise InvalidURL(f"Invalid IPv4 address: {host!r}") return host
elif IPv6_STYLE_HOSTNAME.match(host): # Validate IPv6 hostnames like [...] # # From https://datatracker.ietf.org/doc/html/rfc3986/#section-3.2.2 # # "A host identified by an Internet Protocol literal address, version 6 # [RFC3513] or later, is distinguished by enclosing the IP literal # within square brackets ("[" and "]"). This is the only place where # square bracket characters are allowed in the URI syntax." try: ipaddress.IPv6Address(host[1:-1]) except ipaddress.AddressValueError: raise InvalidURL(f"Invalid IPv6 address: {host!r}") return host[1:-1]
elif host.isascii(): # Regular ASCII hostnames # # From https://datatracker.ietf.org/doc/html/rfc3986/#section-3.2.2 # # reg-name = *( unreserved / pct-encoded / sub-delims ) WHATWG_SAFE = '"`{}%|\\' return quote(host.lower(), safe=SUB_DELIMS + WHATWG_SAFE)
# IDNA hostnames try: return idna.encode(host.lower()).decode("ascii") except idna.IDNAError: raise InvalidURL(f"Invalid IDNA hostname: {host!r}")
def normalize_port(port: str | int | None, scheme: str) -> int | None: # From https://tools.ietf.org/html/rfc3986#section-3.2.3 # # "A scheme may define a default port. For example, the "http" scheme # defines a default port of "80", corresponding to its reserved TCP # port number. The type of port designated by the port number (e.g., # TCP, UDP, SCTP) is defined by the URI scheme. URI producers and # normalizers should omit the port component and its ":" delimiter if # port is empty or if its value would be the same as that of the # scheme's default." if port is None or port == "": return None
try: port_as_int = int(port) except ValueError: raise InvalidURL(f"Invalid port: {port!r}")
# See https://url.spec.whatwg.org/#url-miscellaneous default_port = {"ftp": 21, "http": 80, "https": 443, "ws": 80, "wss": 443}.get( scheme ) if port_as_int == default_port: return None return port_as_int
def validate_path(path: str, has_scheme: bool, has_authority: bool) -> None: """ Path validation rules that depend on if the URL contains a scheme or authority component.
See https://datatracker.ietf.org/doc/html/rfc3986.html#section-3.3 """ if has_authority: # If a URI contains an authority component, then the path component # must either be empty or begin with a slash ("/") character." if path and not path.startswith("/"): raise InvalidURL("For absolute URLs, path must be empty or begin with '/'")
if not has_scheme and not has_authority: # If a URI does not contain an authority component, then the path cannot begin # with two slash characters ("//"). if path.startswith("//"): raise InvalidURL("Relative URLs cannot have a path starting with '//'")
# In addition, a URI reference (Section 4.1) may be a relative-path reference, # in which case the first path segment cannot contain a colon (":") character. if path.startswith(":"): raise InvalidURL("Relative URLs cannot have a path starting with ':'")
def normalize_path(path: str) -> str: """ Drop "." and ".." segments from a URL path.
For example:
normalize_path("/path/./to/somewhere/..") == "/path/to" """ # Fast return when no '.' characters in the path. if "." not in path: return path
components = path.split("/")
# Fast return when no '.' or '..' components in the path. if "." not in components and ".." not in components: return path
# https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4 output: list[str] = [] for component in components: if component == ".": pass elif component == "..": if output and output != [""]: output.pop() else: output.append(component) return "/".join(output)
def PERCENT(string: str) -> str: return "".join([f"%{byte:02X}" for byte in string.encode("utf-8")])
def percent_encoded(string: str, safe: str) -> str: """ Use percent-encoding to quote a string. """ NON_ESCAPED_CHARS = UNRESERVED_CHARACTERS + safe
# Fast path for strings that don't need escaping. if not string.rstrip(NON_ESCAPED_CHARS): return string
return "".join( [char if char in NON_ESCAPED_CHARS else PERCENT(char) for char in string] )
def quote(string: str, safe: str) -> str: """ Use percent-encoding to quote a string, omitting existing '%xx' escape sequences.
See: https://www.rfc-editor.org/rfc/rfc3986#section-2.1
* `string`: The string to be percent-escaped. * `safe`: A string containing characters that may be treated as safe, and do not need to be escaped. Unreserved characters are always treated as safe. See: https://www.rfc-editor.org/rfc/rfc3986#section-2.3 """ parts = [] current_position = 0 for match in re.finditer(PERCENT_ENCODED_REGEX, string): start_position, end_position = match.start(), match.end() matched_text = match.group(0) # Add any text up to the '%xx' escape sequence. if start_position != current_position: leading_text = string[current_position:start_position] parts.append(percent_encoded(leading_text, safe=safe))
# Add the '%xx' escape sequence. parts.append(matched_text) current_position = end_position
# Add any text after the final '%xx' escape sequence. if current_position != len(string): trailing_text = string[current_position:] parts.append(percent_encoded(trailing_text, safe=safe))
return "".join(parts)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641from __future__ import annotations
import typingfrom urllib.parse import parse_qs, unquote, urlencode
import idna
from ._types import QueryParamTypesfrom ._urlparse import urlparsefrom ._utils import primitive_value_to_str
__all__ = ["URL", "QueryParams"]
class URL: """ url = httpx.URL("HTTPS://jo%40email.com:a%20secret@müller.de:1234/pa%20th?search=ab#anchorlink")
assert url.scheme == "https" assert url.username == "jo@email.com" assert url.password == "a secret" assert url.userinfo == b"jo%40email.com:a%20secret" assert url.host == "müller.de" assert url.raw_host == b"xn--mller-kva.de" assert url.port == 1234 assert url.netloc == b"xn--mller-kva.de:1234" assert url.path == "/pa th" assert url.query == b"?search=ab" assert url.raw_path == b"/pa%20th?search=ab" assert url.fragment == "anchorlink"
The components of a URL are broken down like this:
https://jo%40email.com:a%20secret@müller.de:1234/pa%20th?search=ab#anchorlink [scheme] [ username ] [password] [ host ][port][ path ] [ query ] [fragment] [ userinfo ] [ netloc ][ raw_path ]
Note that:
* `url.scheme` is normalized to always be lowercased.
* `url.host` is normalized to always be lowercased. Internationalized domain names are represented in unicode, without IDNA encoding applied. For instance:
url = httpx.URL("http://中国.icom.museum") assert url.host == "中国.icom.museum" url = httpx.URL("http://xn--fiqs8s.icom.museum") assert url.host == "中国.icom.museum"
* `url.raw_host` is normalized to always be lowercased, and is IDNA encoded.
url = httpx.URL("http://中国.icom.museum") assert url.raw_host == b"xn--fiqs8s.icom.museum" url = httpx.URL("http://xn--fiqs8s.icom.museum") assert url.raw_host == b"xn--fiqs8s.icom.museum"
* `url.port` is either None or an integer. URLs that include the default port for "http", "https", "ws", "wss", and "ftp" schemes have their port normalized to `None`.
assert httpx.URL("http://example.com") == httpx.URL("http://example.com:80") assert httpx.URL("http://example.com").port is None assert httpx.URL("http://example.com:80").port is None
* `url.userinfo` is raw bytes, without URL escaping. Usually you'll want to work with `url.username` and `url.password` instead, which handle the URL escaping.
* `url.raw_path` is raw bytes of both the path and query, without URL escaping. This portion is used as the target when constructing HTTP requests. Usually you'll want to work with `url.path` instead.
* `url.query` is raw bytes, without URL escaping. A URL query string portion can only be properly URL escaped when decoding the parameter names and values themselves. """
def __init__(self, url: URL | str = "", **kwargs: typing.Any) -> None: if kwargs: allowed = { "scheme": str, "username": str, "password": str, "userinfo": bytes, "host": str, "port": int, "netloc": bytes, "path": str, "query": bytes, "raw_path": bytes, "fragment": str, "params": object, }
# Perform type checking for all supported keyword arguments. for key, value in kwargs.items(): if key not in allowed: message = f"{key!r} is an invalid keyword argument for URL()" raise TypeError(message) if value is not None and not isinstance(value, allowed[key]): expected = allowed[key].__name__ seen = type(value).__name__ message = f"Argument {key!r} must be {expected} but got {seen}" raise TypeError(message) if isinstance(value, bytes): kwargs[key] = value.decode("ascii")
if "params" in kwargs: # Replace any "params" keyword with the raw "query" instead. # # Ensure that empty params use `kwargs["query"] = None` rather # than `kwargs["query"] = ""`, so that generated URLs do not # include an empty trailing "?". params = kwargs.pop("params") kwargs["query"] = None if not params else str(QueryParams(params))
if isinstance(url, str): self._uri_reference = urlparse(url, **kwargs) elif isinstance(url, URL): self._uri_reference = url._uri_reference.copy_with(**kwargs) else: raise TypeError( "Invalid type for url. Expected str or httpx.URL," f" got {type(url)}: {url!r}" )
@property def scheme(self) -> str: """ The URL scheme, such as "http", "https". Always normalised to lowercase. """ return self._uri_reference.scheme
@property def raw_scheme(self) -> bytes: """ The raw bytes representation of the URL scheme, such as b"http", b"https". Always normalised to lowercase. """ return self._uri_reference.scheme.encode("ascii")
@property def userinfo(self) -> bytes: """ The URL userinfo as a raw bytestring. For example: b"jo%40email.com:a%20secret". """ return self._uri_reference.userinfo.encode("ascii")
@property def username(self) -> str: """ The URL username as a string, with URL decoding applied. For example: "jo@email.com" """ userinfo = self._uri_reference.userinfo return unquote(userinfo.partition(":")[0])
@property def password(self) -> str: """ The URL password as a string, with URL decoding applied. For example: "a secret" """ userinfo = self._uri_reference.userinfo return unquote(userinfo.partition(":")[2])
@property def host(self) -> str: """ The URL host as a string. Always normalized to lowercase, with IDNA hosts decoded into unicode.
Examples:
url = httpx.URL("http://www.EXAMPLE.org") assert url.host == "www.example.org"
url = httpx.URL("http://中国.icom.museum") assert url.host == "中国.icom.museum"
url = httpx.URL("http://xn--fiqs8s.icom.museum") assert url.host == "中国.icom.museum"
url = httpx.URL("https://[::ffff:192.168.0.1]") assert url.host == "::ffff:192.168.0.1" """ host: str = self._uri_reference.host
if host.startswith("xn--"): host = idna.decode(host)
return host
@property def raw_host(self) -> bytes: """ The raw bytes representation of the URL host. Always normalized to lowercase, and IDNA encoded.
Examples:
url = httpx.URL("http://www.EXAMPLE.org") assert url.raw_host == b"www.example.org"
url = httpx.URL("http://中国.icom.museum") assert url.raw_host == b"xn--fiqs8s.icom.museum"
url = httpx.URL("http://xn--fiqs8s.icom.museum") assert url.raw_host == b"xn--fiqs8s.icom.museum"
url = httpx.URL("https://[::ffff:192.168.0.1]") assert url.raw_host == b"::ffff:192.168.0.1" """ return self._uri_reference.host.encode("ascii")
@property def port(self) -> int | None: """ The URL port as an integer.
Note that the URL class performs port normalization as per the WHATWG spec. Default ports for "http", "https", "ws", "wss", and "ftp" schemes are always treated as `None`.
For example:
assert httpx.URL("http://www.example.com") == httpx.URL("http://www.example.com:80") assert httpx.URL("http://www.example.com:80").port is None """ return self._uri_reference.port
@property def netloc(self) -> bytes: """ Either `<host>` or `<host>:<port>` as bytes. Always normalized to lowercase, and IDNA encoded.
This property may be used for generating the value of a request "Host" header. """ return self._uri_reference.netloc.encode("ascii")
@property def path(self) -> str: """ The URL path as a string. Excluding the query string, and URL decoded.
For example:
url = httpx.URL("https://example.com/pa%20th") assert url.path == "/pa th" """ path = self._uri_reference.path or "/" return unquote(path)
@property def query(self) -> bytes: """ The URL query string, as raw bytes, excluding the leading b"?".
This is necessarily a bytewise interface, because we cannot perform URL decoding of this representation until we've parsed the keys and values into a QueryParams instance.
For example:
url = httpx.URL("https://example.com/?filter=some%20search%20terms") assert url.query == b"filter=some%20search%20terms" """ query = self._uri_reference.query or "" return query.encode("ascii")
@property def params(self) -> QueryParams: """ The URL query parameters, neatly parsed and packaged into an immutable multidict representation. """ return QueryParams(self._uri_reference.query)
@property def raw_path(self) -> bytes: """ The complete URL path and query string as raw bytes. Used as the target when constructing HTTP requests.
For example:
GET /users?search=some%20text HTTP/1.1 Host: www.example.org Connection: close """ path = self._uri_reference.path or "/" if self._uri_reference.query is not None: path += "?" + self._uri_reference.query return path.encode("ascii")
@property def fragment(self) -> str: """ The URL fragments, as used in HTML anchors. As a string, without the leading '#'. """ return unquote(self._uri_reference.fragment or "")
@property def is_absolute_url(self) -> bool: """ Return `True` for absolute URLs such as 'http://example.com/path', and `False` for relative URLs such as '/path'. """ # We don't use `.is_absolute` from `rfc3986` because it treats # URLs with a fragment portion as not absolute. # What we actually care about is if the URL provides # a scheme and hostname to which connections should be made. return bool(self._uri_reference.scheme and self._uri_reference.host)
@property def is_relative_url(self) -> bool: """ Return `False` for absolute URLs such as 'http://example.com/path', and `True` for relative URLs such as '/path'. """ return not self.is_absolute_url
def copy_with(self, **kwargs: typing.Any) -> URL: """ Copy this URL, returning a new URL with some components altered. Accepts the same set of parameters as the components that are made available via properties on the `URL` class.
For example:
url = httpx.URL("https://www.example.com").copy_with( username="jo@gmail.com", password="a secret" ) assert url == "https://jo%40email.com:a%20secret@www.example.com" """ return URL(self, **kwargs)
def copy_set_param(self, key: str, value: typing.Any = None) -> URL: return self.copy_with(params=self.params.set(key, value))
def copy_add_param(self, key: str, value: typing.Any = None) -> URL: return self.copy_with(params=self.params.add(key, value))
def copy_remove_param(self, key: str) -> URL: return self.copy_with(params=self.params.remove(key))
def copy_merge_params(self, params: QueryParamTypes) -> URL: return self.copy_with(params=self.params.merge(params))
def join(self, url: URL | str) -> URL: """ Return an absolute URL, using this URL as the base.
Eg.
url = httpx.URL("https://www.example.com/test") url = url.join("/new/path") assert url == "https://www.example.com/new/path" """ from urllib.parse import urljoin
return URL(urljoin(str(self), str(URL(url))))
def __hash__(self) -> int: return hash(str(self))
def __eq__(self, other: typing.Any) -> bool: return isinstance(other, (URL, str)) and str(self) == str(URL(other))
def __str__(self) -> str: return str(self._uri_reference)
def __repr__(self) -> str: scheme, userinfo, host, port, path, query, fragment = self._uri_reference
if ":" in userinfo: # Mask any password component. userinfo = f'{userinfo.split(":")[0]}:[secure]'
authority = "".join( [ f"{userinfo}@" if userinfo else "", f"[{host}]" if ":" in host else host, f":{port}" if port is not None else "", ] ) url = "".join( [ f"{self.scheme}:" if scheme else "", f"//{authority}" if authority else "", path, f"?{query}" if query is not None else "", f"#{fragment}" if fragment is not None else "", ] )
return f"{self.__class__.__name__}({url!r})"
@property def raw(self) -> tuple[bytes, bytes, int, bytes]: # pragma: nocover import collections import warnings
warnings.warn("URL.raw is deprecated.") RawURL = collections.namedtuple( "RawURL", ["raw_scheme", "raw_host", "port", "raw_path"] ) return RawURL( raw_scheme=self.raw_scheme, raw_host=self.raw_host, port=self.port, raw_path=self.raw_path, )
class QueryParams(typing.Mapping[str, str]): """ URL query parameters, as a multi-dict. """
def __init__(self, *args: QueryParamTypes | None, **kwargs: typing.Any) -> None: assert len(args) < 2, "Too many arguments." assert not (args and kwargs), "Cannot mix named and unnamed arguments."
value = args[0] if args else kwargs
if value is None or isinstance(value, (str, bytes)): value = value.decode("ascii") if isinstance(value, bytes) else value self._dict = parse_qs(value, keep_blank_values=True) elif isinstance(value, QueryParams): self._dict = {k: list(v) for k, v in value._dict.items()} else: dict_value: dict[typing.Any, list[typing.Any]] = {} if isinstance(value, (list, tuple)): # Convert list inputs like: # [("a", "123"), ("a", "456"), ("b", "789")] # To a dict representation, like: # {"a": ["123", "456"], "b": ["789"]} for item in value: dict_value.setdefault(item[0], []).append(item[1]) else: # Convert dict inputs like: # {"a": "123", "b": ["456", "789"]} # To dict inputs where values are always lists, like: # {"a": ["123"], "b": ["456", "789"]} dict_value = { k: list(v) if isinstance(v, (list, tuple)) else [v] for k, v in value.items() }
# Ensure that keys and values are neatly coerced to strings. # We coerce values `True` and `False` to JSON-like "true" and "false" # representations, and coerce `None` values to the empty string. self._dict = { str(k): [primitive_value_to_str(item) for item in v] for k, v in dict_value.items() }
def keys(self) -> typing.KeysView[str]: """ Return all the keys in the query params.
Usage:
q = httpx.QueryParams("a=123&a=456&b=789") assert list(q.keys()) == ["a", "b"] """ return self._dict.keys()
def values(self) -> typing.ValuesView[str]: """ Return all the values in the query params. If a key occurs more than once only the first item for that key is returned.
Usage:
q = httpx.QueryParams("a=123&a=456&b=789") assert list(q.values()) == ["123", "789"] """ return {k: v[0] for k, v in self._dict.items()}.values()
def items(self) -> typing.ItemsView[str, str]: """ Return all items in the query params. If a key occurs more than once only the first item for that key is returned.
Usage:
q = httpx.QueryParams("a=123&a=456&b=789") assert list(q.items()) == [("a", "123"), ("b", "789")] """ return {k: v[0] for k, v in self._dict.items()}.items()
def multi_items(self) -> list[tuple[str, str]]: """ Return all items in the query params. Allow duplicate keys to occur.
Usage:
q = httpx.QueryParams("a=123&a=456&b=789") assert list(q.multi_items()) == [("a", "123"), ("a", "456"), ("b", "789")] """ multi_items: list[tuple[str, str]] = [] for k, v in self._dict.items(): multi_items.extend([(k, i) for i in v]) return multi_items
def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any: """ Get a value from the query param for a given key. If the key occurs more than once, then only the first value is returned.
Usage:
q = httpx.QueryParams("a=123&a=456&b=789") assert q.get("a") == "123" """ if key in self._dict: return self._dict[str(key)][0] return default
def get_list(self, key: str) -> list[str]: """ Get all values from the query param for a given key.
Usage:
q = httpx.QueryParams("a=123&a=456&b=789") assert q.get_list("a") == ["123", "456"] """ return list(self._dict.get(str(key), []))
def set(self, key: str, value: typing.Any = None) -> QueryParams: """ Return a new QueryParams instance, setting the value of a key.
Usage:
q = httpx.QueryParams("a=123") q = q.set("a", "456") assert q == httpx.QueryParams("a=456") """ q = QueryParams() q._dict = dict(self._dict) q._dict[str(key)] = [primitive_value_to_str(value)] return q
def add(self, key: str, value: typing.Any = None) -> QueryParams: """ Return a new QueryParams instance, setting or appending the value of a key.
Usage:
q = httpx.QueryParams("a=123") q = q.add("a", "456") assert q == httpx.QueryParams("a=123&a=456") """ q = QueryParams() q._dict = dict(self._dict) q._dict[str(key)] = q.get_list(key) + [primitive_value_to_str(value)] return q
def remove(self, key: str) -> QueryParams: """ Return a new QueryParams instance, removing the value of a key.
Usage:
q = httpx.QueryParams("a=123") q = q.remove("a") assert q == httpx.QueryParams("") """ q = QueryParams() q._dict = dict(self._dict) q._dict.pop(str(key), None) return q
def merge(self, params: QueryParamTypes | None = None) -> QueryParams: """ Return a new QueryParams instance, updated with.
Usage:
q = httpx.QueryParams("a=123") q = q.merge({"b": "456"}) assert q == httpx.QueryParams("a=123&b=456")
q = httpx.QueryParams("a=123") q = q.merge({"a": "456", "b": "789"}) assert q == httpx.QueryParams("a=456&b=789") """ q = QueryParams(params) q._dict = {**self._dict, **q._dict} return q
def __getitem__(self, key: typing.Any) -> str: return self._dict[key][0]
def __contains__(self, key: typing.Any) -> bool: return key in self._dict
def __iter__(self) -> typing.Iterator[typing.Any]: return iter(self.keys())
def __len__(self) -> int: return len(self._dict)
def __bool__(self) -> bool: return bool(self._dict)
def __hash__(self) -> int: return hash(str(self))
def __eq__(self, other: typing.Any) -> bool: if not isinstance(other, self.__class__): return False return sorted(self.multi_items()) == sorted(other.multi_items())
def __str__(self) -> str: return urlencode(self.multi_items())
def __repr__(self) -> str: class_name = self.__class__.__name__ query_string = str(self) return f"{class_name}({query_string!r})"
def update(self, params: QueryParamTypes | None = None) -> None: raise RuntimeError( "QueryParams are immutable since 0.18.0. " "Use `q = q.merge(...)` to create an updated copy." )
def __setitem__(self, key: str, value: str) -> None: raise RuntimeError( "QueryParams are immutable since 0.18.0. " "Use `q = q.set(key, value)` to create an updated copy." )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242from __future__ import annotations
import ipaddressimport osimport reimport typingfrom urllib.request import getproxies
from ._types import PrimitiveData
if typing.TYPE_CHECKING: # pragma: no cover from ._urls import URL
def primitive_value_to_str(value: PrimitiveData) -> str: """ Coerce a primitive data type into a string value.
Note that we prefer JSON-style 'true'/'false' for boolean values here. """ if value is True: return "true" elif value is False: return "false" elif value is None: return "" return str(value)
def get_environment_proxies() -> dict[str, str | None]: """Gets proxy information from the environment"""
# urllib.request.getproxies() falls back on System # Registry and Config for proxies on Windows and macOS. # We don't want to propagate non-HTTP proxies into # our configuration such as 'TRAVIS_APT_PROXY'. proxy_info = getproxies() mounts: dict[str, str | None] = {}
for scheme in ("http", "https", "all"): if proxy_info.get(scheme): hostname = proxy_info[scheme] mounts[f"{scheme}://"] = ( hostname if "://" in hostname else f"http://{hostname}" )
no_proxy_hosts = [host.strip() for host in proxy_info.get("no", "").split(",")] for hostname in no_proxy_hosts: # See https://curl.haxx.se/libcurl/c/CURLOPT_NOPROXY.html for details # on how names in `NO_PROXY` are handled. if hostname == "*": # If NO_PROXY=* is used or if "*" occurs as any one of the comma # separated hostnames, then we should just bypass any information # from HTTP_PROXY, HTTPS_PROXY, ALL_PROXY, and always ignore # proxies. return {} elif hostname: # NO_PROXY=.google.com is marked as "all://*.google.com, # which disables "www.google.com" but not "google.com" # NO_PROXY=google.com is marked as "all://*google.com, # which disables "www.google.com" and "google.com". # (But not "wwwgoogle.com") # NO_PROXY can include domains, IPv6, IPv4 addresses and "localhost" # NO_PROXY=example.com,::1,localhost,192.168.0.0/16 if "://" in hostname: mounts[hostname] = None elif is_ipv4_hostname(hostname): mounts[f"all://{hostname}"] = None elif is_ipv6_hostname(hostname): mounts[f"all://[{hostname}]"] = None elif hostname.lower() == "localhost": mounts[f"all://{hostname}"] = None else: mounts[f"all://*{hostname}"] = None
return mounts
def to_bytes(value: str | bytes, encoding: str = "utf-8") -> bytes: return value.encode(encoding) if isinstance(value, str) else value
def to_str(value: str | bytes, encoding: str = "utf-8") -> str: return value if isinstance(value, str) else value.decode(encoding)
def to_bytes_or_str(value: str, match_type_of: typing.AnyStr) -> typing.AnyStr: return value if isinstance(match_type_of, str) else value.encode()
def unquote(value: str) -> str: return value[1:-1] if value[0] == value[-1] == '"' else value
def peek_filelike_length(stream: typing.Any) -> int | None: """ Given a file-like stream object, return its length in number of bytes without reading it into memory. """ try: # Is it an actual file? fd = stream.fileno() # Yup, seems to be an actual file. length = os.fstat(fd).st_size except (AttributeError, OSError): # No... Maybe it's something that supports random access, like `io.BytesIO`? try: # Assuming so, go to end of stream to figure out its length, # then put it back in place. offset = stream.tell() length = stream.seek(0, os.SEEK_END) stream.seek(offset) except (AttributeError, OSError): # Not even that? Sorry, we're doomed... return None
return length
class URLPattern: """ A utility class currently used for making lookups against proxy keys...
# Wildcard matching... >>> pattern = URLPattern("all://") >>> pattern.matches(httpx.URL("http://example.com")) True
# Witch scheme matching... >>> pattern = URLPattern("https://") >>> pattern.matches(httpx.URL("https://example.com")) True >>> pattern.matches(httpx.URL("http://example.com")) False
# With domain matching... >>> pattern = URLPattern("https://example.com") >>> pattern.matches(httpx.URL("https://example.com")) True >>> pattern.matches(httpx.URL("http://example.com")) False >>> pattern.matches(httpx.URL("https://other.com")) False
# Wildcard scheme, with domain matching... >>> pattern = URLPattern("all://example.com") >>> pattern.matches(httpx.URL("https://example.com")) True >>> pattern.matches(httpx.URL("http://example.com")) True >>> pattern.matches(httpx.URL("https://other.com")) False
# With port matching... >>> pattern = URLPattern("https://example.com:1234") >>> pattern.matches(httpx.URL("https://example.com:1234")) True >>> pattern.matches(httpx.URL("https://example.com")) False """
def __init__(self, pattern: str) -> None: from ._urls import URL
if pattern and ":" not in pattern: raise ValueError( f"Proxy keys should use proper URL forms rather " f"than plain scheme strings. " f'Instead of "{pattern}", use "{pattern}://"' )
url = URL(pattern) self.pattern = pattern self.scheme = "" if url.scheme == "all" else url.scheme self.host = "" if url.host == "*" else url.host self.port = url.port if not url.host or url.host == "*": self.host_regex: typing.Pattern[str] | None = None elif url.host.startswith("*."): # *.example.com should match "www.example.com", but not "example.com" domain = re.escape(url.host[2:]) self.host_regex = re.compile(f"^.+\\.{domain}$") elif url.host.startswith("*"): # *example.com should match "www.example.com" and "example.com" domain = re.escape(url.host[1:]) self.host_regex = re.compile(f"^(.+\\.)?{domain}$") else: # example.com should match "example.com" but not "www.example.com" domain = re.escape(url.host) self.host_regex = re.compile(f"^{domain}$")
def matches(self, other: URL) -> bool: if self.scheme and self.scheme != other.scheme: return False if ( self.host and self.host_regex is not None and not self.host_regex.match(other.host) ): return False if self.port is not None and self.port != other.port: return False return True
@property def priority(self) -> tuple[int, int, int]: """ The priority allows URLPattern instances to be sortable, so that we can match from most specific to least specific. """ # URLs with a port should take priority over URLs without a port. port_priority = 0 if self.port is not None else 1 # Longer hostnames should match first. host_priority = -len(self.host) # Longer schemes should match first. scheme_priority = -len(self.scheme) return (port_priority, host_priority, scheme_priority)
def __hash__(self) -> int: return hash(self.pattern)
def __lt__(self, other: URLPattern) -> bool: return self.priority < other.priority
def __eq__(self, other: typing.Any) -> bool: return isinstance(other, URLPattern) and self.pattern == other.pattern
def is_ipv4_hostname(hostname: str) -> bool: try: ipaddress.IPv4Address(hostname.split("/")[0]) except Exception: return False return True
def is_ipv6_hostname(hostname: str) -> bool: try: ipaddress.IPv6Address(hostname.split("/")[0]) except Exception: return False return True1pip123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373Metadata-Version: 2.4Name: huggingface_hubVersion: 1.27.0Summary: Client library to download and publish models, datasets and other repos on the huggingface.co hubHome-page: https://github.com/huggingface/huggingface_hubAuthor: Hugging Face, Inc.Author-email: julien@huggingface.coLicense: Apache-2.0Keywords: model-hub machine-learning models natural-language-processing deep-learning pytorch pretrained-modelsClassifier: Intended Audience :: DevelopersClassifier: Intended Audience :: EducationClassifier: Intended Audience :: Science/ResearchClassifier: License :: OSI Approved :: Apache Software LicenseClassifier: Operating System :: OS IndependentClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: 3 :: OnlyClassifier: Programming Language :: Python :: 3.10Classifier: Programming Language :: Python :: 3.11Classifier: Programming Language :: Python :: 3.12Classifier: Programming Language :: Python :: 3.13Classifier: Programming Language :: Python :: 3.14Classifier: Topic :: Scientific/Engineering :: Artificial IntelligenceRequires-Python: >=3.10.0Description-Content-Type: text/markdownLicense-File: LICENSERequires-Dist: click<9.0.0,>=8.4.2Requires-Dist: filelock>=3.10.0Requires-Dist: fsspec>=2023.5.0Requires-Dist: hf-xet<2.0.0,>=1.5.2; platform_machine == "x86_64" or platform_machine == "amd64" or platform_machine == "AMD64" or platform_machine == "arm64" or platform_machine == "aarch64"Requires-Dist: httpx<1,>=0.23.0Requires-Dist: packaging>=20.9Requires-Dist: pyyaml>=5.1Requires-Dist: tqdm>=4.42.1Requires-Dist: typing-extensions>=4.1.0Provides-Extra: oauthRequires-Dist: authlib>=1.3.2; extra == "oauth"Requires-Dist: fastapi; extra == "oauth"Requires-Dist: httpx; extra == "oauth"Requires-Dist: itsdangerous; extra == "oauth"Provides-Extra: torchRequires-Dist: torch; extra == "torch"Requires-Dist: safetensors[torch]; extra == "torch"Provides-Extra: fastaiRequires-Dist: toml; extra == "fastai"Requires-Dist: fastai>=2.4; extra == "fastai"Requires-Dist: fastcore>=1.3.27; extra == "fastai"Provides-Extra: hf-xetRequires-Dist: hf-xet<2.0.0,>=1.5.2; extra == "hf-xet"Provides-Extra: mcpRequires-Dist: mcp>=1.8.0; extra == "mcp"Provides-Extra: testingRequires-Dist: authlib>=1.3.2; extra == "testing"Requires-Dist: fastapi; extra == "testing"Requires-Dist: httpx; extra == "testing"Requires-Dist: itsdangerous; extra == "testing"Requires-Dist: jedi; extra == "testing"Requires-Dist: Jinja2; extra == "testing"Requires-Dist: pytest>=8.4.2; extra == "testing"Requires-Dist: pytest-cov; extra == "testing"Requires-Dist: pytest-env; extra == "testing"Requires-Dist: pytest-xdist; extra == "testing"Requires-Dist: pytest-vcr; extra == "testing"Requires-Dist: pytest-asyncio; extra == "testing"Requires-Dist: pytest-rerunfailures>=16.2; extra == "testing"Requires-Dist: pytest-mock; extra == "testing"Requires-Dist: urllib3<2.0; extra == "testing"Requires-Dist: soundfile; extra == "testing"Requires-Dist: Pillow; extra == "testing"Requires-Dist: numpy; extra == "testing"Requires-Dist: duckdb; extra == "testing"Requires-Dist: fastapi; extra == "testing"Provides-Extra: gradioRequires-Dist: gradio>=5.0.0; extra == "gradio"Requires-Dist: requests; extra == "gradio"Provides-Extra: typingRequires-Dist: typing-extensions>=4.8.0; extra == "typing"Requires-Dist: types-PyYAML; extra == "typing"Requires-Dist: types-simplejson; extra == "typing"Requires-Dist: types-toml; extra == "typing"Requires-Dist: types-tqdm; extra == "typing"Requires-Dist: types-urllib3; extra == "typing"Provides-Extra: qualityRequires-Dist: ruff>=0.9.0; extra == "quality"Requires-Dist: mypy==1.15.0; extra == "quality"Requires-Dist: libcst>=1.4.0; extra == "quality"Requires-Dist: ty; extra == "quality"Provides-Extra: allRequires-Dist: authlib>=1.3.2; extra == "all"Requires-Dist: fastapi; extra == "all"Requires-Dist: httpx; extra == "all"Requires-Dist: itsdangerous; extra == "all"Requires-Dist: jedi; extra == "all"Requires-Dist: Jinja2; extra == "all"Requires-Dist: pytest>=8.4.2; extra == "all"Requires-Dist: pytest-cov; extra == "all"Requires-Dist: pytest-env; extra == "all"Requires-Dist: pytest-xdist; extra == "all"Requires-Dist: pytest-vcr; extra == "all"Requires-Dist: pytest-asyncio; extra == "all"Requires-Dist: pytest-rerunfailures>=16.2; extra == "all"Requires-Dist: pytest-mock; extra == "all"Requires-Dist: urllib3<2.0; extra == "all"Requires-Dist: soundfile; extra == "all"Requires-Dist: Pillow; extra == "all"Requires-Dist: numpy; extra == "all"Requires-Dist: duckdb; extra == "all"Requires-Dist: fastapi; extra == "all"Requires-Dist: ruff>=0.9.0; extra == "all"Requires-Dist: mypy==1.15.0; extra == "all"Requires-Dist: libcst>=1.4.0; extra == "all"Requires-Dist: ty; extra == "all"Requires-Dist: typing-extensions>=4.8.0; extra == "all"Requires-Dist: types-PyYAML; extra == "all"Requires-Dist: types-simplejson; extra == "all"Requires-Dist: types-toml; extra == "all"Requires-Dist: types-tqdm; extra == "all"Requires-Dist: types-urllib3; extra == "all"Provides-Extra: devRequires-Dist: authlib>=1.3.2; extra == "dev"Requires-Dist: fastapi; extra == "dev"Requires-Dist: httpx; extra == "dev"Requires-Dist: itsdangerous; extra == "dev"Requires-Dist: jedi; extra == "dev"Requires-Dist: Jinja2; extra == "dev"Requires-Dist: pytest>=8.4.2; extra == "dev"Requires-Dist: pytest-cov; extra == "dev"Requires-Dist: pytest-env; extra == "dev"Requires-Dist: pytest-xdist; extra == "dev"Requires-Dist: pytest-vcr; extra == "dev"Requires-Dist: pytest-asyncio; extra == "dev"Requires-Dist: pytest-rerunfailures>=16.2; extra == "dev"Requires-Dist: pytest-mock; extra == "dev"Requires-Dist: urllib3<2.0; extra == "dev"Requires-Dist: soundfile; extra == "dev"Requires-Dist: Pillow; extra == "dev"Requires-Dist: numpy; extra == "dev"Requires-Dist: duckdb; extra == "dev"Requires-Dist: fastapi; extra == "dev"Requires-Dist: ruff>=0.9.0; extra == "dev"Requires-Dist: mypy==1.15.0; extra == "dev"Requires-Dist: libcst>=1.4.0; extra == "dev"Requires-Dist: ty; extra == "dev"Requires-Dist: typing-extensions>=4.8.0; extra == "dev"Requires-Dist: types-PyYAML; extra == "dev"Requires-Dist: types-simplejson; extra == "dev"Requires-Dist: types-toml; extra == "dev"Requires-Dist: types-tqdm; extra == "dev"Requires-Dist: types-urllib3; extra == "dev"Dynamic: authorDynamic: author-emailDynamic: classifierDynamic: descriptionDynamic: description-content-typeDynamic: home-pageDynamic: keywordsDynamic: licenseDynamic: license-fileDynamic: provides-extraDynamic: requires-distDynamic: requires-pythonDynamic: summary
<p align="center"> <picture> <source media="(prefers-color-scheme: dark)" srcset="https://huggingface.co/datasets/huggingface/documentation-images/raw/main/huggingface_hub-dark.svg"> <source media="(prefers-color-scheme: light)" srcset="https://huggingface.co/datasets/huggingface/documentation-images/raw/main/huggingface_hub.svg"> <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%"> </picture> <br/> <br/></p>
<p align="center"> <i>The official CLI and Python client for the Hugging Face Hub.</i> <br/> <a href="#what-is-huggingface_hub">About</a> · <a href="https://huggingface.co/docs/huggingface_hub">Documentation</a> · <a href="https://huggingface.co/docs/huggingface_hub/en/installation">Install</a> · <a href="https://huggingface.co/docs/huggingface_hub/en/guides/cli">CLI Guide</a> · <a href="https://github.com/huggingface/huggingface_hub/blob/main/CONTRIBUTING.md">Contributing</a></p>
<p align="center"> <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> <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> <a href="https://github.com/huggingface/huggingface_hub"><img alt="PyPi version" src="https://img.shields.io/pypi/pyversions/huggingface_hub.svg"></a> <a href="https://pypi.org/project/huggingface-hub"><img alt="PyPI - Downloads" src="https://img.shields.io/pypi/dm/huggingface_hub"></a> <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></p>
<h4 align="center"> <p> <b>English</b> | <a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_de.md">Deutsch</a> | <a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_fr.md">Français</a> | <a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_hi.md">हिंदी</a> | <a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_ko.md">한국어</a> | <a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_cn.md">中文 (简体)</a> | <a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_kn.md">ಕನ್ನಡ</a> </p></h4>
## Quick start
Install the [`hf` CLI](https://huggingface.co/docs/huggingface_hub/en/guides/cli) with the standalone installer:
```bash# On macOS and Linux.curl -LsSf https://hf.co/cli/install.sh | bash```
```powershell# On Windows.powershell -ExecutionPolicy ByPass -c "irm https://hf.co/cli/install.ps1 | iex"```
Log in, then start working with the Hub:
```bash# Log in (use --token $HF_TOKEN in non-interactive environments)hf auth login
# Find models served by Inference Providershf models ls --warm
# Download a modelhf download Qwen/Qwen3-0.6B
# Upload files to your own repohf upload username/my-cool-model ./model.safetensors
# Sync a local folder to a storage buckethf buckets sync ./checkpoints hf://buckets/username/my-bucket
# Run a job on Hugging Face infrastructurehf jobs run python:3.12 python -c "print('Hello from the cloud!')"
# Discover everything elsehf --help```
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.
## What is `huggingface_hub`?
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:
- [Download files](https://huggingface.co/docs/huggingface_hub/en/guides/download) from the Hub.- [Upload files](https://huggingface.co/docs/huggingface_hub/en/guides/upload) to the Hub.- [Manage your repositories](https://huggingface.co/docs/huggingface_hub/en/guides/repository).- [Run Inference](https://huggingface.co/docs/huggingface_hub/en/guides/inference) on deployed models.- [Run Jobs](https://huggingface.co/docs/huggingface_hub/en/guides/jobs) on Hugging Face infrastructure.- [Search](https://huggingface.co/docs/huggingface_hub/en/guides/search) for models, datasets and Spaces.- [Share Model Cards](https://huggingface.co/docs/huggingface_hub/en/guides/model-cards) to document your models.- [Engage with the community](https://huggingface.co/docs/huggingface_hub/en/guides/community) through PRs and comments.- Do all of the above from the terminal with the [`hf` CLI](https://huggingface.co/docs/huggingface_hub/en/guides/cli).
## Built for humans and AI agents
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:
```bash# for Codex, Cursor, OpenCode, Pi and other agents that load skills from `.agents/skills`hf skills add# includes the above + Claude Codehf skills add --claude```
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).
## Use the Python library
Install the `huggingface_hub` package with [pip](https://pypi.org/project/huggingface-hub/) (this also installs the `hf` CLI):
```bashpip install huggingface_hub```
We recommend using [`uv`](https://docs.astral.sh/uv/) for a fast and reliable install:
```bashuv pip install huggingface_hub```
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:
```bashpip install "huggingface_hub[mcp]"```
To learn more about installation and optional dependencies, check out the [installation guide](https://huggingface.co/docs/huggingface_hub/en/installation).
### Download files
Download a single file
```pyfrom huggingface_hub import hf_hub_download
hf_hub_download(repo_id="zai-org/GLM-5.2", filename="config.json")```
Or an entire repository
```pyfrom huggingface_hub import snapshot_download
snapshot_download("sentence-transformers/all-MiniLM-L6-v2")```
Files will be downloaded in a local cache folder. More details in [this guide](https://huggingface.co/docs/huggingface_hub/en/guides/manage-cache).
### Create a repository
```pyfrom huggingface_hub import create_repo
create_repo(repo_id="super-cool-model")```
### Upload files
Upload a single file
```pyfrom huggingface_hub import upload_file
upload_file( path_or_fileobj="/home/lysandre/dummy-test/README.md", path_in_repo="README.md", repo_id="lysandre/test-model",)```
Or an entire folder
```pyfrom huggingface_hub import upload_folder
upload_folder( folder_path="/path/to/local/space", repo_id="username/my-cool-space", repo_type="space",)```
More details in the [upload guide](https://huggingface.co/docs/huggingface_hub/en/guides/upload).
## Integrating with the Hub.
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).
The advantages are:
- Free model or dataset hosting for libraries and their users.- 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.- In-browser widgets to play with the uploaded models.- Anyone can upload a new model for your library, they just need to add the corresponding tag for the model to be discoverable.- Fast downloads! We use Cloudfront (a CDN) to geo-replicate downloads so they're blazing fast from anywhere on the globe.- Usage stats and more features to come.
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.
## Contributions (feature requests, bugs, etc.) are super welcome 💙💚💛💜🧡❤️
Everyone is welcome to contribute, and we value everybody's contribution. Code is not the only way to help the community.Answering questions, helping others, reaching out and improving the documentations are immensely valuable to the community.We wrote a [contribution guide](https://github.com/huggingface/huggingface_hub/blob/main/CONTRIBUTING.md) to summarizehow to get started to contribute to this repository.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380../../../bin/hf,sha256=9r2GE6ilZMvWmyfzj1KZx1-a-qGRArEmQA-_VotIhug,311
../../../bin/huggingface-cli,sha256=BVUY5rR_qa4LD9H3D8JYXg5d1Iq4FeIOiuSWj0jkTAs,323
../../../bin/tiny-agents,sha256=cYH0RSZZvdPEkZ2SfaSD1UnmgHRpHM_p05W8hZPZ26U,321
huggingface_hub-1.27.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
huggingface_hub-1.27.0.dist-info/METADATA,sha256=kdWT-K9bIzIoJpph_rdX1f5gcwxRWXkZ5PTijS2m2co,16314
huggingface_hub-1.27.0.dist-info/RECORD,,
huggingface_hub-1.27.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
huggingface_hub-1.27.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
huggingface_hub-1.27.0.dist-info/entry_points.txt,sha256=zP7F_bBSdircPQFysHQZ9F3Lcn5_dCSOEZxVlGCsG0w,212
huggingface_hub-1.27.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
huggingface_hub-1.27.0.dist-info/top_level.txt,sha256=8KzlQJAY4miUvjAssOAJodqKOw3harNzuiwGQ9qLSSk,16
huggingface_hub/__init__.py,sha256=eZLm_W9SknOwodC709pz-SVyWudPEfO0-yrtIlL1FMc,60623
huggingface_hub/__pycache__/__init__.cpython-314.pyc,,
huggingface_hub/__pycache__/_buckets.cpython-314.pyc,,
huggingface_hub/__pycache__/_commit_api.cpython-314.pyc,,
huggingface_hub/__pycache__/_commit_scheduler.cpython-314.pyc,,
huggingface_hub/__pycache__/_dataset_viewer.cpython-314.pyc,,
huggingface_hub/__pycache__/_eval_results.cpython-314.pyc,,
huggingface_hub/__pycache__/_inference_endpoints.cpython-314.pyc,,
huggingface_hub/__pycache__/_jobs_api.cpython-314.pyc,,
huggingface_hub/__pycache__/_local_folder.cpython-314.pyc,,
huggingface_hub/__pycache__/_login.cpython-314.pyc,,
huggingface_hub/__pycache__/_oauth.cpython-314.pyc,,
huggingface_hub/__pycache__/_oidc.cpython-314.pyc,,
huggingface_hub/__pycache__/_revision.cpython-314.pyc,,
huggingface_hub/__pycache__/_sandbox.cpython-314.pyc,,
huggingface_hub/__pycache__/_sandbox_cache.cpython-314.pyc,,
huggingface_hub/__pycache__/_snapshot_download.cpython-314.pyc,,
huggingface_hub/__pycache__/_space_api.cpython-314.pyc,,
huggingface_hub/__pycache__/_tensorboard_logger.cpython-314.pyc,,
huggingface_hub/__pycache__/_tree_cache.cpython-314.pyc,,
huggingface_hub/__pycache__/_upload_large_folder.cpython-314.pyc,,
huggingface_hub/__pycache__/_upload_pipeline.cpython-314.pyc,,
huggingface_hub/__pycache__/_webhooks_payload.cpython-314.pyc,,
huggingface_hub/__pycache__/_webhooks_server.cpython-314.pyc,,
huggingface_hub/__pycache__/community.cpython-314.pyc,,
huggingface_hub/__pycache__/constants.cpython-314.pyc,,
huggingface_hub/__pycache__/dataclasses.cpython-314.pyc,,
huggingface_hub/__pycache__/errors.cpython-314.pyc,,
huggingface_hub/__pycache__/fastai_utils.cpython-314.pyc,,
huggingface_hub/__pycache__/file_download.cpython-314.pyc,,
huggingface_hub/__pycache__/hf_api.cpython-314.pyc,,
huggingface_hub/__pycache__/hf_file_system.cpython-314.pyc,,
huggingface_hub/__pycache__/hub_mixin.cpython-314.pyc,,
huggingface_hub/__pycache__/lfs.cpython-314.pyc,,
huggingface_hub/__pycache__/repocard.cpython-314.pyc,,
huggingface_hub/__pycache__/repocard_data.cpython-314.pyc,,
huggingface_hub/_buckets.py,sha256=XyLbsLzS2fpQz0aAIjKzV-1YbQ4XYZ4-HXQTVq0TXoU,45311
huggingface_hub/_commit_api.py,sha256=lalqhJKl8_RWVHgAdnzZKG_fy4E7fbyHIev6nDLrj4w,45378
huggingface_hub/_commit_scheduler.py,sha256=VG3zjb7xb66NrFMq_pB9dWIsoqSPoF6CntovV7vUiWg,14684
huggingface_hub/_dataset_viewer.py,sha256=LE9k4s0WJ0JNdriJ8L6qV_-xfbUVC1VEh7CBd0jOjLI,5675
huggingface_hub/_eval_results.py,sha256=Og7p7bCl2HQG6ZWlSDyir-CRTXjNWPu3S3q65cTGffs,8126
huggingface_hub/_hot_reload/__init__.py,sha256=nQEuyVZLAS_463Dff1JH5MorTpkYsBVFCyPhYWY3UyI,606
huggingface_hub/_hot_reload/__pycache__/__init__.cpython-314.pyc,,
huggingface_hub/_hot_reload/__pycache__/client.cpython-314.pyc,,
huggingface_hub/_hot_reload/__pycache__/sse_client.cpython-314.pyc,,
huggingface_hub/_hot_reload/__pycache__/types.cpython-314.pyc,,
huggingface_hub/_hot_reload/client.py,sha256=Ax7qT4CUi5wrg3mDzqkAG8ZzDsCwdcIIS1FIXK0SqD8,4269
huggingface_hub/_hot_reload/sse_client.py,sha256=49kmsB2P9sxgbZ16ed6F4aLDs3rsHrNpbp6iKlvF90c,4948
huggingface_hub/_hot_reload/types.py,sha256=d3AOJCLUxT41Fhz4jUrFevm9bfpooe_3PQhpBdgNYSs,2725
huggingface_hub/_inference_endpoints.py,sha256=FWSixNvBQlqLU4Z0yUC7Ch7a8V8Ci6eJBAD4pbTMKhk,18424
huggingface_hub/_jobs_api.py,sha256=f7NhziUMH6jWpWClnLPFx4XIZ0xVGAdTGfBxIn2IVy0,23679
huggingface_hub/_local_folder.py,sha256=KsetQw7pW0ZwFI2RLQPqVq0ZnORogPkBwRYcbRqNd5o,20654
huggingface_hub/_login.py,sha256=wAMdhqMSSh3GBJDozodmk4IIsAvb9J6LaLY9KnXFoyY,21818
huggingface_hub/_oauth.py,sha256=S8evEd8JLJHz-JiSjGH4WiIi_A7oDox_xH7E9rN1Jic,18628
huggingface_hub/_oidc.py,sha256=3kcCLavWQ5FQOwizUPzLaBb1ft2FIJo0bSXL24S3r4U,7098
huggingface_hub/_revision.py,sha256=NCmIVCR-_HjmxeYiDntcsTU-bLSfJLq8PLvvG8UhZtI,1696
huggingface_hub/_sandbox.py,sha256=XEXZi5S3rYyw_o3td3rB0xOVdmhpAlnyUykBsAw9KP8,80148
huggingface_hub/_sandbox_cache.py,sha256=UYpvHOWZj7CRhacYs5Ot-5N1wFcAapiAyniYdoX-jX8,5742
huggingface_hub/_snapshot_download.py,sha256=fOte9xmpaok0LGbubJZhSRd7t0nn-p00mWMebCx56qc,31029
huggingface_hub/_space_api.py,sha256=MF3ezhgl0Vpt3RP1wuwZ7VI9_rSyIlIJ5SmDzIwQlcQ,13424
huggingface_hub/_tensorboard_logger.py,sha256=GA-LhoG4Z-0Zq7w5B9vTIDJbWUkAhiG2d8a-ktlwGDY,8377
huggingface_hub/_tree_cache.py,sha256=M7CHMKhwY1cuhe9fb3WT1X8jmd9BXa2Sx_HS4TIXFgI,5843
huggingface_hub/_upload_large_folder.py,sha256=BWA1zyOK9W_3YUerX9YWQa3wAYtHRe_ypgsO79JEkqo,31235
huggingface_hub/_upload_pipeline.py,sha256=6YaQNtubAEaPyRoRBjPQrmsdSnCExg2KzfBuhjNqI5I,28994
huggingface_hub/_webhooks_payload.py,sha256=B9zqljcm20DGeVxJKba570i6RP-cR9CEupMGBuNDHHA,3544
huggingface_hub/_webhooks_server.py,sha256=VXOk3FHkbIc28phxknJfaFy5B_EoKOKihoCKyOaWZQk,15767
huggingface_hub/cli/__init__.py,sha256=tWu3Is-m2tlJwXhM_vT2mPRgpnt9KhU9qvw5aRsnjU0,664
huggingface_hub/cli/__pycache__/__init__.cpython-314.pyc,,
huggingface_hub/cli/__pycache__/_city_game.cpython-314.pyc,,
huggingface_hub/cli/__pycache__/_cli_utils.cpython-314.pyc,,
huggingface_hub/cli/__pycache__/_completion.cpython-314.pyc,,
huggingface_hub/cli/__pycache__/_cp.cpython-314.pyc,,
huggingface_hub/cli/__pycache__/_errors.cpython-314.pyc,,
huggingface_hub/cli/__pycache__/_file_listing.cpython-314.pyc,,
huggingface_hub/cli/__pycache__/_framework.cpython-314.pyc,,
huggingface_hub/cli/__pycache__/_help_formatter.cpython-314.pyc,,
huggingface_hub/cli/__pycache__/_output.cpython-314.pyc,,
huggingface_hub/cli/__pycache__/_skills.cpython-314.pyc,,
huggingface_hub/cli/__pycache__/auth.cpython-314.pyc,,
huggingface_hub/cli/__pycache__/buckets.cpython-314.pyc,,
huggingface_hub/cli/__pycache__/cache.cpython-314.pyc,,
huggingface_hub/cli/__pycache__/collections.cpython-314.pyc,,
huggingface_hub/cli/__pycache__/datasets.cpython-314.pyc,,
huggingface_hub/cli/__pycache__/deprecated_cli.cpython-314.pyc,,
huggingface_hub/cli/__pycache__/discussions.cpython-314.pyc,,
huggingface_hub/cli/__pycache__/download.cpython-314.pyc,,
huggingface_hub/cli/__pycache__/extensions.cpython-314.pyc,,
huggingface_hub/cli/__pycache__/hf.cpython-314.pyc,,
huggingface_hub/cli/__pycache__/inference_endpoints.cpython-314.pyc,,
huggingface_hub/cli/__pycache__/jobs.cpython-314.pyc,,
huggingface_hub/cli/__pycache__/lfs.cpython-314.pyc,,
huggingface_hub/cli/__pycache__/models.cpython-314.pyc,,
huggingface_hub/cli/__pycache__/papers.cpython-314.pyc,,
huggingface_hub/cli/__pycache__/repo_files.cpython-314.pyc,,
huggingface_hub/cli/__pycache__/repos.cpython-314.pyc,,
huggingface_hub/cli/__pycache__/sandbox.cpython-314.pyc,,
huggingface_hub/cli/__pycache__/skills.cpython-314.pyc,,
huggingface_hub/cli/__pycache__/spaces.cpython-314.pyc,,
huggingface_hub/cli/__pycache__/system.cpython-314.pyc,,
huggingface_hub/cli/__pycache__/upload.cpython-314.pyc,,
huggingface_hub/cli/__pycache__/upload_large_folder.cpython-314.pyc,,
huggingface_hub/cli/__pycache__/webhooks.cpython-314.pyc,,
huggingface_hub/cli/_city_game.py,sha256=2qkC9dCtPwf4-aqrnbN-vApf0YqIcGGjn2v-etrTfqg,20585
huggingface_hub/cli/_cli_utils.py,sha256=uFCEHDWmxTri9ei1kmN4t4ybdm4wO5Cj0e6DvLWWFao,41824
huggingface_hub/cli/_completion.py,sha256=BDP6Vob9TLFp6K3lr0XOY98FyD-rm22KrjwsO_YGNbE,3759
huggingface_hub/cli/_cp.py,sha256=Z-2Z_tBs1e4XBqRO5R9QnabU4qTi9HDlbA52jTBaCkY,10436
huggingface_hub/cli/_errors.py,sha256=X0rUTO-3eCK5v_MLGEza1BxcuXGccPY-h7ShzmuQc34,5907
huggingface_hub/cli/_file_listing.py,sha256=h_dTEphSqtvknzqJ_9cIK3Cjlz5M6cycYD3cqUW9Fn0,7986
huggingface_hub/cli/_framework.py,sha256=HqfAEYGWRSjKABAZi2zVNgryyU9QKW8u-tRXfR_4nQ8,27364
huggingface_hub/cli/_help_formatter.py,sha256=-vsa3HfHQFkKWms77EGyp9i22t44ETmVt2L-e8qP-KM,1288
huggingface_hub/cli/_output.py,sha256=OxFrvAcDU1TRDV0AbNh4EI1P6tqifSeVT-yqfF92U_0,14754
huggingface_hub/cli/_skills.py,sha256=s9Q4o4AIerDyLNuGzUB1ISXANQPgSiAs2CRcAY4NckA,15135
huggingface_hub/cli/auth.py,sha256=Ew79M60pTMCnS1ewKVK3fd8ZyfHrNjREOmNWuFXy37M,6056
huggingface_hub/cli/buckets.py,sha256=J8xMP88fQ6ri3f65Z8XEImI2GNA4KKWloLJJQCBezZw,21062
huggingface_hub/cli/cache.py,sha256=2T0oTYXsrtcJxhQENSpXnYYNUkagsvvdrf5gbCACBjA,28574
huggingface_hub/cli/collections.py,sha256=Ed41zJqrvK-AWkHdkeHWm_aJKR_ZeNIovCGvWG04itk,10120
huggingface_hub/cli/datasets.py,sha256=X1xMJTFhHH5NJtmjTS6NN1g4ffai6Abh_obDEJM5mvo,10497
huggingface_hub/cli/deprecated_cli.py,sha256=vAK_CR4NE9uzNJ0I59SyBnIln5nlypG4CPoohMoPMVg,1090
huggingface_hub/cli/discussions.py,sha256=obvvN4mtsFnfMs67YTZaMvHkVaM6A-FYr5n-wGkF_jE,14029
huggingface_hub/cli/download.py,sha256=o6fMKJoNQMxCm1RQUnX3blihJ17mantxkf0F68rZIxs,9669
huggingface_hub/cli/extensions.py,sha256=qNM1DmzcQXt8kPWQfISc8Pvyku8BxAs-BOVP6sKRBOM,25572
huggingface_hub/cli/hf.py,sha256=84sV7zWF5SB7Q48FMXpA9XwKsMFGaCAzNklrkV7l-vQ,5549
huggingface_hub/cli/inference_endpoints.py,sha256=F-td5VCPrzgBZbkRwc6HhasJDrJDbLmreHoe4nTgktA,18820
huggingface_hub/cli/jobs.py,sha256=EVGuxn2GZqkQolHib98PztJeJ64Opq-MjgIub2WTYb4,52840
huggingface_hub/cli/lfs.py,sha256=MAccazVPX0n-ySRaPocaQUHP7oBnVrvWZt0RhmNIavs,5936
huggingface_hub/cli/models.py,sha256=eG7H5yDjCVrdL7W_-wpcl70qXlv8bC-roSEu8AroPws,10148
huggingface_hub/cli/papers.py,sha256=HvT-8zj2fi14ua6awWpHphlbJ362FEJIwSCBJRQZ_cM,4982
huggingface_hub/cli/repo_files.py,sha256=sGbD5wND3miF71ThfOBJm4xzPRUpJBeLFdvyj229NAM,2443
huggingface_hub/cli/repos.py,sha256=QS3xYKvspLhCfO5VvpORrSiF6XhSVFclmBxsacVDP2c,20192
huggingface_hub/cli/sandbox.py,sha256=rTCZf6WhoDa7UiNhsTU_4Lh5uKqKYOs73xXGAAqJGdA,18379
huggingface_hub/cli/skills.py,sha256=PcZsDiB8XC_-98c9Pw5upmof4FAAlMQPZUmRT0T8kCQ,19926
huggingface_hub/cli/spaces.py,sha256=AU655GGrQmF1s1yO8yO6ml2Z8veE7zsh4UMuR5b13RI,40800
huggingface_hub/cli/system.py,sha256=8_xaa-GLGp5tC-slv7cuFnpUQT3zozevsftYGlvFTgs,3071
huggingface_hub/cli/upload.py,sha256=P6sq8Dj81a2wazUgZEqbliRleVAAmJrf8ajFDDzHrBE,11318
huggingface_hub/cli/upload_large_folder.py,sha256=A-2qxAdLrYd8IogfZS2nDhSR1cpA_aaxhXst638WkAk,4081
huggingface_hub/cli/webhooks.py,sha256=HdpPp01c6Ece_EuNNJr46rnRki3vF4j4o9-SqYRUHnM,8550
huggingface_hub/community.py,sha256=N5OE5Rbc2BMwpNXCFOPQAwn0otqQunsXdEnSE_0J2Xo,12325
huggingface_hub/constants.py,sha256=leJzcvH7fkoIpb8LLLd21gB_j71AWSonum0MRV18a6c,13792
huggingface_hub/dataclasses.py,sha256=dkPHOKq1YVlto9TWMkeX8BnErmbZk6tVtqD1S_n6Cw8,25896
huggingface_hub/errors.py,sha256=MsfOFq6Sxo2bZ8PTPWbQb250v7aqZJO5-mmWSnX_kDk,18695
huggingface_hub/fastai_utils.py,sha256=jwKeVXH_VP0zxnOKVNQCVCkF-stH70l-bExbbrYkBKQ,16583
huggingface_hub/file_download.py,sha256=3IPbCapgC-tvlh9ErLCzA-RerYXR_1XIhDKvUOjHvKA,89165
huggingface_hub/hf_api.py,sha256=RNpf-DpBdBQQ5-lYjB8APlRaCOIcSK4lWUTMkvQiPcA,673285
huggingface_hub/hf_file_system.py,sha256=3_tdhCz6IaLVbcfk_tpbQUd7VfndHyOmbI_6q4Lq36o,60869
huggingface_hub/hub_mixin.py,sha256=ljKAtm3qQsY-ARtxY-PCFx0koFXLI37JytMrzpqfnQo,36912
huggingface_hub/inference/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
huggingface_hub/inference/__pycache__/__init__.cpython-314.pyc,,
huggingface_hub/inference/__pycache__/_client.cpython-314.pyc,,
huggingface_hub/inference/__pycache__/_common.cpython-314.pyc,,
huggingface_hub/inference/_client.py,sha256=mENW3_gqgJR_9PuC7dwFZYjkQETPvrIrw8rU74PeusQ,157692
huggingface_hub/inference/_common.py,sha256=X-fBP8s6xuNTAuQsGVIethE8dNQaa-mK7Ds54qVVDz8,14999
huggingface_hub/inference/_generated/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
huggingface_hub/inference/_generated/__pycache__/__init__.cpython-314.pyc,,
huggingface_hub/inference/_generated/__pycache__/_async_client.cpython-314.pyc,,
huggingface_hub/inference/_generated/_async_client.py,sha256=MQNKNIqcgqpGvL-HskuX1yJV6QDDuUEjM0mtZAZv8ss,160903
huggingface_hub/inference/_generated/types/__init__.py,sha256=e625ENOmTUM4uUL1eAlsZOK7CovNoGBDH-TxSNQhaC4,6869
huggingface_hub/inference/_generated/types/__pycache__/__init__.cpython-314.pyc,,
huggingface_hub/inference/_generated/types/__pycache__/audio_classification.cpython-314.pyc,,
huggingface_hub/inference/_generated/types/__pycache__/audio_to_audio.cpython-314.pyc,,
huggingface_hub/inference/_generated/types/__pycache__/automatic_speech_recognition.cpython-314.pyc,,
huggingface_hub/inference/_generated/types/__pycache__/base.cpython-314.pyc,,
huggingface_hub/inference/_generated/types/__pycache__/chat_completion.cpython-314.pyc,,
huggingface_hub/inference/_generated/types/__pycache__/depth_estimation.cpython-314.pyc,,
huggingface_hub/inference/_generated/types/__pycache__/document_question_answering.cpython-314.pyc,,
huggingface_hub/inference/_generated/types/__pycache__/feature_extraction.cpython-314.pyc,,
huggingface_hub/inference/_generated/types/__pycache__/fill_mask.cpython-314.pyc,,
huggingface_hub/inference/_generated/types/__pycache__/image_classification.cpython-314.pyc,,
huggingface_hub/inference/_generated/types/__pycache__/image_segmentation.cpython-314.pyc,,
huggingface_hub/inference/_generated/types/__pycache__/image_text_to_image.cpython-314.pyc,,
huggingface_hub/inference/_generated/types/__pycache__/image_text_to_video.cpython-314.pyc,,
huggingface_hub/inference/_generated/types/__pycache__/image_to_image.cpython-314.pyc,,
huggingface_hub/inference/_generated/types/__pycache__/image_to_text.cpython-314.pyc,,
huggingface_hub/inference/_generated/types/__pycache__/image_to_video.cpython-314.pyc,,
huggingface_hub/inference/_generated/types/__pycache__/object_detection.cpython-314.pyc,,
huggingface_hub/inference/_generated/types/__pycache__/question_answering.cpython-314.pyc,,
huggingface_hub/inference/_generated/types/__pycache__/sentence_similarity.cpython-314.pyc,,
huggingface_hub/inference/_generated/types/__pycache__/summarization.cpython-314.pyc,,
huggingface_hub/inference/_generated/types/__pycache__/table_question_answering.cpython-314.pyc,,
huggingface_hub/inference/_generated/types/__pycache__/text2text_generation.cpython-314.pyc,,
huggingface_hub/inference/_generated/types/__pycache__/text_classification.cpython-314.pyc,,
huggingface_hub/inference/_generated/types/__pycache__/text_generation.cpython-314.pyc,,
huggingface_hub/inference/_generated/types/__pycache__/text_to_audio.cpython-314.pyc,,
huggingface_hub/inference/_generated/types/__pycache__/text_to_image.cpython-314.pyc,,
huggingface_hub/inference/_generated/types/__pycache__/text_to_speech.cpython-314.pyc,,
huggingface_hub/inference/_generated/types/__pycache__/text_to_video.cpython-314.pyc,,
huggingface_hub/inference/_generated/types/__pycache__/token_classification.cpython-314.pyc,,
huggingface_hub/inference/_generated/types/__pycache__/translation.cpython-314.pyc,,
huggingface_hub/inference/_generated/types/__pycache__/video_classification.cpython-314.pyc,,
huggingface_hub/inference/_generated/types/__pycache__/visual_question_answering.cpython-314.pyc,,
huggingface_hub/inference/_generated/types/__pycache__/zero_shot_classification.cpython-314.pyc,,
huggingface_hub/inference/_generated/types/__pycache__/zero_shot_image_classification.cpython-314.pyc,,
huggingface_hub/inference/_generated/types/__pycache__/zero_shot_object_detection.cpython-314.pyc,,
huggingface_hub/inference/_generated/types/audio_classification.py,sha256=DGWEvrRPX7xpXlbYY4LMojGcULdEZFTshhNR81rTNcQ,1567
huggingface_hub/inference/_generated/types/audio_to_audio.py,sha256=2Ep4WkePL7oJwcp5nRJqApwviumGHbft9HhXE9XLHj4,891
huggingface_hub/inference/_generated/types/automatic_speech_recognition.py,sha256=X0uCj9qwAcOmlKtV3vWH5cAgLGY0PuYIy2eSH7GE1qs,5439
huggingface_hub/inference/_generated/types/base.py,sha256=EPWp1qudjeEimEAyQ-ptdxpAACoRM8tW342-Ds7pP3I,6938
huggingface_hub/inference/_generated/types/chat_completion.py,sha256=3yc06ZI0NCZzsaeoxSMWyIHqGc8Vn_6aExncuXa1llE,11100
huggingface_hub/inference/_generated/types/depth_estimation.py,sha256=5Kn4xNGJg235Cofr1lzO59eRGCuLTZun8z5t6a2do8Q,910
huggingface_hub/inference/_generated/types/document_question_answering.py,sha256=aUZcrDGexjw8Fnm2rACm_3my77V15NnQHZxj-sa7bjo,3146
huggingface_hub/inference/_generated/types/feature_extraction.py,sha256=DiO47PqwhdNta_KPDBsXfCPIL6BWNhyCLymxORlqUA0,1509
huggingface_hub/inference/_generated/types/fill_mask.py,sha256=NhEskgoiMst7U_0cV_S-wryga4_2T5LgpbyQ23vHMp0,1680
huggingface_hub/inference/_generated/types/image_classification.py,sha256=xWr4OY65EcIIhd7MI610a7xlaAVHQeydi8Gc7tlaPTU,1579
huggingface_hub/inference/_generated/types/image_segmentation.py,sha256=lZKzbn_gkSi1sYGLb9ryeRr0aDAVrfYh0H5Iiv5JNsY,1935
huggingface_hub/inference/_generated/types/image_text_to_image.py,sha256=pRQgYKXJbIpEjRBxuIE6NRDtk_km9DSTQ2s2qxkYJRM,2585
huggingface_hub/inference/_generated/types/image_text_to_video.py,sha256=MVhP8D4eYjpT3hWYkkpuiME-hWY09o7C4rIn_wmnAmY,2450
huggingface_hub/inference/_generated/types/image_to_image.py,sha256=P9TeMFSnZI_pa6DyinzDPWL0PNm_INJwsqFUEzpwIcU,2262
huggingface_hub/inference/_generated/types/image_to_text.py,sha256=DCDS0Nqi-4AuATitvZm4EgrzYQuQEQ5lzBcaHuCmHnY,4740
huggingface_hub/inference/_generated/types/image_to_video.py,sha256=iMCjiFTUza9AW_MyJ1videhYgvMY9QSzQ59kNdTE9QY,2206
huggingface_hub/inference/_generated/types/object_detection.py,sha256=zNILlyZJh59rNNfqXM5x9uprDCPfEU-bvBtabeKSMzI,1965
huggingface_hub/inference/_generated/types/question_answering.py,sha256=lIRf8DjRiAsjzWUBEsGt354SB4bvejLokf-8luHw6_o,2845
huggingface_hub/inference/_generated/types/sentence_similarity.py,sha256=eNGiO4dR-Lft9yOLE0E97jfVyOT_ExDWZW5GeJGdatU,1027
huggingface_hub/inference/_generated/types/summarization.py,sha256=5Dpt6LRteT-hO9esa3Ty_-xSL5U-zTtVZzy3iKwZRng,1472
huggingface_hub/inference/_generated/types/table_question_answering.py,sha256=bwn616XJ-eLa5JKzn3m9rZZ3z63INGEUwRSOCWlEh-4,2269
huggingface_hub/inference/_generated/types/text2text_generation.py,sha256=fotSlPWtIlp_LG26AQvNRXxU-jCUfda5PWsxCkbFeKM,1591
huggingface_hub/inference/_generated/types/text_classification.py,sha256=uamBzz4YzWQ9mb6yuriykX8r47ZHf0K3eJpOLzB2qJw,1439
huggingface_hub/inference/_generated/types/text_generation.py,sha256=FRUljypvCSQ2RaiylhlHeLJfHNy8qZvuty6SCB_zcaA,5813
huggingface_hub/inference/_generated/types/text_to_audio.py,sha256=CiaTUSBdFtOs3gGTosqyQrjCwrN8mVJLRxDDWUtwZpQ,4677
huggingface_hub/inference/_generated/types/text_to_image.py,sha256=Ju25WIDHE-1n8jlZ_udG4rpAaPYpmghR7-cDgVfuf48,1869
huggingface_hub/inference/_generated/types/text_to_speech.py,sha256=WqDzWkhZsDcjapkoFrkyjF903SKs7aHhjypsYrn8oBw,4693
huggingface_hub/inference/_generated/types/text_to_video.py,sha256=KjcDbtChwrIxIdTH6vcesUaMcjL2xjPf2nWEnHazj4Y,1756
huggingface_hub/inference/_generated/types/token_classification.py,sha256=8KRBlqgFDszaUnPMvdRkZNQaZBtDfBhKZ6SggQldQMM,1894
huggingface_hub/inference/_generated/types/translation.py,sha256=-j2PC1-qfoxvGMaKesqf5jXelqj0BDlEpfvZ7dsIEJM,1742
huggingface_hub/inference/_generated/types/video_classification.py,sha256=vfaCqp8MuRMMtGvYCX0x4-AcwEd71kPHgSYJTNIOxLQ,1668
huggingface_hub/inference/_generated/types/visual_question_answering.py,sha256=sWIB-SuEpW21oU6O5qQF3tt5PavUFsFOa8Xg4upTtek,1654
huggingface_hub/inference/_generated/types/zero_shot_classification.py,sha256=gx-7WHad7xsNa89iSKSteKHjaHrKbIyzN_nSdJN3HCY,1697
huggingface_hub/inference/_generated/types/zero_shot_image_classification.py,sha256=JZTQvcbSGrOQlWcPuJvAMT8YziDpBRn1O2RQSw507uY,1449
huggingface_hub/inference/_generated/types/zero_shot_object_detection.py,sha256=sjdpVUN5zW9aYBymLVUs6i5HVk2qkUBO9ysEjHmsXVM,1605
huggingface_hub/inference/_mcp/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
huggingface_hub/inference/_mcp/__pycache__/__init__.cpython-314.pyc,,
huggingface_hub/inference/_mcp/__pycache__/_cli_hacks.cpython-314.pyc,,
huggingface_hub/inference/_mcp/__pycache__/agent.cpython-314.pyc,,
huggingface_hub/inference/_mcp/__pycache__/cli.cpython-314.pyc,,
huggingface_hub/inference/_mcp/__pycache__/constants.cpython-314.pyc,,
huggingface_hub/inference/_mcp/__pycache__/mcp_client.cpython-314.pyc,,
huggingface_hub/inference/_mcp/__pycache__/types.cpython-314.pyc,,
huggingface_hub/inference/_mcp/__pycache__/utils.cpython-314.pyc,,
huggingface_hub/inference/_mcp/_cli_hacks.py,sha256=kIA8FfRfOWS3SrZrMTbuVOjE6yxfKfMK75Co5egTWHA,3284
huggingface_hub/inference/_mcp/agent.py,sha256=ufIzMGHore5n252hV5GZPM0ouDXIl6tv5Jl_5gHXnbg,4250
huggingface_hub/inference/_mcp/cli.py,sha256=RKdVQ_VdEgf1AL_QBCvwrsUQ0Ux4R1yerrE46DrV5C0,9642
huggingface_hub/inference/_mcp/constants.py,sha256=0Ih6ivEvG-pfF8NwErFngzP4Rof4lQoz6ms_eKSAkUI,2463
huggingface_hub/inference/_mcp/mcp_client.py,sha256=dGp8PhN6aVw4bDnuSySFSiguHUiz-nzhgv89CVdO7pI,17243
huggingface_hub/inference/_mcp/types.py,sha256=yHNfPsM9MhD06oeKdkbmrBsW-3WhUeqA26fyfRfx_bk,929
huggingface_hub/inference/_mcp/utils.py,sha256=gxSB_rBjQ6VrkApKFsxk6-UzhijxkDVNuZrsjW5pL8k,4318
huggingface_hub/inference/_providers/__init__.py,sha256=RSm8iJhLmkIvzUdAR9FGwOYuuWauK2RKVnZH_YHnK7s,9979
huggingface_hub/inference/_providers/__pycache__/__init__.cpython-314.pyc,,
huggingface_hub/inference/_providers/__pycache__/_common.cpython-314.pyc,,
huggingface_hub/inference/_providers/__pycache__/baseten.cpython-314.pyc,,
huggingface_hub/inference/_providers/__pycache__/cerebras.cpython-314.pyc,,
huggingface_hub/inference/_providers/__pycache__/cohere.cpython-314.pyc,,
huggingface_hub/inference/_providers/__pycache__/deepinfra.cpython-314.pyc,,
huggingface_hub/inference/_providers/__pycache__/fal_ai.cpython-314.pyc,,
huggingface_hub/inference/_providers/__pycache__/featherless_ai.cpython-314.pyc,,
huggingface_hub/inference/_providers/__pycache__/fireworks_ai.cpython-314.pyc,,
huggingface_hub/inference/_providers/__pycache__/groq.cpython-314.pyc,,
huggingface_hub/inference/_providers/__pycache__/hf_inference.cpython-314.pyc,,
huggingface_hub/inference/_providers/__pycache__/novita.cpython-314.pyc,,
huggingface_hub/inference/_providers/__pycache__/nscale.cpython-314.pyc,,
huggingface_hub/inference/_providers/__pycache__/openai.cpython-314.pyc,,
huggingface_hub/inference/_providers/__pycache__/ovhcloud.cpython-314.pyc,,
huggingface_hub/inference/_providers/__pycache__/publicai.cpython-314.pyc,,
huggingface_hub/inference/_providers/__pycache__/replicate.cpython-314.pyc,,
huggingface_hub/inference/_providers/__pycache__/scaleway.cpython-314.pyc,,
huggingface_hub/inference/_providers/__pycache__/together.cpython-314.pyc,,
huggingface_hub/inference/_providers/__pycache__/wavespeed.cpython-314.pyc,,
huggingface_hub/inference/_providers/__pycache__/zai_org.cpython-314.pyc,,
huggingface_hub/inference/_providers/_common.py,sha256=T3iKT6McNs7GeVfK3q-l7CBbuih2mTFcqkRluQn7GnQ,14308
huggingface_hub/inference/_providers/baseten.py,sha256=1uucLZp6HiF8OjfeFOkiuJP6WqunP_xzwk3yWPF8vGE,213
huggingface_hub/inference/_providers/cerebras.py,sha256=QOJ-1U-os7uE7p6eUnn_P_APq-yQhx28be7c3Tq2EuA,210
huggingface_hub/inference/_providers/cohere.py,sha256=P9kbIuvQ2rXI1yNmgbw5VKFFTE0huLq2k-BCyDkDico,1226
huggingface_hub/inference/_providers/deepinfra.py,sha256=4Behgf5V7FTv7CbN6vPEIYwv1z4gztdRRU-KVoOgxVE,4703
huggingface_hub/inference/_providers/fal_ai.py,sha256=Y2vo5Dl3e8EoehplwNshu8LbDT1e7V4ZyhAMqs0wXws,11705
huggingface_hub/inference/_providers/featherless_ai.py,sha256=C8OHdFpoFyA--pawLTekUmUSRq4sw_r0D-cSPekD4kE,1347
huggingface_hub/inference/_providers/fireworks_ai.py,sha256=go6XPum8u0-g768HJ_r0S4Gb445gZJxnuY_acktz-9c,1188
huggingface_hub/inference/_providers/groq.py,sha256=JTk2JV4ZOlaohho7zLAFQtk92kGVsPmLJ1hmzcwsqvQ,315
huggingface_hub/inference/_providers/hf_inference.py,sha256=z-NoYyjppc2iBPh6uVGMDikIrhnW8-dD1CJHo665ko0,9803
huggingface_hub/inference/_providers/novita.py,sha256=ATEoSdPAPLMfx3JpBc0sOyLh4upJYP6xHBuo4YEDYvg,2470
huggingface_hub/inference/_providers/nscale.py,sha256=T1L2JLI9LqYT9_YEdW76YEtxfDNtdGkoFhH-p2LmSxg,1767
huggingface_hub/inference/_providers/openai.py,sha256=wwjaaQ55xLmDsDnHpZk52xbuLoGZfWzJkFsE8AdFVaI,1054
huggingface_hub/inference/_providers/ovhcloud.py,sha256=tdmymlkbddMJKV7NRZ-tH2wymbLPFDTqUSXpWJUXyDQ,314
huggingface_hub/inference/_providers/publicai.py,sha256=1I2W6rORloB5QHSvky4njZO2XKLTwA-kPdNoauoT5rg,210
huggingface_hub/inference/_providers/replicate.py,sha256=hte0ZB2RtGFwpAuLrFp2Gbgsn3EOlccCnJkWTDTW__A,6027
huggingface_hub/inference/_providers/scaleway.py,sha256=MfIc7ZND1sPr__rOmNHZVg0VpECQo0bVyksgIm_32xQ,1174
huggingface_hub/inference/_providers/together.py,sha256=lrymDZ86n5yoR_Zz7o3AzzSePyo0s7BOBU5digLxb5o,12220
huggingface_hub/inference/_providers/wavespeed.py,sha256=MGM7Y7r2nQiH_EH0t5UE1o1fT-o3sS7RaQlicS9WHsg,5028
huggingface_hub/inference/_providers/zai_org.py,sha256=gLJZOEmCPmUZvdM7VDn2nxm4ac3veHdoMgQNR63UeWE,4739
huggingface_hub/lfs.py,sha256=8ymYNHRXgvgUUM9w0EAnC-vkSOOq_1EFJEJNoevoeE8,16588
huggingface_hub/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
huggingface_hub/repocard.py,sha256=7u7hiKjNuPYOwa3XPOPUnYPpuv4buya4WM47kVexklY,35602
huggingface_hub/repocard_data.py,sha256=f834MUSXGqrVcC02668r3ACrPzKKOAg75y3aB_hXm1U,34308
huggingface_hub/serialization/__init__.py,sha256=jCiw_vVQYW52gwVfWiqgocf2Q19kGTQlRGVpf-4SLP8,963
huggingface_hub/serialization/__pycache__/__init__.cpython-314.pyc,,
huggingface_hub/serialization/__pycache__/_base.cpython-314.pyc,,
huggingface_hub/serialization/__pycache__/_dduf.cpython-314.pyc,,
huggingface_hub/serialization/__pycache__/_torch.cpython-314.pyc,,
huggingface_hub/serialization/_base.py,sha256=8vYeDIsqgyOO3I_uii44Bkb50LsMz3kkD4gwAPzhfWU,8436
huggingface_hub/serialization/_dduf.py,sha256=FmGRg5wkXI5sNCgZgCNJFmqb_nVrrQYOHf4Lqq0d64I,15385
huggingface_hub/serialization/_torch.py,sha256=BtaCP-G3oYRP6Pj9MhI-ygBsk3JbBPnVDW9huSOgtkk,46897
huggingface_hub/templates/datasetcard_template.md,sha256=W-EMqR6wndbrnZorkVv56URWPG49l7MATGeI015kTvs,5503
huggingface_hub/templates/modelcard_template.md,sha256=4AqArS3cqdtbit5Bo-DhjcnDFR-pza5hErLLTPM4Yuc,6870
huggingface_hub/utils/__init__.py,sha256=pdVhPWWZkv0QM7kAQw7Bf259RZdPtYBLQqQwLQN-VC4,4045
huggingface_hub/utils/__pycache__/__init__.cpython-314.pyc,,
huggingface_hub/utils/__pycache__/_auth.cpython-314.pyc,,
huggingface_hub/utils/__pycache__/_cache_assets.cpython-314.pyc,,
huggingface_hub/utils/__pycache__/_cache_manager.cpython-314.pyc,,
huggingface_hub/utils/__pycache__/_chunk_utils.cpython-314.pyc,,
huggingface_hub/utils/__pycache__/_datetime.cpython-314.pyc,,
huggingface_hub/utils/__pycache__/_deprecation.cpython-314.pyc,,
huggingface_hub/utils/__pycache__/_detect_agent.cpython-314.pyc,,
huggingface_hub/utils/__pycache__/_dotenv.cpython-314.pyc,,
huggingface_hub/utils/__pycache__/_experimental.cpython-314.pyc,,
huggingface_hub/utils/__pycache__/_fixes.cpython-314.pyc,,
huggingface_hub/utils/__pycache__/_git_credential.cpython-314.pyc,,
huggingface_hub/utils/__pycache__/_headers.cpython-314.pyc,,
huggingface_hub/utils/__pycache__/_hf_uris.cpython-314.pyc,,
huggingface_hub/utils/__pycache__/_http.cpython-314.pyc,,
huggingface_hub/utils/__pycache__/_lfs.cpython-314.pyc,,
huggingface_hub/utils/__pycache__/_oauth_device.cpython-314.pyc,,
huggingface_hub/utils/__pycache__/_pagination.cpython-314.pyc,,
huggingface_hub/utils/__pycache__/_parsing.cpython-314.pyc,,
huggingface_hub/utils/__pycache__/_paths.cpython-314.pyc,,
huggingface_hub/utils/__pycache__/_runtime.cpython-314.pyc,,
huggingface_hub/utils/__pycache__/_safetensors.cpython-314.pyc,,
huggingface_hub/utils/__pycache__/_subprocess.cpython-314.pyc,,
huggingface_hub/utils/__pycache__/_telemetry.cpython-314.pyc,,
huggingface_hub/utils/__pycache__/_terminal.cpython-314.pyc,,
huggingface_hub/utils/__pycache__/_typing.cpython-314.pyc,,
huggingface_hub/utils/__pycache__/_validators.cpython-314.pyc,,
huggingface_hub/utils/__pycache__/_verification.cpython-314.pyc,,
huggingface_hub/utils/__pycache__/_xet.cpython-314.pyc,,
huggingface_hub/utils/__pycache__/_xet_progress_reporting.cpython-314.pyc,,
huggingface_hub/utils/__pycache__/endpoint_helpers.cpython-314.pyc,,
huggingface_hub/utils/__pycache__/insecure_hashlib.cpython-314.pyc,,
huggingface_hub/utils/__pycache__/logging.cpython-314.pyc,,
huggingface_hub/utils/__pycache__/sha.cpython-314.pyc,,
huggingface_hub/utils/__pycache__/tqdm.cpython-314.pyc,,
huggingface_hub/utils/_auth.py,sha256=Ykuq3yi67jxHmFdyLSc43xvGuCAIR7-h-dajX8IxpGQ,19958
huggingface_hub/utils/_cache_assets.py,sha256=nnzHRtQAR50dQeIK6qKddsmjjTW9v9HZ7b9bq7PJqss,5691
huggingface_hub/utils/_cache_manager.py,sha256=BFixsojrtG1K8rsD89EsGtXSktXbt0-VlJJkPRz5tso,35733
huggingface_hub/utils/_chunk_utils.py,sha256=pTjy8Z-KLU4W_6D3OUh3E8lCodWDCd6aJwjNDU0C5U8,2121
huggingface_hub/utils/_datetime.py,sha256=tbNyI0Dkh27oScPUtLIT_8apqIIkXZYbigjOn9S3aMw,2755
huggingface_hub/utils/_deprecation.py,sha256=n4kNHbGipquSObJ-gxodcfd6lqoe_8s-VIsTuo3Oruk,4865
huggingface_hub/utils/_detect_agent.py,sha256=Iw2KW9BUZWfIypn9CtiTmEibHwKK9xx5Ar48z1cMU-Q,7337
huggingface_hub/utils/_dotenv.py,sha256=NdlEM8OXtzwlwmJCmdc6oGubFObrpgr408y8gnSs7ls,2604
huggingface_hub/utils/_experimental.py,sha256=q9vUvc1JybVFRQ0GRREG-BLouZEJC_40MxcwbAlOud0,2464
huggingface_hub/utils/_fixes.py,sha256=jTK1VLmc0ZC9ROSXjKoL5F6kOZFByzirRWIdXxhBfWU,4124
huggingface_hub/utils/_git_credential.py,sha256=1BhjvIScCOAToDORLOKrR3Szs-m0E5AYHPmC0SD7Nrs,4548
huggingface_hub/utils/_headers.py,sha256=Q9bu9mvOpm-9rfv-YRlr_Ywy_aMZkmRcN3MbVEcJAJA,8234
huggingface_hub/utils/_hf_uris.py,sha256=RTHrVKLT5vVU-ca8roXHrKwbN3njowanvxHjx5B4sUg,27558
huggingface_hub/utils/_http.py,sha256=zx1TItko5i0_CzL95zHyt36XXrtVLnn5F9fl6ODq8aw,46197
huggingface_hub/utils/_lfs.py,sha256=xMU-ROgNAUpDkzbH6yRZsE-eVYUYTNMGrgVb_QdTv-k,3942
huggingface_hub/utils/_oauth_device.py,sha256=o7ICmI01yDt1oAFNMUJvN1ThSfaCDpC8AHYSQgcnFGw,7983
huggingface_hub/utils/_pagination.py,sha256=h-TJjFbX3FqkA1T0tGZ0EhxMvuRSCg-UfL_a-BMs54I,1943
huggingface_hub/utils/_parsing.py,sha256=DVWuO6s_XMiGfXyc0jyX5hi_yGgBHpF9KLoeQM-VVK0,3586
huggingface_hub/utils/_paths.py,sha256=kWpUMIK9rmKb2LHgHCkk2DnroDzucrwbj-urCJCgfGw,5962
huggingface_hub/utils/_runtime.py,sha256=GVJ_Dt6y_48TZWl0ui9yPdW8M7rqGblRGyUqKaXxkCo,13493
huggingface_hub/utils/_safetensors.py,sha256=qFE7OA-vjU8X0zBBtOeNRzLu147KF-PdFoaxkYfWB4M,4426
huggingface_hub/utils/_subprocess.py,sha256=tFVBBNot_HLVqQ79y873TGb12C4PUTMwub-GhzDTemE,4542
huggingface_hub/utils/_telemetry.py,sha256=Tpa3YmOLhK_MEnL2i2fRLQy8aqAEZWbj6MKC18Hs8BA,4824
huggingface_hub/utils/_terminal.py,sha256=whHgs0Co-1LatoCmJE_ojqE_cWP6b5dWPWpU-uSFWUU,8969
huggingface_hub/utils/_typing.py,sha256=1LeE785YedppXSR9a1fQDu5rhTxX5v9kBYBaHrP65rA,3542
huggingface_hub/utils/_validators.py,sha256=tuC1U4yxB-4XKIajZMnKZUSKvZ6qPpydY8LItfa0g40,8419
huggingface_hub/utils/_verification.py,sha256=ZSilnolSkYmHB3vmBlWuuVr53xz59P5uGnxC3H-Hjc0,5434
huggingface_hub/utils/_xet.py,sha256=lVCUmCxzmBFYRSkJxFLtfhe7_HJWdLzJdENL-ln5Grc,6556
huggingface_hub/utils/_xet_progress_reporting.py,sha256=MnNCxB9ieflArNNyz3R4kpkjOdt6mQxi8qp8xqzXQTM,14162
huggingface_hub/utils/endpoint_helpers.py,sha256=9VtIAlxQ5H_4y30sjCAgbu7XCqAtNLC7aRYxaNn0hLI,2366
huggingface_hub/utils/insecure_hashlib.py,sha256=z3dVUFvdBZ8kQI_8Vzvvlr3ims-EBiY-SYPdnzIKOkw,1008
huggingface_hub/utils/logging.py,sha256=WaXk5gRa8Ml_LUIH34QCr8suYj8i_8Wot4IDnYJyWyM,4870
huggingface_hub/utils/sha.py,sha256=h8wxheZpcv671RhtiIFcFmQTDSrogN3kwQx3ZaNEUHg,2121
huggingface_hub/utils/tqdm.py,sha256=xXjKGy2y2gMqpKeMUqXcQWc66buW39NwkTr3hlWH6MY,1672912345Wheel-Version: 1.0Generator: setuptools (83.0.0)Root-Is-Purelib: trueTag: py3-none-any
1234567[console_scripts]hf = huggingface_hub.cli.hf:mainhuggingface-cli = huggingface_hub.cli.deprecated_cli:maintiny-agents = huggingface_hub.inference._mcp.cli:app
[fsspec.specs]hf = huggingface_hub.HfFileSystem123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.1huggingface_hub.venv-deploy/lib/python3.14/site-packages/httpcore-1.0.9.dist-info/INSTALLERAdded+1
.venv-deploy/lib/python3.14/site-packages/httpcore-1.0.9.dist-info/METADATAAdded+625
.venv-deploy/lib/python3.14/site-packages/httpcore-1.0.9.dist-info/RECORDAdded+68
.venv-deploy/lib/python3.14/site-packages/httpcore-1.0.9.dist-info/WHEELAdded+4
.venv-deploy/lib/python3.14/site-packages/httpcore-1.0.9.dist-info/licenses/LICENSE.mdAdded+27
.venv-deploy/lib/python3.14/site-packages/httpcore/_sync/http_proxy.pyAdded+367
.venv-deploy/lib/python3.14/site-packages/httpcore/_sync/interfaces.pyAdded+137
.venv-deploy/lib/python3.14/site-packages/httpcore/_sync/socks_proxy.pyAdded+341
.venv-deploy/lib/python3.14/site-packages/httpcore/_synchronization.pyAdded+318
.venv-deploy/lib/python3.14/site-packages/httpcore/_trace.pyAdded+107
.venv-deploy/lib/python3.14/site-packages/httpcore/_utils.pyAdded+37
.venv-deploy/lib/python3.14/site-packages/httpcore/py.typedAdded
.venv-deploy/lib/python3.14/site-packages/httpx-0.28.1.dist-info/INSTALLERAdded+1
.venv-deploy/lib/python3.14/site-packages/httpx-0.28.1.dist-info/METADATAAdded+203
.venv-deploy/lib/python3.14/site-packages/httpx-0.28.1.dist-info/RECORDAdded+54
.venv-deploy/lib/python3.14/site-packages/httpx-0.28.1.dist-info/WHEELAdded+4
.venv-deploy/lib/python3.14/site-packages/httpx-0.28.1.dist-info/entry_points.txtAdded+2
.venv-deploy/lib/python3.14/site-packages/httpx-0.28.1.dist-info/licenses/LICENSE.mdAdded+12
.venv-deploy/lib/python3.14/site-packages/httpx/__init__.pyAdded+105
.venv-deploy/lib/python3.14/site-packages/httpx/__version__.pyAdded+3
.venv-deploy/lib/python3.14/site-packages/httpx/_api.pyAdded+438
.venv-deploy/lib/python3.14/site-packages/httpx/_auth.pyAdded+348
.venv-deploy/lib/python3.14/site-packages/httpx/_client.pyAdded+2019
.venv-deploy/lib/python3.14/site-packages/httpx/_config.pyAdded+248
.venv-deploy/lib/python3.14/site-packages/httpx/_content.pyAdded+240
.venv-deploy/lib/python3.14/site-packages/httpx/_decoders.pyAdded+393
.venv-deploy/lib/python3.14/site-packages/httpx/_exceptions.pyAdded+379
.venv-deploy/lib/python3.14/site-packages/httpx/_main.pyAdded+506
.venv-deploy/lib/python3.14/site-packages/httpx/_models.pyAdded+1277
.venv-deploy/lib/python3.14/site-packages/httpx/_multipart.pyAdded+300
.venv-deploy/lib/python3.14/site-packages/httpx/_status_codes.pyAdded+162
.venv-deploy/lib/python3.14/site-packages/httpx/_transports/__init__.pyAdded+15
.venv-deploy/lib/python3.14/site-packages/httpx/_transports/asgi.pyAdded+187
.venv-deploy/lib/python3.14/site-packages/httpx/_transports/base.pyAdded+86
.venv-deploy/lib/python3.14/site-packages/httpx/_transports/default.pyAdded+406
.venv-deploy/lib/python3.14/site-packages/httpx/_transports/mock.pyAdded+43
.venv-deploy/lib/python3.14/site-packages/httpx/_transports/wsgi.pyAdded+149
.venv-deploy/lib/python3.14/site-packages/httpx/_types.pyAdded+114
.venv-deploy/lib/python3.14/site-packages/httpx/_urlparse.pyAdded+527
.venv-deploy/lib/python3.14/site-packages/httpx/_urls.pyAdded+641
.venv-deploy/lib/python3.14/site-packages/httpx/_utils.pyAdded+242
.venv-deploy/lib/python3.14/site-packages/httpx/py.typedAdded
.venv-deploy/lib/python3.14/site-packages/huggingface_hub-1.27.0.dist-info/INSTALLERAdded+1
.venv-deploy/lib/python3.14/site-packages/huggingface_hub-1.27.0.dist-info/METADATAAdded+373
.venv-deploy/lib/python3.14/site-packages/huggingface_hub-1.27.0.dist-info/RECORDAdded+380
.venv-deploy/lib/python3.14/site-packages/huggingface_hub-1.27.0.dist-info/REQUESTEDAdded
.venv-deploy/lib/python3.14/site-packages/huggingface_hub-1.27.0.dist-info/WHEELAdded+5
.venv-deploy/lib/python3.14/site-packages/huggingface_hub-1.27.0.dist-info/entry_points.txtAdded+7
.venv-deploy/lib/python3.14/site-packages/huggingface_hub-1.27.0.dist-info/licenses/LICENSEAdded+201
.venv-deploy/lib/python3.14/site-packages/huggingface_hub-1.27.0.dist-info/top_level.txtAdded+1