stalzone-api 0.1.0__py3-none-any.whl
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.
- stalzone_api/__init__.py +228 -0
- stalzone_api/_http.py +375 -0
- stalzone_api/_version.py +3 -0
- stalzone_api/auth.py +525 -0
- stalzone_api/client.py +1033 -0
- stalzone_api/constants.py +32 -0
- stalzone_api/database/__init__.py +165 -0
- stalzone_api/database/cache.py +146 -0
- stalzone_api/database/icons.py +90 -0
- stalzone_api/database/index.py +135 -0
- stalzone_api/database/items.py +692 -0
- stalzone_api/database/providers.py +393 -0
- stalzone_api/errors.py +138 -0
- stalzone_api/models/__init__.py +41 -0
- stalzone_api/models/auction.py +217 -0
- stalzone_api/models/character.py +188 -0
- stalzone_api/models/clan.py +146 -0
- stalzone_api/models/common.py +162 -0
- stalzone_api/models/emission.py +44 -0
- stalzone_api/models/operations.py +149 -0
- stalzone_api/pagination.py +50 -0
- stalzone_api/py.typed +0 -0
- stalzone_api/simple.py +403 -0
- stalzone_api-0.1.0.dist-info/METADATA +213 -0
- stalzone_api-0.1.0.dist-info/RECORD +27 -0
- stalzone_api-0.1.0.dist-info/WHEEL +4 -0
- stalzone_api-0.1.0.dist-info/licenses/LICENSE +21 -0
stalzone_api/__init__.py
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
"""``stalzone_api`` — an insanely simple Python client for Stalzone (Stalcraft).
|
|
2
|
+
|
|
3
|
+
Quick start::
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
from stalzone_api import AppClient
|
|
7
|
+
|
|
8
|
+
async def main():
|
|
9
|
+
async with AppClient() as client: # env vars, or the demo server
|
|
10
|
+
print(await client.emission())
|
|
11
|
+
print(await client.profile("ZIV"))
|
|
12
|
+
print(await client.auction("zyv9").lots(limit=3))
|
|
13
|
+
|
|
14
|
+
asyncio.run(main())
|
|
15
|
+
|
|
16
|
+
The lower-level :class:`Client` / :class:`AsyncClient` and :class:`Database`
|
|
17
|
+
remain available for advanced use.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from ._version import __version__
|
|
21
|
+
from .auth import (
|
|
22
|
+
AppSecretCredentials,
|
|
23
|
+
Credentials,
|
|
24
|
+
OAuth,
|
|
25
|
+
StaticTokenCredentials,
|
|
26
|
+
Token,
|
|
27
|
+
TokenCredentials,
|
|
28
|
+
UserInfo,
|
|
29
|
+
async_fetch_user_info,
|
|
30
|
+
decode_jwt,
|
|
31
|
+
fetch_user_info,
|
|
32
|
+
)
|
|
33
|
+
from .client import AsyncClient, Client
|
|
34
|
+
from .constants import (
|
|
35
|
+
DATABASE_REF,
|
|
36
|
+
DATABASE_REPO,
|
|
37
|
+
DEFAULT_TIMEOUT,
|
|
38
|
+
DEFAULT_USER_AGENT,
|
|
39
|
+
DEMO_APP_ID,
|
|
40
|
+
DEMO_APP_SECRET,
|
|
41
|
+
DEMO_APP_TOKEN,
|
|
42
|
+
DEMO_URL,
|
|
43
|
+
DEMO_USER_TOKEN,
|
|
44
|
+
OAUTH_AUTHORIZE_URL,
|
|
45
|
+
OAUTH_TOKEN_URL,
|
|
46
|
+
OAUTH_USERINFO_URL,
|
|
47
|
+
PROD_URL,
|
|
48
|
+
)
|
|
49
|
+
from .database import (
|
|
50
|
+
Database,
|
|
51
|
+
GitHubProvider,
|
|
52
|
+
IconStore,
|
|
53
|
+
Item,
|
|
54
|
+
ItemStore,
|
|
55
|
+
LocalProvider,
|
|
56
|
+
Provider,
|
|
57
|
+
Text,
|
|
58
|
+
default_cache_dir,
|
|
59
|
+
)
|
|
60
|
+
from .database.items import (
|
|
61
|
+
Block,
|
|
62
|
+
DamageBlock,
|
|
63
|
+
Element,
|
|
64
|
+
Formatted,
|
|
65
|
+
GroupedBlock,
|
|
66
|
+
ItemElement,
|
|
67
|
+
ItemStatus,
|
|
68
|
+
KeyValueElement,
|
|
69
|
+
ListBlock,
|
|
70
|
+
NumericElement,
|
|
71
|
+
PriceElement,
|
|
72
|
+
RangeElement,
|
|
73
|
+
RawBlock,
|
|
74
|
+
RawElement,
|
|
75
|
+
TextBlock,
|
|
76
|
+
TextElement,
|
|
77
|
+
)
|
|
78
|
+
from .errors import (
|
|
79
|
+
ApiError,
|
|
80
|
+
AuthError,
|
|
81
|
+
BadRequest,
|
|
82
|
+
DatabaseError,
|
|
83
|
+
DatabaseNotFound,
|
|
84
|
+
DatabaseUnavailable,
|
|
85
|
+
Forbidden,
|
|
86
|
+
JwtError,
|
|
87
|
+
NotFound,
|
|
88
|
+
RateLimited,
|
|
89
|
+
ServerError,
|
|
90
|
+
StalzoneError,
|
|
91
|
+
TransportError,
|
|
92
|
+
Unauthorized,
|
|
93
|
+
UnprocessableEntity,
|
|
94
|
+
error_from_response,
|
|
95
|
+
)
|
|
96
|
+
from .models import (
|
|
97
|
+
Alliance,
|
|
98
|
+
Character,
|
|
99
|
+
CharacterClan,
|
|
100
|
+
CharacterInformation,
|
|
101
|
+
CharacterProfile,
|
|
102
|
+
CharacterStat,
|
|
103
|
+
Clan,
|
|
104
|
+
ClanList,
|
|
105
|
+
ClanMember,
|
|
106
|
+
ClanRank,
|
|
107
|
+
Emission,
|
|
108
|
+
Lot,
|
|
109
|
+
LotPage,
|
|
110
|
+
OperationSession,
|
|
111
|
+
PriceEntry,
|
|
112
|
+
PricePage,
|
|
113
|
+
PriceSummary,
|
|
114
|
+
Realm,
|
|
115
|
+
Region,
|
|
116
|
+
RegionInfo,
|
|
117
|
+
SessionPage,
|
|
118
|
+
SessionParticipant,
|
|
119
|
+
StatType,
|
|
120
|
+
)
|
|
121
|
+
from .pagination import paginate
|
|
122
|
+
from .simple import AppClient, Auction, SyncAppClient, SyncAuction
|
|
123
|
+
|
|
124
|
+
__all__ = [
|
|
125
|
+
"__version__",
|
|
126
|
+
# simple facade
|
|
127
|
+
"AppClient",
|
|
128
|
+
"SyncAppClient",
|
|
129
|
+
"Auction",
|
|
130
|
+
"SyncAuction",
|
|
131
|
+
# clients
|
|
132
|
+
"AsyncClient",
|
|
133
|
+
"Client",
|
|
134
|
+
# auth
|
|
135
|
+
"AppSecretCredentials",
|
|
136
|
+
"Credentials",
|
|
137
|
+
"OAuth",
|
|
138
|
+
"StaticTokenCredentials",
|
|
139
|
+
"Token",
|
|
140
|
+
"TokenCredentials",
|
|
141
|
+
"UserInfo",
|
|
142
|
+
"async_fetch_user_info",
|
|
143
|
+
"decode_jwt",
|
|
144
|
+
"fetch_user_info",
|
|
145
|
+
# constants
|
|
146
|
+
"DATABASE_REF",
|
|
147
|
+
"DATABASE_REPO",
|
|
148
|
+
"DEFAULT_TIMEOUT",
|
|
149
|
+
"DEFAULT_USER_AGENT",
|
|
150
|
+
"DEMO_APP_ID",
|
|
151
|
+
"DEMO_APP_SECRET",
|
|
152
|
+
"DEMO_APP_TOKEN",
|
|
153
|
+
"DEMO_URL",
|
|
154
|
+
"DEMO_USER_TOKEN",
|
|
155
|
+
"OAUTH_AUTHORIZE_URL",
|
|
156
|
+
"OAUTH_TOKEN_URL",
|
|
157
|
+
"OAUTH_USERINFO_URL",
|
|
158
|
+
"PROD_URL",
|
|
159
|
+
# database
|
|
160
|
+
"Database",
|
|
161
|
+
"GitHubProvider",
|
|
162
|
+
"IconStore",
|
|
163
|
+
"Item",
|
|
164
|
+
"ItemStore",
|
|
165
|
+
"LocalProvider",
|
|
166
|
+
"Provider",
|
|
167
|
+
"Text",
|
|
168
|
+
"default_cache_dir",
|
|
169
|
+
"Block",
|
|
170
|
+
"DamageBlock",
|
|
171
|
+
"Element",
|
|
172
|
+
"Formatted",
|
|
173
|
+
"GroupedBlock",
|
|
174
|
+
"ItemElement",
|
|
175
|
+
"ItemStatus",
|
|
176
|
+
"KeyValueElement",
|
|
177
|
+
"ListBlock",
|
|
178
|
+
"NumericElement",
|
|
179
|
+
"PriceElement",
|
|
180
|
+
"RangeElement",
|
|
181
|
+
"RawBlock",
|
|
182
|
+
"RawElement",
|
|
183
|
+
"TextBlock",
|
|
184
|
+
"TextElement",
|
|
185
|
+
# errors
|
|
186
|
+
"ApiError",
|
|
187
|
+
"AuthError",
|
|
188
|
+
"BadRequest",
|
|
189
|
+
"DatabaseError",
|
|
190
|
+
"DatabaseNotFound",
|
|
191
|
+
"DatabaseUnavailable",
|
|
192
|
+
"Forbidden",
|
|
193
|
+
"JwtError",
|
|
194
|
+
"NotFound",
|
|
195
|
+
"RateLimited",
|
|
196
|
+
"ServerError",
|
|
197
|
+
"StalzoneError",
|
|
198
|
+
"TransportError",
|
|
199
|
+
"Unauthorized",
|
|
200
|
+
"UnprocessableEntity",
|
|
201
|
+
"error_from_response",
|
|
202
|
+
# models
|
|
203
|
+
"Alliance",
|
|
204
|
+
"Character",
|
|
205
|
+
"CharacterClan",
|
|
206
|
+
"CharacterInformation",
|
|
207
|
+
"CharacterProfile",
|
|
208
|
+
"CharacterStat",
|
|
209
|
+
"Clan",
|
|
210
|
+
"ClanList",
|
|
211
|
+
"ClanMember",
|
|
212
|
+
"ClanRank",
|
|
213
|
+
"Emission",
|
|
214
|
+
"Lot",
|
|
215
|
+
"LotPage",
|
|
216
|
+
"OperationSession",
|
|
217
|
+
"PriceEntry",
|
|
218
|
+
"PricePage",
|
|
219
|
+
"PriceSummary",
|
|
220
|
+
"Realm",
|
|
221
|
+
"Region",
|
|
222
|
+
"RegionInfo",
|
|
223
|
+
"SessionPage",
|
|
224
|
+
"SessionParticipant",
|
|
225
|
+
"StatType",
|
|
226
|
+
# helpers
|
|
227
|
+
"paginate",
|
|
228
|
+
]
|
stalzone_api/_http.py
ADDED
|
@@ -0,0 +1,375 @@
|
|
|
1
|
+
"""HTTP transports: retries, rate limiting, authentication and error mapping."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import logging
|
|
7
|
+
import random
|
|
8
|
+
import threading
|
|
9
|
+
import time
|
|
10
|
+
from email.utils import parsedate_to_datetime
|
|
11
|
+
from typing import Any, Mapping
|
|
12
|
+
|
|
13
|
+
import httpx
|
|
14
|
+
|
|
15
|
+
from .auth import Credentials
|
|
16
|
+
from .constants import DEFAULT_TIMEOUT, DEFAULT_USER_AGENT
|
|
17
|
+
from .errors import ApiError, TransportError, error_from_response
|
|
18
|
+
|
|
19
|
+
__all__ = ["AsyncTransport", "RateLimiter", "SyncTransport"]
|
|
20
|
+
|
|
21
|
+
logger = logging.getLogger("stalzone_api")
|
|
22
|
+
|
|
23
|
+
RETRY_STATUSES = (429, 500, 502, 503, 504)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _parse_retry_after(value: str | None) -> float | None:
|
|
27
|
+
if not value:
|
|
28
|
+
return None
|
|
29
|
+
try:
|
|
30
|
+
return max(0.0, float(value))
|
|
31
|
+
except ValueError:
|
|
32
|
+
pass
|
|
33
|
+
try:
|
|
34
|
+
parsed = parsedate_to_datetime(value)
|
|
35
|
+
except (TypeError, ValueError):
|
|
36
|
+
return None
|
|
37
|
+
if parsed is None:
|
|
38
|
+
return None
|
|
39
|
+
return max(0.0, parsed.timestamp() - time.time())
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _clean_params(params: Mapping[str, Any] | None) -> dict[str, str]:
|
|
43
|
+
cleaned: dict[str, str] = {}
|
|
44
|
+
if not params:
|
|
45
|
+
return cleaned
|
|
46
|
+
for key, value in params.items():
|
|
47
|
+
if value is None:
|
|
48
|
+
continue
|
|
49
|
+
if isinstance(value, bool):
|
|
50
|
+
cleaned[key] = "true" if value else "false"
|
|
51
|
+
else:
|
|
52
|
+
cleaned[key] = str(value)
|
|
53
|
+
return cleaned
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class RateLimiter:
|
|
57
|
+
"""Simple client-side rate limiter (minimum interval between requests)."""
|
|
58
|
+
|
|
59
|
+
def __init__(self, rate: float, per: float = 1.0) -> None:
|
|
60
|
+
if rate <= 0:
|
|
61
|
+
raise ValueError("rate must be positive")
|
|
62
|
+
self.interval = per / rate
|
|
63
|
+
self._next = 0.0
|
|
64
|
+
self._lock = threading.Lock()
|
|
65
|
+
|
|
66
|
+
def acquire(self) -> None:
|
|
67
|
+
with self._lock:
|
|
68
|
+
now = time.monotonic()
|
|
69
|
+
wait = self._next - now
|
|
70
|
+
if wait > 0:
|
|
71
|
+
time.sleep(wait)
|
|
72
|
+
now = time.monotonic()
|
|
73
|
+
self._next = max(now, self._next) + self.interval
|
|
74
|
+
|
|
75
|
+
async def async_acquire(self) -> None:
|
|
76
|
+
with self._lock:
|
|
77
|
+
now = time.monotonic()
|
|
78
|
+
wait = max(0.0, self._next - now)
|
|
79
|
+
self._next = now + wait + self.interval
|
|
80
|
+
if wait > 0:
|
|
81
|
+
await asyncio.sleep(wait)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class _TransportBase:
|
|
85
|
+
def __init__(
|
|
86
|
+
self,
|
|
87
|
+
base_url: str,
|
|
88
|
+
*,
|
|
89
|
+
credentials: Credentials | None = None,
|
|
90
|
+
headers: Mapping[str, str] | None = None,
|
|
91
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
92
|
+
retries: int = 3,
|
|
93
|
+
backoff: float = 0.5,
|
|
94
|
+
max_backoff: float = 8.0,
|
|
95
|
+
retry_statuses: tuple[int, ...] = RETRY_STATUSES,
|
|
96
|
+
rate_limiter: RateLimiter | None = None,
|
|
97
|
+
user_agent: str | None = None,
|
|
98
|
+
) -> None:
|
|
99
|
+
self.base_url = base_url.rstrip("/")
|
|
100
|
+
self.credentials = credentials
|
|
101
|
+
self.timeout = timeout
|
|
102
|
+
self.retries = max(0, int(retries))
|
|
103
|
+
self.backoff = backoff
|
|
104
|
+
self.max_backoff = max_backoff
|
|
105
|
+
self.retry_statuses = tuple(retry_statuses)
|
|
106
|
+
self.rate_limiter = rate_limiter
|
|
107
|
+
self.user_agent = user_agent or DEFAULT_USER_AGENT
|
|
108
|
+
self.default_headers: dict[str, str] = {
|
|
109
|
+
"User-Agent": self.user_agent,
|
|
110
|
+
"Accept": "application/json",
|
|
111
|
+
}
|
|
112
|
+
if headers:
|
|
113
|
+
self.default_headers.update({str(k): str(v) for k, v in headers.items()})
|
|
114
|
+
|
|
115
|
+
# ------------------------------------------------------------------ helpers
|
|
116
|
+
def _url(self, path: str) -> str:
|
|
117
|
+
if path.startswith(("http://", "https://")):
|
|
118
|
+
return path
|
|
119
|
+
return f"{self.base_url}/{path.lstrip('/')}"
|
|
120
|
+
|
|
121
|
+
def _headers(self, extra: Mapping[str, str] | None = None) -> dict[str, str]:
|
|
122
|
+
headers = dict(self.default_headers)
|
|
123
|
+
if self.credentials is not None:
|
|
124
|
+
headers.update(self.credentials.headers())
|
|
125
|
+
if extra:
|
|
126
|
+
headers.update({str(k): str(v) for k, v in extra.items()})
|
|
127
|
+
return headers
|
|
128
|
+
|
|
129
|
+
async def _async_headers(self, extra: Mapping[str, str] | None = None) -> dict[str, str]:
|
|
130
|
+
headers = dict(self.default_headers)
|
|
131
|
+
if self.credentials is not None:
|
|
132
|
+
headers.update(await self.credentials.async_headers())
|
|
133
|
+
if extra:
|
|
134
|
+
headers.update({str(k): str(v) for k, v in extra.items()})
|
|
135
|
+
return headers
|
|
136
|
+
|
|
137
|
+
def _delay(self, attempt: int, retry_after: float | None = None) -> float:
|
|
138
|
+
if retry_after is not None:
|
|
139
|
+
return retry_after
|
|
140
|
+
base = min(self.max_backoff, self.backoff * (2**attempt))
|
|
141
|
+
return base + random.uniform(0, base * 0.1)
|
|
142
|
+
|
|
143
|
+
@staticmethod
|
|
144
|
+
def _error(response: httpx.Response) -> ApiError:
|
|
145
|
+
try:
|
|
146
|
+
payload: Any = response.json()
|
|
147
|
+
except ValueError:
|
|
148
|
+
payload = response.text
|
|
149
|
+
return error_from_response(
|
|
150
|
+
response.status_code,
|
|
151
|
+
payload,
|
|
152
|
+
url=str(response.request.url),
|
|
153
|
+
body=response.text[:2000],
|
|
154
|
+
retry_after=_parse_retry_after(response.headers.get("Retry-After")),
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
@staticmethod
|
|
158
|
+
def _json(response: httpx.Response) -> Any:
|
|
159
|
+
if not response.content:
|
|
160
|
+
return None
|
|
161
|
+
try:
|
|
162
|
+
return response.json()
|
|
163
|
+
except ValueError as exc:
|
|
164
|
+
raise ApiError(
|
|
165
|
+
"response is not valid JSON",
|
|
166
|
+
status=response.status_code,
|
|
167
|
+
url=str(response.request.url),
|
|
168
|
+
body=response.text[:2000],
|
|
169
|
+
) from exc
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
class SyncTransport(_TransportBase):
|
|
173
|
+
"""Blocking HTTP transport."""
|
|
174
|
+
|
|
175
|
+
def __init__(
|
|
176
|
+
self,
|
|
177
|
+
base_url: str,
|
|
178
|
+
*,
|
|
179
|
+
client: httpx.Client | None = None,
|
|
180
|
+
**kwargs: Any,
|
|
181
|
+
) -> None:
|
|
182
|
+
super().__init__(base_url, **kwargs)
|
|
183
|
+
self._client = client
|
|
184
|
+
self._owns_client = client is None
|
|
185
|
+
if self._client is None:
|
|
186
|
+
self._client = httpx.Client(
|
|
187
|
+
timeout=self.timeout,
|
|
188
|
+
headers=self.default_headers,
|
|
189
|
+
follow_redirects=True,
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
@property
|
|
193
|
+
def client(self) -> httpx.Client:
|
|
194
|
+
return self._client # type: ignore[return-value]
|
|
195
|
+
|
|
196
|
+
def request(
|
|
197
|
+
self,
|
|
198
|
+
method: str,
|
|
199
|
+
path: str,
|
|
200
|
+
*,
|
|
201
|
+
params: Mapping[str, Any] | None = None,
|
|
202
|
+
headers: Mapping[str, str] | None = None,
|
|
203
|
+
) -> Any:
|
|
204
|
+
return self._execute(method, path, params=params, headers=headers, raw=False)
|
|
205
|
+
|
|
206
|
+
def request_bytes(
|
|
207
|
+
self,
|
|
208
|
+
method: str,
|
|
209
|
+
path: str,
|
|
210
|
+
*,
|
|
211
|
+
params: Mapping[str, Any] | None = None,
|
|
212
|
+
headers: Mapping[str, str] | None = None,
|
|
213
|
+
) -> bytes:
|
|
214
|
+
return self._execute(method, path, params=params, headers=headers, raw=True)
|
|
215
|
+
|
|
216
|
+
def _execute(
|
|
217
|
+
self,
|
|
218
|
+
method: str,
|
|
219
|
+
path: str,
|
|
220
|
+
*,
|
|
221
|
+
params: Mapping[str, Any] | None,
|
|
222
|
+
headers: Mapping[str, str] | None,
|
|
223
|
+
raw: bool,
|
|
224
|
+
) -> Any:
|
|
225
|
+
url = self._url(path)
|
|
226
|
+
query = _clean_params(params)
|
|
227
|
+
attempt = 0
|
|
228
|
+
refreshed = False
|
|
229
|
+
while True:
|
|
230
|
+
if self.rate_limiter is not None:
|
|
231
|
+
self.rate_limiter.acquire()
|
|
232
|
+
try:
|
|
233
|
+
response = self._client.request(
|
|
234
|
+
method,
|
|
235
|
+
url,
|
|
236
|
+
params=query or None,
|
|
237
|
+
headers=self._headers(headers),
|
|
238
|
+
)
|
|
239
|
+
except httpx.HTTPError as exc:
|
|
240
|
+
if attempt < self.retries:
|
|
241
|
+
delay = self._delay(attempt)
|
|
242
|
+
logger.debug("request to %s failed (%s), retrying in %.2fs", url, exc, delay)
|
|
243
|
+
time.sleep(delay)
|
|
244
|
+
attempt += 1
|
|
245
|
+
continue
|
|
246
|
+
raise TransportError(f"request to {url} failed: {exc}", url=url, cause=exc) from exc
|
|
247
|
+
|
|
248
|
+
if response.status_code == 401 and not refreshed and self.credentials is not None:
|
|
249
|
+
if self.credentials.refresh():
|
|
250
|
+
refreshed = True
|
|
251
|
+
logger.debug("access token refreshed after 401 from %s", url)
|
|
252
|
+
continue
|
|
253
|
+
|
|
254
|
+
if response.status_code in self.retry_statuses and attempt < self.retries:
|
|
255
|
+
delay = self._delay(attempt, _parse_retry_after(response.headers.get("Retry-After")))
|
|
256
|
+
logger.debug("got %s from %s, retrying in %.2fs", response.status_code, url, delay)
|
|
257
|
+
time.sleep(delay)
|
|
258
|
+
attempt += 1
|
|
259
|
+
continue
|
|
260
|
+
|
|
261
|
+
if response.is_success:
|
|
262
|
+
return response.content if raw else self._json(response)
|
|
263
|
+
raise self._error(response)
|
|
264
|
+
|
|
265
|
+
def close(self) -> None:
|
|
266
|
+
if self._owns_client and self._client is not None:
|
|
267
|
+
self._client.close()
|
|
268
|
+
|
|
269
|
+
def __enter__(self) -> "SyncTransport":
|
|
270
|
+
return self
|
|
271
|
+
|
|
272
|
+
def __exit__(self, *_: Any) -> None:
|
|
273
|
+
self.close()
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
class AsyncTransport(_TransportBase):
|
|
277
|
+
"""Asynchronous HTTP transport."""
|
|
278
|
+
|
|
279
|
+
def __init__(
|
|
280
|
+
self,
|
|
281
|
+
base_url: str,
|
|
282
|
+
*,
|
|
283
|
+
client: httpx.AsyncClient | None = None,
|
|
284
|
+
**kwargs: Any,
|
|
285
|
+
) -> None:
|
|
286
|
+
super().__init__(base_url, **kwargs)
|
|
287
|
+
self._client = client
|
|
288
|
+
self._owns_client = client is None
|
|
289
|
+
if self._client is None:
|
|
290
|
+
self._client = httpx.AsyncClient(
|
|
291
|
+
timeout=self.timeout,
|
|
292
|
+
headers=self.default_headers,
|
|
293
|
+
follow_redirects=True,
|
|
294
|
+
)
|
|
295
|
+
|
|
296
|
+
@property
|
|
297
|
+
def client(self) -> httpx.AsyncClient:
|
|
298
|
+
return self._client # type: ignore[return-value]
|
|
299
|
+
|
|
300
|
+
async def request(
|
|
301
|
+
self,
|
|
302
|
+
method: str,
|
|
303
|
+
path: str,
|
|
304
|
+
*,
|
|
305
|
+
params: Mapping[str, Any] | None = None,
|
|
306
|
+
headers: Mapping[str, str] | None = None,
|
|
307
|
+
) -> Any:
|
|
308
|
+
return await self._execute(method, path, params=params, headers=headers, raw=False)
|
|
309
|
+
|
|
310
|
+
async def request_bytes(
|
|
311
|
+
self,
|
|
312
|
+
method: str,
|
|
313
|
+
path: str,
|
|
314
|
+
*,
|
|
315
|
+
params: Mapping[str, Any] | None = None,
|
|
316
|
+
headers: Mapping[str, str] | None = None,
|
|
317
|
+
) -> bytes:
|
|
318
|
+
return await self._execute(method, path, params=params, headers=headers, raw=True)
|
|
319
|
+
|
|
320
|
+
async def _execute(
|
|
321
|
+
self,
|
|
322
|
+
method: str,
|
|
323
|
+
path: str,
|
|
324
|
+
*,
|
|
325
|
+
params: Mapping[str, Any] | None,
|
|
326
|
+
headers: Mapping[str, str] | None,
|
|
327
|
+
raw: bool,
|
|
328
|
+
) -> Any:
|
|
329
|
+
url = self._url(path)
|
|
330
|
+
query = _clean_params(params)
|
|
331
|
+
attempt = 0
|
|
332
|
+
refreshed = False
|
|
333
|
+
while True:
|
|
334
|
+
if self.rate_limiter is not None:
|
|
335
|
+
await self.rate_limiter.async_acquire()
|
|
336
|
+
try:
|
|
337
|
+
response = await self._client.request(
|
|
338
|
+
method,
|
|
339
|
+
url,
|
|
340
|
+
params=query or None,
|
|
341
|
+
headers=await self._async_headers(headers),
|
|
342
|
+
)
|
|
343
|
+
except httpx.HTTPError as exc:
|
|
344
|
+
if attempt < self.retries:
|
|
345
|
+
delay = self._delay(attempt)
|
|
346
|
+
logger.debug("request to %s failed (%s), retrying in %.2fs", url, exc, delay)
|
|
347
|
+
await asyncio.sleep(delay)
|
|
348
|
+
attempt += 1
|
|
349
|
+
continue
|
|
350
|
+
raise TransportError(f"request to {url} failed: {exc}", url=url, cause=exc) from exc
|
|
351
|
+
|
|
352
|
+
if response.status_code == 401 and not refreshed and self.credentials is not None:
|
|
353
|
+
if await self.credentials.async_refresh():
|
|
354
|
+
refreshed = True
|
|
355
|
+
continue
|
|
356
|
+
|
|
357
|
+
if response.status_code in self.retry_statuses and attempt < self.retries:
|
|
358
|
+
delay = self._delay(attempt, _parse_retry_after(response.headers.get("Retry-After")))
|
|
359
|
+
await asyncio.sleep(delay)
|
|
360
|
+
attempt += 1
|
|
361
|
+
continue
|
|
362
|
+
|
|
363
|
+
if response.is_success:
|
|
364
|
+
return response.content if raw else self._json(response)
|
|
365
|
+
raise self._error(response)
|
|
366
|
+
|
|
367
|
+
async def aclose(self) -> None:
|
|
368
|
+
if self._owns_client and self._client is not None:
|
|
369
|
+
await self._client.aclose()
|
|
370
|
+
|
|
371
|
+
async def __aenter__(self) -> "AsyncTransport":
|
|
372
|
+
return self
|
|
373
|
+
|
|
374
|
+
async def __aexit__(self, *_: Any) -> None:
|
|
375
|
+
await self.aclose()
|
stalzone_api/_version.py
ADDED