asindotdev 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.
- asin/__init__.py +59 -0
- asin/_endpoints.py +74 -0
- asin/_operations.py +616 -0
- asin/_response.py +86 -0
- asin/_serialization.py +103 -0
- asin/_version.py +1 -0
- asin/client.py +450 -0
- asin/errors.py +73 -0
- asin/models.py +81 -0
- asin/py.typed +1 -0
- asindotdev-0.1.0.dist-info/METADATA +201 -0
- asindotdev-0.1.0.dist-info/RECORD +14 -0
- asindotdev-0.1.0.dist-info/WHEEL +4 -0
- asindotdev-0.1.0.dist-info/licenses/LICENSE +21 -0
asin/_serialization.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""Request serialization: path filling, query pairs and JSON bodies."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import math
|
|
7
|
+
import re
|
|
8
|
+
from collections.abc import Mapping
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from typing import Any
|
|
11
|
+
from urllib.parse import quote, urlencode
|
|
12
|
+
|
|
13
|
+
from .errors import AsinSerializationError
|
|
14
|
+
from .models import HTTPMethod
|
|
15
|
+
|
|
16
|
+
_PATH_PARAM = re.compile(r"\{([^}]+)\}")
|
|
17
|
+
# The API reads the global parameters from the query string, whatever the method.
|
|
18
|
+
QUERY_STRING_PARAMS = {"/products/{id}/check": ("wait",)}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True, slots=True)
|
|
22
|
+
class SerializedRequest:
|
|
23
|
+
path: str
|
|
24
|
+
query: list[tuple[str, str]]
|
|
25
|
+
body: dict[str, Any] | None
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def serialize_request(
|
|
29
|
+
method: HTTPMethod, path_template: str, params: Mapping[str, Any] | None
|
|
30
|
+
) -> SerializedRequest:
|
|
31
|
+
"""Fill ``{name}`` path segments, then send the rest as query pairs (GET, DELETE) or a JSON body (POST, PATCH).
|
|
32
|
+
|
|
33
|
+
``wait`` stays in the query string on POST /products/{id}/check.
|
|
34
|
+
|
|
35
|
+
``None`` values and empty sequences are omitted; ``False`` and ``0`` are sent.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
if params is not None and not isinstance(params, Mapping):
|
|
39
|
+
raise AsinSerializationError("Request parameters must be a mapping.")
|
|
40
|
+
remaining = {name: value for name, value in (params or {}).items() if value is not None}
|
|
41
|
+
|
|
42
|
+
def fill(match: re.Match[str]) -> str:
|
|
43
|
+
name = match.group(1)
|
|
44
|
+
if name not in remaining:
|
|
45
|
+
raise AsinSerializationError(f'The "{name}" path parameter is required.', name)
|
|
46
|
+
return quote(to_wire_string(name, remaining.pop(name)), safe="")
|
|
47
|
+
|
|
48
|
+
path = _PATH_PARAM.sub(fill, path_template)
|
|
49
|
+
|
|
50
|
+
if method in ("GET", "DELETE"):
|
|
51
|
+
query: list[tuple[str, str]] = []
|
|
52
|
+
for name, value in remaining.items():
|
|
53
|
+
if isinstance(value, (list, tuple)):
|
|
54
|
+
query.extend(
|
|
55
|
+
(name, to_wire_string(name, item)) for item in value if item is not None
|
|
56
|
+
)
|
|
57
|
+
else:
|
|
58
|
+
query.append((name, to_wire_string(name, value)))
|
|
59
|
+
return SerializedRequest(path=path, query=query, body=None)
|
|
60
|
+
|
|
61
|
+
query = [
|
|
62
|
+
(name, to_wire_string(name, remaining.pop(name)))
|
|
63
|
+
for name in QUERY_STRING_PARAMS.get(path_template, ())
|
|
64
|
+
if name in remaining
|
|
65
|
+
]
|
|
66
|
+
for name, value in remaining.items():
|
|
67
|
+
if isinstance(value, float) and not math.isfinite(value):
|
|
68
|
+
raise AsinSerializationError(f'The "{name}" parameter must be a finite number.', name)
|
|
69
|
+
return SerializedRequest(path=path, query=query, body=remaining)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def to_wire_string(name: str, value: Any) -> str:
|
|
73
|
+
if isinstance(value, bool):
|
|
74
|
+
return "true" if value else "false"
|
|
75
|
+
if isinstance(value, str):
|
|
76
|
+
return value
|
|
77
|
+
if isinstance(value, int):
|
|
78
|
+
return str(value)
|
|
79
|
+
if isinstance(value, float):
|
|
80
|
+
if not math.isfinite(value):
|
|
81
|
+
raise AsinSerializationError(f'The "{name}" parameter must be a finite number.', name)
|
|
82
|
+
return str(int(value)) if value.is_integer() else repr(value)
|
|
83
|
+
if isinstance(value, (Mapping, list, tuple)):
|
|
84
|
+
try:
|
|
85
|
+
return json.dumps(value, separators=(",", ":"), ensure_ascii=False)
|
|
86
|
+
except (TypeError, ValueError) as cause:
|
|
87
|
+
raise AsinSerializationError(
|
|
88
|
+
f'The "{name}" parameter could not be serialized.', name
|
|
89
|
+
) from cause
|
|
90
|
+
raise AsinSerializationError(
|
|
91
|
+
f'The "{name}" parameter has an unsupported type ({type(value).__name__}).', name
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def encode_query(pairs: list[tuple[str, str]]) -> str:
|
|
96
|
+
return urlencode(pairs, quote_via=quote)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def encode_json_body(body: Mapping[str, Any]) -> bytes:
|
|
100
|
+
try:
|
|
101
|
+
return json.dumps(body, ensure_ascii=False, allow_nan=False).encode("utf-8")
|
|
102
|
+
except (TypeError, ValueError) as cause:
|
|
103
|
+
raise AsinSerializationError("The request body could not be serialized as JSON.") from cause
|
asin/_version.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
asin/client.py
ADDED
|
@@ -0,0 +1,450 @@
|
|
|
1
|
+
"""Blocking and async-I/O Asin clients backed by HTTPX."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import os
|
|
7
|
+
import time
|
|
8
|
+
from collections.abc import Awaitable, Callable, Iterable, Mapping
|
|
9
|
+
from concurrent.futures import Future, ThreadPoolExecutor
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from types import TracebackType
|
|
12
|
+
from typing import Any, Literal, Self, TypeVar
|
|
13
|
+
from urllib.parse import urlsplit
|
|
14
|
+
|
|
15
|
+
import httpx
|
|
16
|
+
|
|
17
|
+
from ._endpoints import ENDPOINTS
|
|
18
|
+
from ._operations import _AsyncOperations, _SyncOperations
|
|
19
|
+
from ._response import create_api_error, create_raw_response, decode_success_response
|
|
20
|
+
from ._serialization import encode_json_body, encode_query, serialize_request
|
|
21
|
+
from ._version import __version__
|
|
22
|
+
from .errors import (
|
|
23
|
+
AsinConfigurationError,
|
|
24
|
+
AsinSerializationError,
|
|
25
|
+
AsinTransportError,
|
|
26
|
+
)
|
|
27
|
+
from .models import APIResponse, BatchResult, HTTPMethod, RawResponse, RequestOptions
|
|
28
|
+
|
|
29
|
+
_I = TypeVar("_I")
|
|
30
|
+
_T = TypeVar("_T")
|
|
31
|
+
|
|
32
|
+
DEFAULT_BASE_URL = "https://www.asin.dev/api/v1"
|
|
33
|
+
DEFAULT_TIMEOUT = 120.0
|
|
34
|
+
DEFAULT_CONCURRENCY = 10
|
|
35
|
+
"""Tasks run at the same time by ``batch()``."""
|
|
36
|
+
MAX_RETRIES = 3
|
|
37
|
+
"""Retries after a network error or a 408, 429, 500, 502, 503 or 504 response."""
|
|
38
|
+
RETRY_BACKOFF_FACTOR = 1.5
|
|
39
|
+
"""Each retry waits this many times longer than the previous one (a Retry-After header wins)."""
|
|
40
|
+
DEFAULT_RETRY_DELAY = 1.0
|
|
41
|
+
"""Seconds before the first retry."""
|
|
42
|
+
MAX_RETRY_DELAY = 30.0
|
|
43
|
+
RETRYABLE_STATUSES = frozenset({408, 429, 500, 502, 503, 504})
|
|
44
|
+
API_KEY_ENVIRONMENT_VARIABLE = "ASIN_API_KEY"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass(frozen=True, slots=True)
|
|
48
|
+
class _Configuration:
|
|
49
|
+
api_key: str
|
|
50
|
+
base_url: str
|
|
51
|
+
timeout: float | None
|
|
52
|
+
headers: Mapping[str, str]
|
|
53
|
+
max_retries: int
|
|
54
|
+
retry_delay: float
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass(frozen=True, slots=True)
|
|
58
|
+
class _PreparedRequest:
|
|
59
|
+
method: HTTPMethod
|
|
60
|
+
url: str
|
|
61
|
+
headers: dict[str, str]
|
|
62
|
+
content: bytes | None
|
|
63
|
+
timeout: float | None
|
|
64
|
+
expected: Literal["json", "any"]
|
|
65
|
+
max_retries: int
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class AsinClient(_SyncOperations):
|
|
69
|
+
"""Reusable blocking Asin client. Use it as a context manager or call ``close()``."""
|
|
70
|
+
|
|
71
|
+
__slots__ = ("_closed", "_configuration", "_http_client", "_owns_http_client")
|
|
72
|
+
|
|
73
|
+
def __init__(
|
|
74
|
+
self,
|
|
75
|
+
api_key: str | None = None,
|
|
76
|
+
*,
|
|
77
|
+
base_url: str | None = None,
|
|
78
|
+
timeout: float | None = DEFAULT_TIMEOUT,
|
|
79
|
+
headers: Mapping[str, str] | None = None,
|
|
80
|
+
max_retries: int = MAX_RETRIES,
|
|
81
|
+
retry_delay: float = DEFAULT_RETRY_DELAY,
|
|
82
|
+
http_client: httpx.Client | None = None,
|
|
83
|
+
) -> None:
|
|
84
|
+
self._configuration = _build_configuration(
|
|
85
|
+
api_key, base_url, timeout, headers, max_retries, retry_delay
|
|
86
|
+
)
|
|
87
|
+
if http_client is not None and not isinstance(http_client, httpx.Client):
|
|
88
|
+
raise AsinConfigurationError("http_client must be an httpx.Client when provided.")
|
|
89
|
+
self._owns_http_client = http_client is None
|
|
90
|
+
self._http_client = http_client or httpx.Client(follow_redirects=False)
|
|
91
|
+
self._closed = False
|
|
92
|
+
|
|
93
|
+
def request(
|
|
94
|
+
self,
|
|
95
|
+
method: HTTPMethod,
|
|
96
|
+
path: str,
|
|
97
|
+
params: Mapping[str, Any] | None = None,
|
|
98
|
+
*,
|
|
99
|
+
timeout: float | None = None,
|
|
100
|
+
headers: Mapping[str, str] | None = None,
|
|
101
|
+
max_retries: int | None = None,
|
|
102
|
+
) -> APIResponse:
|
|
103
|
+
"""Send any request to the Asin API, including endpoints newer than this SDK."""
|
|
104
|
+
|
|
105
|
+
options = RequestOptions(
|
|
106
|
+
method=method, timeout=timeout, headers=headers, max_retries=max_retries
|
|
107
|
+
)
|
|
108
|
+
return self._send(_prepare(self._configuration, method, path, params, options, "any"))
|
|
109
|
+
|
|
110
|
+
def batch(
|
|
111
|
+
self,
|
|
112
|
+
items: Iterable[_I],
|
|
113
|
+
task: Callable[[_I], _T],
|
|
114
|
+
*,
|
|
115
|
+
concurrency: int = DEFAULT_CONCURRENCY,
|
|
116
|
+
) -> list[BatchResult[_T]]:
|
|
117
|
+
"""Run ``task`` for every item on ``concurrency`` threads (default 10).
|
|
118
|
+
|
|
119
|
+
Returns one :class:`BatchResult` per item, in input order; a failing item never stops the others.
|
|
120
|
+
The client is thread-safe, so ``task`` can call its methods directly.
|
|
121
|
+
"""
|
|
122
|
+
|
|
123
|
+
_check_concurrency(concurrency)
|
|
124
|
+
values = list(items)
|
|
125
|
+
if not values:
|
|
126
|
+
return []
|
|
127
|
+
with ThreadPoolExecutor(max_workers=min(concurrency, len(values))) as pool:
|
|
128
|
+
futures = [pool.submit(task, value) for value in values]
|
|
129
|
+
return [_settle(index, future) for index, future in enumerate(futures)]
|
|
130
|
+
|
|
131
|
+
def close(self) -> None:
|
|
132
|
+
"""Close transport resources owned by this client."""
|
|
133
|
+
|
|
134
|
+
if self._closed:
|
|
135
|
+
return
|
|
136
|
+
try:
|
|
137
|
+
if self._owns_http_client:
|
|
138
|
+
self._http_client.close()
|
|
139
|
+
finally:
|
|
140
|
+
self._closed = True
|
|
141
|
+
|
|
142
|
+
def __enter__(self) -> Self:
|
|
143
|
+
self._ensure_open()
|
|
144
|
+
return self
|
|
145
|
+
|
|
146
|
+
def __exit__(
|
|
147
|
+
self,
|
|
148
|
+
exc_type: type[BaseException] | None,
|
|
149
|
+
exc_value: BaseException | None,
|
|
150
|
+
traceback: TracebackType | None,
|
|
151
|
+
) -> None:
|
|
152
|
+
self.close()
|
|
153
|
+
|
|
154
|
+
def _call(
|
|
155
|
+
self, name: str, params: dict[str, Any], options: RequestOptions | None
|
|
156
|
+
) -> APIResponse:
|
|
157
|
+
return self._send(_prepare_operation(self._configuration, name, params, options))
|
|
158
|
+
|
|
159
|
+
def _send(self, prepared: _PreparedRequest) -> APIResponse:
|
|
160
|
+
self._ensure_open()
|
|
161
|
+
attempt = 0
|
|
162
|
+
while True:
|
|
163
|
+
try:
|
|
164
|
+
response = self._http_client.request(
|
|
165
|
+
prepared.method,
|
|
166
|
+
prepared.url,
|
|
167
|
+
headers=prepared.headers,
|
|
168
|
+
content=prepared.content,
|
|
169
|
+
timeout=prepared.timeout,
|
|
170
|
+
follow_redirects=False,
|
|
171
|
+
)
|
|
172
|
+
body = response.read()
|
|
173
|
+
except httpx.TimeoutException as cause:
|
|
174
|
+
raise AsinTransportError("Asin request timed out.", cause) from cause
|
|
175
|
+
except Exception as cause:
|
|
176
|
+
if attempt < prepared.max_retries:
|
|
177
|
+
time.sleep(_retry_delay(self._configuration.retry_delay, attempt, None))
|
|
178
|
+
attempt += 1
|
|
179
|
+
continue
|
|
180
|
+
raise AsinTransportError(
|
|
181
|
+
"Asin request failed before an HTTP response body was received.", cause
|
|
182
|
+
) from cause
|
|
183
|
+
raw_response = create_raw_response(response, body)
|
|
184
|
+
if _is_retryable(raw_response) and attempt < prepared.max_retries:
|
|
185
|
+
retry_after = (raw_response.headers.get("retry-after") or (None,))[0]
|
|
186
|
+
time.sleep(_retry_delay(self._configuration.retry_delay, attempt, retry_after))
|
|
187
|
+
attempt += 1
|
|
188
|
+
continue
|
|
189
|
+
return _decode(raw_response, prepared)
|
|
190
|
+
|
|
191
|
+
def _ensure_open(self) -> None:
|
|
192
|
+
if self._closed:
|
|
193
|
+
raise AsinConfigurationError("This AsinClient is closed.")
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
class AsyncAsinClient(_AsyncOperations):
|
|
197
|
+
"""Reusable async-I/O Asin client. Use it as an async context manager or await ``aclose()``."""
|
|
198
|
+
|
|
199
|
+
__slots__ = ("_closed", "_configuration", "_http_client", "_owns_http_client")
|
|
200
|
+
|
|
201
|
+
def __init__(
|
|
202
|
+
self,
|
|
203
|
+
api_key: str | None = None,
|
|
204
|
+
*,
|
|
205
|
+
base_url: str | None = None,
|
|
206
|
+
timeout: float | None = DEFAULT_TIMEOUT,
|
|
207
|
+
headers: Mapping[str, str] | None = None,
|
|
208
|
+
max_retries: int = MAX_RETRIES,
|
|
209
|
+
retry_delay: float = DEFAULT_RETRY_DELAY,
|
|
210
|
+
http_client: httpx.AsyncClient | None = None,
|
|
211
|
+
) -> None:
|
|
212
|
+
self._configuration = _build_configuration(
|
|
213
|
+
api_key, base_url, timeout, headers, max_retries, retry_delay
|
|
214
|
+
)
|
|
215
|
+
if http_client is not None and not isinstance(http_client, httpx.AsyncClient):
|
|
216
|
+
raise AsinConfigurationError("http_client must be an httpx.AsyncClient when provided.")
|
|
217
|
+
self._owns_http_client = http_client is None
|
|
218
|
+
self._http_client = http_client or httpx.AsyncClient(follow_redirects=False)
|
|
219
|
+
self._closed = False
|
|
220
|
+
|
|
221
|
+
async def request(
|
|
222
|
+
self,
|
|
223
|
+
method: HTTPMethod,
|
|
224
|
+
path: str,
|
|
225
|
+
params: Mapping[str, Any] | None = None,
|
|
226
|
+
*,
|
|
227
|
+
timeout: float | None = None,
|
|
228
|
+
headers: Mapping[str, str] | None = None,
|
|
229
|
+
max_retries: int | None = None,
|
|
230
|
+
) -> APIResponse:
|
|
231
|
+
"""Send any request to the Asin API, including endpoints newer than this SDK."""
|
|
232
|
+
|
|
233
|
+
options = RequestOptions(
|
|
234
|
+
method=method, timeout=timeout, headers=headers, max_retries=max_retries
|
|
235
|
+
)
|
|
236
|
+
return await self._send(_prepare(self._configuration, method, path, params, options, "any"))
|
|
237
|
+
|
|
238
|
+
async def batch(
|
|
239
|
+
self,
|
|
240
|
+
items: Iterable[_I],
|
|
241
|
+
task: Callable[[_I], Awaitable[_T]],
|
|
242
|
+
*,
|
|
243
|
+
concurrency: int = DEFAULT_CONCURRENCY,
|
|
244
|
+
) -> list[BatchResult[_T]]:
|
|
245
|
+
"""Await ``task`` for every item with at most ``concurrency`` in flight (default 10).
|
|
246
|
+
|
|
247
|
+
Returns one :class:`BatchResult` per item, in input order; a failing item never stops the others.
|
|
248
|
+
"""
|
|
249
|
+
|
|
250
|
+
_check_concurrency(concurrency)
|
|
251
|
+
semaphore = asyncio.Semaphore(concurrency)
|
|
252
|
+
|
|
253
|
+
async def run(index: int, value: _I) -> BatchResult[_T]:
|
|
254
|
+
async with semaphore:
|
|
255
|
+
try:
|
|
256
|
+
return BatchResult(index=index, value=await task(value))
|
|
257
|
+
except Exception as error:
|
|
258
|
+
return BatchResult(index=index, error=error)
|
|
259
|
+
|
|
260
|
+
return list(await asyncio.gather(*(run(i, v) for i, v in enumerate(items))))
|
|
261
|
+
|
|
262
|
+
async def aclose(self) -> None:
|
|
263
|
+
"""Close transport resources owned by this client."""
|
|
264
|
+
|
|
265
|
+
if self._closed:
|
|
266
|
+
return
|
|
267
|
+
try:
|
|
268
|
+
if self._owns_http_client:
|
|
269
|
+
await self._http_client.aclose()
|
|
270
|
+
finally:
|
|
271
|
+
self._closed = True
|
|
272
|
+
|
|
273
|
+
async def __aenter__(self) -> Self:
|
|
274
|
+
self._ensure_open()
|
|
275
|
+
return self
|
|
276
|
+
|
|
277
|
+
async def __aexit__(
|
|
278
|
+
self,
|
|
279
|
+
exc_type: type[BaseException] | None,
|
|
280
|
+
exc_value: BaseException | None,
|
|
281
|
+
traceback: TracebackType | None,
|
|
282
|
+
) -> None:
|
|
283
|
+
await self.aclose()
|
|
284
|
+
|
|
285
|
+
async def _call(
|
|
286
|
+
self, name: str, params: dict[str, Any], options: RequestOptions | None
|
|
287
|
+
) -> APIResponse:
|
|
288
|
+
return await self._send(_prepare_operation(self._configuration, name, params, options))
|
|
289
|
+
|
|
290
|
+
async def _send(self, prepared: _PreparedRequest) -> APIResponse:
|
|
291
|
+
self._ensure_open()
|
|
292
|
+
attempt = 0
|
|
293
|
+
while True:
|
|
294
|
+
try:
|
|
295
|
+
response = await self._http_client.request(
|
|
296
|
+
prepared.method,
|
|
297
|
+
prepared.url,
|
|
298
|
+
headers=prepared.headers,
|
|
299
|
+
content=prepared.content,
|
|
300
|
+
timeout=prepared.timeout,
|
|
301
|
+
follow_redirects=False,
|
|
302
|
+
)
|
|
303
|
+
body = await response.aread()
|
|
304
|
+
except httpx.TimeoutException as cause:
|
|
305
|
+
raise AsinTransportError("Asin request timed out.", cause) from cause
|
|
306
|
+
except Exception as cause:
|
|
307
|
+
if attempt < prepared.max_retries:
|
|
308
|
+
await asyncio.sleep(
|
|
309
|
+
_retry_delay(self._configuration.retry_delay, attempt, None)
|
|
310
|
+
)
|
|
311
|
+
attempt += 1
|
|
312
|
+
continue
|
|
313
|
+
raise AsinTransportError(
|
|
314
|
+
"Asin request failed before an HTTP response body was received.", cause
|
|
315
|
+
) from cause
|
|
316
|
+
raw_response = create_raw_response(response, body)
|
|
317
|
+
if _is_retryable(raw_response) and attempt < prepared.max_retries:
|
|
318
|
+
retry_after = (raw_response.headers.get("retry-after") or (None,))[0]
|
|
319
|
+
await asyncio.sleep(
|
|
320
|
+
_retry_delay(self._configuration.retry_delay, attempt, retry_after)
|
|
321
|
+
)
|
|
322
|
+
attempt += 1
|
|
323
|
+
continue
|
|
324
|
+
return _decode(raw_response, prepared)
|
|
325
|
+
|
|
326
|
+
def _ensure_open(self) -> None:
|
|
327
|
+
if self._closed:
|
|
328
|
+
raise AsinConfigurationError("This AsyncAsinClient is closed.")
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def _build_configuration(
|
|
332
|
+
api_key: str | None,
|
|
333
|
+
base_url: str | None,
|
|
334
|
+
timeout: float | None,
|
|
335
|
+
headers: Mapping[str, str] | None,
|
|
336
|
+
max_retries: int = MAX_RETRIES,
|
|
337
|
+
retry_delay: float = DEFAULT_RETRY_DELAY,
|
|
338
|
+
) -> _Configuration:
|
|
339
|
+
key = api_key if api_key is not None else os.environ.get(API_KEY_ENVIRONMENT_VARIABLE)
|
|
340
|
+
if not isinstance(key, str) or not key.strip():
|
|
341
|
+
raise AsinConfigurationError(
|
|
342
|
+
f"A non-blank Asin API key is required. Pass api_key or set {API_KEY_ENVIRONMENT_VARIABLE}."
|
|
343
|
+
)
|
|
344
|
+
if any(ch in key for ch in "\r\n"):
|
|
345
|
+
raise AsinConfigurationError("The Asin API key cannot be used in an HTTP header.")
|
|
346
|
+
url = (base_url or DEFAULT_BASE_URL).rstrip("/")
|
|
347
|
+
parts = urlsplit(url)
|
|
348
|
+
if parts.scheme not in ("http", "https") or not parts.netloc:
|
|
349
|
+
raise AsinConfigurationError("base_url must be an absolute http or https URL.")
|
|
350
|
+
if timeout is not None and (not isinstance(timeout, (int, float)) or timeout <= 0):
|
|
351
|
+
raise AsinConfigurationError("timeout must be a positive number of seconds or None.")
|
|
352
|
+
if isinstance(max_retries, bool) or not isinstance(max_retries, int) or max_retries < 0:
|
|
353
|
+
raise AsinConfigurationError("max_retries must be a non-negative integer.")
|
|
354
|
+
if not isinstance(retry_delay, (int, float)) or retry_delay < 0:
|
|
355
|
+
raise AsinConfigurationError("retry_delay must be a non-negative number of seconds.")
|
|
356
|
+
return _Configuration(
|
|
357
|
+
api_key=key,
|
|
358
|
+
base_url=url,
|
|
359
|
+
timeout=timeout,
|
|
360
|
+
headers=dict(headers or {}),
|
|
361
|
+
max_retries=max_retries,
|
|
362
|
+
retry_delay=float(retry_delay),
|
|
363
|
+
)
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def _prepare_operation(
|
|
367
|
+
configuration: _Configuration,
|
|
368
|
+
name: str,
|
|
369
|
+
params: Mapping[str, Any],
|
|
370
|
+
options: RequestOptions | None,
|
|
371
|
+
) -> _PreparedRequest:
|
|
372
|
+
endpoint = ENDPOINTS[name]
|
|
373
|
+
method = (options.method if options else None) or endpoint.methods[0]
|
|
374
|
+
if method not in endpoint.methods:
|
|
375
|
+
raise AsinConfigurationError(
|
|
376
|
+
f"{endpoint.path} supports {', '.join(endpoint.methods)}, not {method}."
|
|
377
|
+
)
|
|
378
|
+
for required in endpoint.required:
|
|
379
|
+
if params.get(required) is None:
|
|
380
|
+
raise AsinSerializationError(f'The "{required}" parameter is required.', required)
|
|
381
|
+
return _prepare(configuration, method, endpoint.path, params, options, endpoint.response)
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def _prepare(
|
|
385
|
+
configuration: _Configuration,
|
|
386
|
+
method: HTTPMethod,
|
|
387
|
+
path: str,
|
|
388
|
+
params: Mapping[str, Any] | None,
|
|
389
|
+
options: RequestOptions | None,
|
|
390
|
+
expected: Literal["json", "any"],
|
|
391
|
+
) -> _PreparedRequest:
|
|
392
|
+
if method not in ("GET", "POST", "PATCH", "DELETE"):
|
|
393
|
+
raise AsinConfigurationError(f"Unsupported HTTP method: {method!r}.")
|
|
394
|
+
if not isinstance(path, str) or not path.startswith("/"):
|
|
395
|
+
raise AsinConfigurationError('The request path must start with "/".')
|
|
396
|
+
serialized = serialize_request(method, path, params)
|
|
397
|
+
url = configuration.base_url + serialized.path
|
|
398
|
+
if serialized.query:
|
|
399
|
+
url += "?" + encode_query(serialized.query)
|
|
400
|
+
headers = {
|
|
401
|
+
"Accept": "application/json, */*;q=0.8",
|
|
402
|
+
"User-Agent": f"asin-python/{__version__}",
|
|
403
|
+
**configuration.headers,
|
|
404
|
+
**dict((options.headers if options else None) or {}),
|
|
405
|
+
"Authorization": f"Bearer {configuration.api_key}",
|
|
406
|
+
}
|
|
407
|
+
content = None
|
|
408
|
+
if serialized.body is not None:
|
|
409
|
+
headers["Content-Type"] = "application/json"
|
|
410
|
+
content = encode_json_body(serialized.body)
|
|
411
|
+
timeout = options.timeout if options and options.timeout is not None else configuration.timeout
|
|
412
|
+
max_retries = (
|
|
413
|
+
options.max_retries
|
|
414
|
+
if options and options.max_retries is not None
|
|
415
|
+
else configuration.max_retries
|
|
416
|
+
)
|
|
417
|
+
return _PreparedRequest(method, url, headers, content, timeout, expected, max_retries)
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
def _decode(raw_response: RawResponse, prepared: _PreparedRequest) -> APIResponse:
|
|
421
|
+
if not 200 <= raw_response.status <= 299:
|
|
422
|
+
raise create_api_error(raw_response)
|
|
423
|
+
return decode_success_response(raw_response, prepared.expected)
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def _check_concurrency(concurrency: int) -> None:
|
|
427
|
+
if isinstance(concurrency, bool) or not isinstance(concurrency, int) or concurrency < 1:
|
|
428
|
+
raise AsinConfigurationError("concurrency must be a positive integer.")
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
def _settle(index: int, future: Future[_T]) -> BatchResult[_T]:
|
|
432
|
+
error = future.exception()
|
|
433
|
+
if error is not None:
|
|
434
|
+
return BatchResult(index=index, error=error)
|
|
435
|
+
return BatchResult(index=index, value=future.result())
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def _is_retryable(raw_response: RawResponse) -> bool:
|
|
439
|
+
return raw_response.status in RETRYABLE_STATUSES
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
def _retry_delay(base: float, attempt: int, retry_after: str | None) -> float:
|
|
443
|
+
if retry_after is not None:
|
|
444
|
+
try:
|
|
445
|
+
seconds = float(retry_after)
|
|
446
|
+
except ValueError:
|
|
447
|
+
seconds = -1.0
|
|
448
|
+
if seconds >= 0:
|
|
449
|
+
return min(seconds, 60.0)
|
|
450
|
+
return float(min(base * RETRY_BACKOFF_FACTOR**attempt, MAX_RETRY_DELAY))
|
asin/errors.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""Asin SDK error categories."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from .models import RawResponse
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class AsinError(Exception):
|
|
11
|
+
"""Base class for all SDK-defined errors."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class AsinConfigurationError(AsinError):
|
|
15
|
+
"""The client configuration is missing or unusable."""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class AsinSerializationError(AsinError):
|
|
19
|
+
"""A request value cannot be represented safely on the wire."""
|
|
20
|
+
|
|
21
|
+
param: str | None
|
|
22
|
+
|
|
23
|
+
def __init__(self, message: str, param: str | None = None) -> None:
|
|
24
|
+
super().__init__(message)
|
|
25
|
+
self.param = param
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class AsinTransportError(AsinError):
|
|
29
|
+
"""The request failed before a complete HTTP response was received."""
|
|
30
|
+
|
|
31
|
+
cause: Exception
|
|
32
|
+
|
|
33
|
+
def __init__(self, message: str, cause: Exception) -> None:
|
|
34
|
+
super().__init__(message)
|
|
35
|
+
self.cause = cause
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class AsinAPIError(AsinError):
|
|
39
|
+
"""Asin returned a non-success HTTP status."""
|
|
40
|
+
|
|
41
|
+
status: int
|
|
42
|
+
error_message: str | None
|
|
43
|
+
response_body: Any | None
|
|
44
|
+
raw_response: RawResponse
|
|
45
|
+
|
|
46
|
+
def __init__(
|
|
47
|
+
self,
|
|
48
|
+
*,
|
|
49
|
+
raw_response: RawResponse,
|
|
50
|
+
response_body: Any | None = None,
|
|
51
|
+
error_message: str | None = None,
|
|
52
|
+
) -> None:
|
|
53
|
+
super().__init__(
|
|
54
|
+
error_message or f"Asin API request failed with status {raw_response.status}."
|
|
55
|
+
)
|
|
56
|
+
self.status = raw_response.status
|
|
57
|
+
self.error_message = error_message
|
|
58
|
+
self.response_body = response_body
|
|
59
|
+
self.raw_response = raw_response
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class AsinResponseDecodingError(AsinError):
|
|
63
|
+
"""A successful response could not be decoded as the documented representation."""
|
|
64
|
+
|
|
65
|
+
raw_response: RawResponse
|
|
66
|
+
cause: Exception | None
|
|
67
|
+
|
|
68
|
+
def __init__(
|
|
69
|
+
self, message: str, raw_response: RawResponse, cause: Exception | None = None
|
|
70
|
+
) -> None:
|
|
71
|
+
super().__init__(message)
|
|
72
|
+
self.raw_response = raw_response
|
|
73
|
+
self.cause = cause
|