exchangerate-dev 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- exchangerate_dev-0.1.0/CHANGELOG.md +8 -0
- exchangerate_dev-0.1.0/LICENSE +21 -0
- exchangerate_dev-0.1.0/PKG-INFO +90 -0
- exchangerate_dev-0.1.0/README.md +65 -0
- exchangerate_dev-0.1.0/hatch_build.py +14 -0
- exchangerate_dev-0.1.0/pyproject.toml +40 -0
- exchangerate_dev-0.1.0/src/exchangerate_dev/__init__.py +16 -0
- exchangerate_dev-0.1.0/src/exchangerate_dev/_client.py +122 -0
- exchangerate_dev-0.1.0/src/exchangerate_dev/_deadline.py +180 -0
- exchangerate_dev-0.1.0/src/exchangerate_dev/_decode.py +67 -0
- exchangerate_dev-0.1.0/src/exchangerate_dev/_generated/__init__.py +2 -0
- exchangerate_dev-0.1.0/src/exchangerate_dev/_generated/models.py +617 -0
- exchangerate_dev-0.1.0/src/exchangerate_dev/_generated/operations.py +986 -0
- exchangerate_dev-0.1.0/src/exchangerate_dev/_meta.py +40 -0
- exchangerate_dev-0.1.0/src/exchangerate_dev/_pagination.py +47 -0
- exchangerate_dev-0.1.0/src/exchangerate_dev/_transport.py +346 -0
- exchangerate_dev-0.1.0/src/exchangerate_dev/_version.py +1 -0
- exchangerate_dev-0.1.0/src/exchangerate_dev/errors.py +84 -0
- exchangerate_dev-0.1.0/src/exchangerate_dev/models.py +48 -0
- exchangerate_dev-0.1.0/src/exchangerate_dev/py.typed +0 -0
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0 — 2026-10-09
|
|
4
|
+
|
|
5
|
+
- Synchronous and asynchronous clients for indicative FX reference rates.
|
|
6
|
+
- Latest and historical rates, conversion, currencies, indices, and daily usage.
|
|
7
|
+
- Exact decimals, typed errors, bounded retries, and response metadata.
|
|
8
|
+
- Pagination iterators for rate ranges and rate and index timeseries.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Nusantara Ventures, LLC
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: exchangerate-dev
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Typed clients for the exchangerate.dev API
|
|
5
|
+
Project-URL: Homepage, https://exchangerate.dev/docs
|
|
6
|
+
Author-email: "Nusantara Ventures, LLC" <hello@exchangerate.dev>
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Keywords: api,currency,decimal,exchange-rates,forex,fx,sdk
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
19
|
+
Classifier: Topic :: Office/Business :: Financial
|
|
20
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Python: >=3.10
|
|
23
|
+
Requires-Dist: httpx<1,>=0.27
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# Exchangerate for Python
|
|
27
|
+
|
|
28
|
+
Python clients for indicative FX reference rates from exchangerate.dev. Read latest
|
|
29
|
+
and historical rates, currency pairs, indices, and account usage, or convert an
|
|
30
|
+
amount between currencies. These rates are not for settlement or trading.
|
|
31
|
+
|
|
32
|
+
## Install
|
|
33
|
+
|
|
34
|
+
Requires Python 3.10 or newer. The only dependency is httpx.
|
|
35
|
+
|
|
36
|
+
```sh
|
|
37
|
+
pip install exchangerate-dev
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## Quickstart
|
|
41
|
+
|
|
42
|
+
Set `EXCHANGERATE_API_KEY` in your environment, then run:
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
from exchangerate_dev import Exchangerate
|
|
46
|
+
|
|
47
|
+
with Exchangerate() as client:
|
|
48
|
+
latest = client.rates.latest(base="USD", symbols=["EUR", "IDR"])
|
|
49
|
+
print(latest.rates["EUR"])
|
|
50
|
+
print(latest.meta.request_id)
|
|
51
|
+
converted = client.convert.amount("USD", "IDR", amount="100")
|
|
52
|
+
print(converted)
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
The context manager closes the client. `AsyncExchangerate` provides asynchronous
|
|
56
|
+
access. Supply `api_key=` to configure a key explicitly. The default base URL is
|
|
57
|
+
`https://api.exchangerate.dev`; override it with `EXCHANGERATE_BASE_URL` or
|
|
58
|
+
`base_url=`. Pass `symbols` as a list of currency codes.
|
|
59
|
+
|
|
60
|
+
Use `currencies.list()` to read available currency codes and
|
|
61
|
+
`account.usage_daily(days=...)` to inspect daily account usage.
|
|
62
|
+
|
|
63
|
+
## Decimals
|
|
64
|
+
|
|
65
|
+
Rates and amounts use exact `decimal.Decimal` values, never floats. The `rates`
|
|
66
|
+
dictionary maps currency codes to decimals. Pass conversion amounts as strings
|
|
67
|
+
to preserve decimal input. Every response carries `meta` with `request_id` and
|
|
68
|
+
rate-limit values from headers.
|
|
69
|
+
|
|
70
|
+
## Errors and retries
|
|
71
|
+
|
|
72
|
+
`errors.Unauthorized`, `errors.RateLimited`, `errors.NotFound`, and
|
|
73
|
+
`errors.BadRequest` extend `errors.ApiError`, which exposes `status`, `code`,
|
|
74
|
+
`detail`, and `request_id`. `errors.RateLimited` also carries `retry_after`.
|
|
75
|
+
All client errors derive from `errors.ExchangerateError`. Import `errors` from
|
|
76
|
+
`exchangerate_dev` when handling these exceptions.
|
|
77
|
+
|
|
78
|
+
Requests retry up to twice by default for short-window rate limits and temporary
|
|
79
|
+
unavailability. Quota exhaustion is not retried.
|
|
80
|
+
|
|
81
|
+
## Pagination iterators
|
|
82
|
+
|
|
83
|
+
Use `rates.range_iter(...)`, `rates.timeseries_iter(...)`, and
|
|
84
|
+
`indices.timeseries_iter(index_slug, ...)` to consume items across pages. Use
|
|
85
|
+
`for` with `Exchangerate` and `async for` with `AsyncExchangerate`. Their
|
|
86
|
+
corresponding methods without `_iter` return a single page.
|
|
87
|
+
|
|
88
|
+
Links: [Documentation](https://exchangerate.dev/docs)
|
|
89
|
+
|
|
90
|
+
MIT licensed
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
# Exchangerate for Python
|
|
2
|
+
|
|
3
|
+
Python clients for indicative FX reference rates from exchangerate.dev. Read latest
|
|
4
|
+
and historical rates, currency pairs, indices, and account usage, or convert an
|
|
5
|
+
amount between currencies. These rates are not for settlement or trading.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
Requires Python 3.10 or newer. The only dependency is httpx.
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
pip install exchangerate-dev
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Quickstart
|
|
16
|
+
|
|
17
|
+
Set `EXCHANGERATE_API_KEY` in your environment, then run:
|
|
18
|
+
|
|
19
|
+
```python
|
|
20
|
+
from exchangerate_dev import Exchangerate
|
|
21
|
+
|
|
22
|
+
with Exchangerate() as client:
|
|
23
|
+
latest = client.rates.latest(base="USD", symbols=["EUR", "IDR"])
|
|
24
|
+
print(latest.rates["EUR"])
|
|
25
|
+
print(latest.meta.request_id)
|
|
26
|
+
converted = client.convert.amount("USD", "IDR", amount="100")
|
|
27
|
+
print(converted)
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
The context manager closes the client. `AsyncExchangerate` provides asynchronous
|
|
31
|
+
access. Supply `api_key=` to configure a key explicitly. The default base URL is
|
|
32
|
+
`https://api.exchangerate.dev`; override it with `EXCHANGERATE_BASE_URL` or
|
|
33
|
+
`base_url=`. Pass `symbols` as a list of currency codes.
|
|
34
|
+
|
|
35
|
+
Use `currencies.list()` to read available currency codes and
|
|
36
|
+
`account.usage_daily(days=...)` to inspect daily account usage.
|
|
37
|
+
|
|
38
|
+
## Decimals
|
|
39
|
+
|
|
40
|
+
Rates and amounts use exact `decimal.Decimal` values, never floats. The `rates`
|
|
41
|
+
dictionary maps currency codes to decimals. Pass conversion amounts as strings
|
|
42
|
+
to preserve decimal input. Every response carries `meta` with `request_id` and
|
|
43
|
+
rate-limit values from headers.
|
|
44
|
+
|
|
45
|
+
## Errors and retries
|
|
46
|
+
|
|
47
|
+
`errors.Unauthorized`, `errors.RateLimited`, `errors.NotFound`, and
|
|
48
|
+
`errors.BadRequest` extend `errors.ApiError`, which exposes `status`, `code`,
|
|
49
|
+
`detail`, and `request_id`. `errors.RateLimited` also carries `retry_after`.
|
|
50
|
+
All client errors derive from `errors.ExchangerateError`. Import `errors` from
|
|
51
|
+
`exchangerate_dev` when handling these exceptions.
|
|
52
|
+
|
|
53
|
+
Requests retry up to twice by default for short-window rate limits and temporary
|
|
54
|
+
unavailability. Quota exhaustion is not retried.
|
|
55
|
+
|
|
56
|
+
## Pagination iterators
|
|
57
|
+
|
|
58
|
+
Use `rates.range_iter(...)`, `rates.timeseries_iter(...)`, and
|
|
59
|
+
`indices.timeseries_iter(index_slug, ...)` to consume items across pages. Use
|
|
60
|
+
`for` with `Exchangerate` and `async for` with `AsyncExchangerate`. Their
|
|
61
|
+
corresponding methods without `_iter` return a single page.
|
|
62
|
+
|
|
63
|
+
Links: [Documentation](https://exchangerate.dev/docs)
|
|
64
|
+
|
|
65
|
+
MIT licensed
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""Keep repository ignore files out of the source distribution."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
from hatchling.builders.hooks.plugin.interface import BuildHookInterface
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class CustomBuildHook(BuildHookInterface):
|
|
9
|
+
def initialize(self, version, build_data):
|
|
10
|
+
if self.target_name == "sdist":
|
|
11
|
+
forced = build_data["force_include"]
|
|
12
|
+
for path in list(forced):
|
|
13
|
+
if Path(path).name in {".gitignore", ".hgignore"}:
|
|
14
|
+
del forced[path]
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.27"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "exchangerate-dev"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Typed clients for the exchangerate.dev API"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
authors = [{ name = "Nusantara Ventures, LLC", email = "hello@exchangerate.dev" }]
|
|
12
|
+
license = "MIT"
|
|
13
|
+
license-files = ["LICENSE"]
|
|
14
|
+
dependencies = ["httpx>=0.27,<1"]
|
|
15
|
+
keywords = ["api", "sdk", "fx", "exchange-rates", "currency", "forex", "decimal"]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"Operating System :: OS Independent",
|
|
19
|
+
"Topic :: Office/Business :: Financial",
|
|
20
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
21
|
+
"Typing :: Typed",
|
|
22
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
23
|
+
"Programming Language :: Python :: 3.10",
|
|
24
|
+
"Programming Language :: Python :: 3.11",
|
|
25
|
+
"Programming Language :: Python :: 3.12",
|
|
26
|
+
"Programming Language :: Python :: 3.13",
|
|
27
|
+
"Programming Language :: Python :: 3.14",
|
|
28
|
+
"License :: OSI Approved :: MIT License",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
[project.urls]
|
|
32
|
+
Homepage = "https://exchangerate.dev/docs"
|
|
33
|
+
|
|
34
|
+
[tool.hatch.build.targets.wheel]
|
|
35
|
+
packages = ["src/exchangerate_dev"]
|
|
36
|
+
|
|
37
|
+
[tool.hatch.build.targets.sdist]
|
|
38
|
+
include = ["src/exchangerate_dev", "README.md", "CHANGELOG.md", "LICENSE", "pyproject.toml"]
|
|
39
|
+
|
|
40
|
+
[tool.hatch.build.hooks.custom]
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""Typed clients for the exchangerate.dev API."""
|
|
2
|
+
|
|
3
|
+
from . import errors, models
|
|
4
|
+
from ._client import AsyncExchangerate, Exchangerate
|
|
5
|
+
from ._meta import RateLimit, ResponseMeta
|
|
6
|
+
from ._version import __version__
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"AsyncExchangerate",
|
|
10
|
+
"Exchangerate",
|
|
11
|
+
"RateLimit",
|
|
12
|
+
"ResponseMeta",
|
|
13
|
+
"__version__",
|
|
14
|
+
"errors",
|
|
15
|
+
"models",
|
|
16
|
+
]
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""Connection-owning synchronous and asynchronous clients."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import random
|
|
5
|
+
import time
|
|
6
|
+
from collections.abc import Awaitable, Callable, Mapping
|
|
7
|
+
from types import TracebackType
|
|
8
|
+
from typing import TypeVar
|
|
9
|
+
|
|
10
|
+
import httpx
|
|
11
|
+
|
|
12
|
+
from ._generated.operations import (
|
|
13
|
+
LIVE_SPEC_SHA,
|
|
14
|
+
AsyncStableOperations,
|
|
15
|
+
StableOperations,
|
|
16
|
+
)
|
|
17
|
+
from ._transport import AsyncTransport, Settings, SyncTransport
|
|
18
|
+
|
|
19
|
+
SyncClient = TypeVar("SyncClient", bound="Exchangerate")
|
|
20
|
+
AsyncClient = TypeVar("AsyncClient", bound="AsyncExchangerate")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class Exchangerate(StableOperations):
|
|
24
|
+
"""Share one client across threads and close it when finished."""
|
|
25
|
+
|
|
26
|
+
def __init__(
|
|
27
|
+
self,
|
|
28
|
+
api_key: str | None = None,
|
|
29
|
+
*,
|
|
30
|
+
base_url: str | None = None,
|
|
31
|
+
proxy: str | None = None,
|
|
32
|
+
timeout: float = 30,
|
|
33
|
+
max_retries: int = 2,
|
|
34
|
+
max_retry_wait: float = 30,
|
|
35
|
+
extra_headers: Mapping[str, str] | None = None,
|
|
36
|
+
transport: httpx.BaseTransport | None = None,
|
|
37
|
+
sleep: Callable[[float], None] = time.sleep,
|
|
38
|
+
clock: Callable[[], float] = time.monotonic,
|
|
39
|
+
random_fraction: Callable[[], float] = random.random,
|
|
40
|
+
) -> None:
|
|
41
|
+
settings = Settings(
|
|
42
|
+
api_key=api_key,
|
|
43
|
+
base_url=base_url,
|
|
44
|
+
proxy=proxy,
|
|
45
|
+
timeout=timeout,
|
|
46
|
+
max_retries=max_retries,
|
|
47
|
+
max_retry_wait=max_retry_wait,
|
|
48
|
+
extra_headers=extra_headers,
|
|
49
|
+
clock=clock,
|
|
50
|
+
random_fraction=random_fraction,
|
|
51
|
+
spec_sha=LIVE_SPEC_SHA,
|
|
52
|
+
)
|
|
53
|
+
self._transport = SyncTransport(settings, transport=transport, sleep=sleep)
|
|
54
|
+
super().__init__(self._transport)
|
|
55
|
+
|
|
56
|
+
def __repr__(self) -> str:
|
|
57
|
+
return "Exchangerate(api_key=<redacted>)"
|
|
58
|
+
|
|
59
|
+
def close(self) -> None:
|
|
60
|
+
self._transport.http.close()
|
|
61
|
+
|
|
62
|
+
def __enter__(self: SyncClient) -> SyncClient:
|
|
63
|
+
return self
|
|
64
|
+
|
|
65
|
+
def __exit__(
|
|
66
|
+
self,
|
|
67
|
+
exc_type: type[BaseException] | None,
|
|
68
|
+
exc: BaseException | None,
|
|
69
|
+
tb: TracebackType | None,
|
|
70
|
+
) -> None:
|
|
71
|
+
self.close()
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class AsyncExchangerate(AsyncStableOperations):
|
|
75
|
+
"""Use one client per event loop and close it with async with."""
|
|
76
|
+
|
|
77
|
+
def __init__(
|
|
78
|
+
self,
|
|
79
|
+
api_key: str | None = None,
|
|
80
|
+
*,
|
|
81
|
+
base_url: str | None = None,
|
|
82
|
+
proxy: str | None = None,
|
|
83
|
+
timeout: float = 30,
|
|
84
|
+
max_retries: int = 2,
|
|
85
|
+
max_retry_wait: float = 30,
|
|
86
|
+
extra_headers: Mapping[str, str] | None = None,
|
|
87
|
+
transport: httpx.AsyncBaseTransport | None = None,
|
|
88
|
+
sleep: Callable[[float], Awaitable[None]] = asyncio.sleep,
|
|
89
|
+
clock: Callable[[], float] = time.monotonic,
|
|
90
|
+
random_fraction: Callable[[], float] = random.random,
|
|
91
|
+
) -> None:
|
|
92
|
+
settings = Settings(
|
|
93
|
+
api_key=api_key,
|
|
94
|
+
base_url=base_url,
|
|
95
|
+
proxy=proxy,
|
|
96
|
+
timeout=timeout,
|
|
97
|
+
max_retries=max_retries,
|
|
98
|
+
max_retry_wait=max_retry_wait,
|
|
99
|
+
extra_headers=extra_headers,
|
|
100
|
+
clock=clock,
|
|
101
|
+
random_fraction=random_fraction,
|
|
102
|
+
spec_sha=LIVE_SPEC_SHA,
|
|
103
|
+
)
|
|
104
|
+
self._transport = AsyncTransport(settings, transport=transport, sleep=sleep)
|
|
105
|
+
super().__init__(self._transport)
|
|
106
|
+
|
|
107
|
+
def __repr__(self) -> str:
|
|
108
|
+
return "AsyncExchangerate(api_key=<redacted>)"
|
|
109
|
+
|
|
110
|
+
async def aclose(self) -> None:
|
|
111
|
+
await self._transport.http.aclose()
|
|
112
|
+
|
|
113
|
+
async def __aenter__(self: AsyncClient) -> AsyncClient:
|
|
114
|
+
return self
|
|
115
|
+
|
|
116
|
+
async def __aexit__(
|
|
117
|
+
self,
|
|
118
|
+
exc_type: type[BaseException] | None,
|
|
119
|
+
exc: BaseException | None,
|
|
120
|
+
tb: TracebackType | None,
|
|
121
|
+
) -> None:
|
|
122
|
+
await self.aclose()
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
"""Per-attempt synchronous I/O deadlines, without threads or event loops."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable, Iterable
|
|
4
|
+
from contextvars import ContextVar
|
|
5
|
+
from ssl import SSLContext
|
|
6
|
+
from typing import Protocol, cast
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
|
|
10
|
+
RESPONSE_STARTED = "exchangerate_dev.response_started"
|
|
11
|
+
SocketOption = tuple[int, int, int | bytes] | tuple[int, int, None, int]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class Deadline:
|
|
15
|
+
def __init__(self, timeout: float, clock: Callable[[], float]) -> None:
|
|
16
|
+
self.clock = clock
|
|
17
|
+
self.expires = clock() + timeout
|
|
18
|
+
|
|
19
|
+
def remaining(self) -> float:
|
|
20
|
+
return max(0.0, self.expires - self.clock())
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
active_deadline: ContextVar[Deadline | None] = ContextVar(
|
|
24
|
+
"exchangerate_dev_deadline", default=None
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def io_timeout(timeout: float | None) -> float | None:
|
|
29
|
+
deadline = active_deadline.get()
|
|
30
|
+
if deadline is None:
|
|
31
|
+
return timeout
|
|
32
|
+
remaining = deadline.remaining()
|
|
33
|
+
if remaining <= 0:
|
|
34
|
+
raise httpx.ReadTimeout("Attempt deadline exceeded")
|
|
35
|
+
return remaining if timeout is None else min(timeout, remaining)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class NetworkStream(Protocol):
|
|
39
|
+
def read(self, max_bytes: int, timeout: float | None = None) -> bytes: ...
|
|
40
|
+
def write(self, buffer: bytes, timeout: float | None = None) -> None: ...
|
|
41
|
+
def close(self) -> None: ...
|
|
42
|
+
def start_tls(
|
|
43
|
+
self,
|
|
44
|
+
ssl_context: SSLContext,
|
|
45
|
+
server_hostname: str | None = None,
|
|
46
|
+
timeout: float | None = None,
|
|
47
|
+
) -> "NetworkStream": ...
|
|
48
|
+
def get_extra_info(self, info: str) -> object: ...
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class NetworkBackend(Protocol):
|
|
52
|
+
def connect_tcp(
|
|
53
|
+
self,
|
|
54
|
+
host: str,
|
|
55
|
+
port: int,
|
|
56
|
+
timeout: float | None = None,
|
|
57
|
+
local_address: str | None = None,
|
|
58
|
+
socket_options: Iterable[SocketOption] | None = None,
|
|
59
|
+
) -> NetworkStream: ...
|
|
60
|
+
def connect_unix_socket(
|
|
61
|
+
self,
|
|
62
|
+
path: str,
|
|
63
|
+
timeout: float | None = None,
|
|
64
|
+
socket_options: Iterable[SocketOption] | None = None,
|
|
65
|
+
) -> NetworkStream: ...
|
|
66
|
+
def sleep(self, seconds: float) -> None: ...
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class _Stream:
|
|
70
|
+
def __init__(self, inner: NetworkStream) -> None:
|
|
71
|
+
self.inner = inner
|
|
72
|
+
|
|
73
|
+
def read(self, max_bytes: int, timeout: float | None = None) -> bytes:
|
|
74
|
+
return self.inner.read(max_bytes, timeout=io_timeout(timeout))
|
|
75
|
+
|
|
76
|
+
def write(self, buffer: bytes, timeout: float | None = None) -> None:
|
|
77
|
+
self.inner.write(buffer, timeout=io_timeout(timeout))
|
|
78
|
+
|
|
79
|
+
def close(self) -> None:
|
|
80
|
+
self.inner.close()
|
|
81
|
+
|
|
82
|
+
def start_tls(
|
|
83
|
+
self,
|
|
84
|
+
ssl_context: SSLContext,
|
|
85
|
+
server_hostname: str | None = None,
|
|
86
|
+
timeout: float | None = None,
|
|
87
|
+
) -> "_Stream":
|
|
88
|
+
return _Stream(
|
|
89
|
+
self.inner.start_tls(
|
|
90
|
+
ssl_context,
|
|
91
|
+
server_hostname=server_hostname,
|
|
92
|
+
timeout=io_timeout(timeout),
|
|
93
|
+
)
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
def get_extra_info(self, info: str) -> object:
|
|
97
|
+
return self.inner.get_extra_info(info)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class _Backend:
|
|
101
|
+
def __init__(self, inner: NetworkBackend) -> None:
|
|
102
|
+
self.inner = inner
|
|
103
|
+
|
|
104
|
+
def connect_tcp(
|
|
105
|
+
self,
|
|
106
|
+
host: str,
|
|
107
|
+
port: int,
|
|
108
|
+
timeout: float | None = None,
|
|
109
|
+
local_address: str | None = None,
|
|
110
|
+
socket_options: Iterable[SocketOption] | None = None,
|
|
111
|
+
) -> NetworkStream:
|
|
112
|
+
return _Stream(
|
|
113
|
+
self.inner.connect_tcp(
|
|
114
|
+
host,
|
|
115
|
+
port,
|
|
116
|
+
timeout=io_timeout(timeout),
|
|
117
|
+
local_address=local_address,
|
|
118
|
+
socket_options=socket_options,
|
|
119
|
+
)
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
def connect_unix_socket(
|
|
123
|
+
self,
|
|
124
|
+
path: str,
|
|
125
|
+
timeout: float | None = None,
|
|
126
|
+
socket_options: Iterable[SocketOption] | None = None,
|
|
127
|
+
) -> NetworkStream:
|
|
128
|
+
return _Stream(
|
|
129
|
+
self.inner.connect_unix_socket(
|
|
130
|
+
path, timeout=io_timeout(timeout), socket_options=socket_options
|
|
131
|
+
)
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
def sleep(self, seconds: float) -> None:
|
|
135
|
+
self.inner.sleep(seconds)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
class _Pool(Protocol):
|
|
139
|
+
_network_backend: NetworkBackend
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
class _ClientTransports(Protocol):
|
|
143
|
+
_transport: httpx.BaseTransport
|
|
144
|
+
_mounts: dict[object, httpx.BaseTransport | None]
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def install_deadlines(client: httpx.Client) -> None:
|
|
148
|
+
"""Adapt native pools, including environment and explicit proxy pools.
|
|
149
|
+
|
|
150
|
+
This is the sole boundary using transport internals. The underlying HTTP codec
|
|
151
|
+
caches the body timeout, so mutating the request timeout between chunks alone
|
|
152
|
+
does not bound slow responses. Native-codec tests verify this adapter against
|
|
153
|
+
the locked dependency. Injected transports can read request timeout extensions.
|
|
154
|
+
"""
|
|
155
|
+
transports = cast(_ClientTransports, client)
|
|
156
|
+
for transport in (transports._transport, *transports._mounts.values()):
|
|
157
|
+
if isinstance(transport, httpx.HTTPTransport):
|
|
158
|
+
pool = cast(_Pool, transport._pool)
|
|
159
|
+
if not isinstance(pool._network_backend, _Backend):
|
|
160
|
+
pool._network_backend = _Backend(pool._network_backend)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def read_response(
|
|
164
|
+
response: httpx.Response, request: httpx.Request, deadline: Deadline
|
|
165
|
+
) -> httpx.Response:
|
|
166
|
+
if response.is_stream_consumed:
|
|
167
|
+
return response
|
|
168
|
+
timeouts = cast(dict[str, float | None], request.extensions["timeout"])
|
|
169
|
+
chunks = []
|
|
170
|
+
for chunk in response.iter_raw():
|
|
171
|
+
chunks.append(chunk)
|
|
172
|
+
# Do not raise after a received chunk: it may be the last one. A next
|
|
173
|
+
# network read is where expiry becomes a transport failure.
|
|
174
|
+
timeouts["read"] = deadline.remaining()
|
|
175
|
+
return httpx.Response(
|
|
176
|
+
response.status_code,
|
|
177
|
+
headers=response.headers,
|
|
178
|
+
content=b"".join(chunks),
|
|
179
|
+
request=request,
|
|
180
|
+
)
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""Strict wire primitives used by generated decoders."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import re
|
|
5
|
+
from decimal import Decimal
|
|
6
|
+
from typing import cast
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def read_object(value: object) -> dict[str, object]:
|
|
10
|
+
if not isinstance(value, dict) or any(not isinstance(k, str) for k in value):
|
|
11
|
+
raise ValueError("expected an object")
|
|
12
|
+
return cast(dict[str, object], value)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def read_list(value: object) -> list[object]:
|
|
16
|
+
if not isinstance(value, list):
|
|
17
|
+
raise TypeError("expected an array")
|
|
18
|
+
return cast(list[object], value)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def read_str(value: object) -> str:
|
|
22
|
+
if not isinstance(value, str):
|
|
23
|
+
raise TypeError("expected a string")
|
|
24
|
+
return value
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def read_int(value: object) -> int:
|
|
28
|
+
if type(value) is not int:
|
|
29
|
+
raise ValueError("expected an integer")
|
|
30
|
+
return value
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def read_bool(value: object) -> bool:
|
|
34
|
+
if not isinstance(value, bool):
|
|
35
|
+
raise TypeError("expected a boolean")
|
|
36
|
+
return value
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def read_decimal(value: object) -> Decimal:
|
|
40
|
+
text = read_str(value)
|
|
41
|
+
if re.fullmatch(r"-?\d+(\.\d+)?", text, re.ASCII) is None:
|
|
42
|
+
raise ValueError("expected a decimal wire string")
|
|
43
|
+
return Decimal(text)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def read_decimal_number(value: object) -> Decimal:
|
|
47
|
+
"""A decimal sent as a JSON number; `read_json` keeps its literal as a Decimal."""
|
|
48
|
+
if isinstance(value, bool) or not isinstance(value, (int, Decimal)):
|
|
49
|
+
raise TypeError("expected a JSON number")
|
|
50
|
+
if isinstance(value, Decimal) and not value.is_finite():
|
|
51
|
+
raise ValueError("expected a finite JSON number")
|
|
52
|
+
return Decimal(value)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def reject_number(value: str) -> object:
|
|
56
|
+
raise ValueError("unexpected non-finite JSON number")
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def read_json(raw: bytes) -> object:
|
|
60
|
+
return json.loads(raw, parse_float=Decimal, parse_constant=reject_number)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def read_cursor(value: object) -> str:
|
|
64
|
+
cursor = read_str(value)
|
|
65
|
+
if not cursor:
|
|
66
|
+
raise ValueError("next_cursor must not be empty")
|
|
67
|
+
return cursor
|