arfigyelo-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.
- arfigyelo_api/__init__.py +61 -0
- arfigyelo_api/_version.py +3 -0
- arfigyelo_api/cache.py +37 -0
- arfigyelo_api/client.py +785 -0
- arfigyelo_api/errors.py +51 -0
- arfigyelo_api/mapping.py +124 -0
- arfigyelo_api/models.py +198 -0
- arfigyelo_api/py.typed +0 -0
- arfigyelo_api-0.1.0.dist-info/METADATA +141 -0
- arfigyelo_api-0.1.0.dist-info/RECORD +12 -0
- arfigyelo_api-0.1.0.dist-info/WHEEL +4 -0
- arfigyelo_api-0.1.0.dist-info/licenses/LICENSE +21 -0
arfigyelo_api/client.py
ADDED
|
@@ -0,0 +1,785 @@
|
|
|
1
|
+
"""Sync and async clients for the Árfigyelő API.
|
|
2
|
+
|
|
3
|
+
One request/validation/caching implementation, two facades over httpx
|
|
4
|
+
(docs/adr/0002-dual-sync-async-clients.md). Structural indexes (categories,
|
|
5
|
+
chains, shops) are always TTL-cached; price responses are cached only when
|
|
6
|
+
``cache_prices=True``.
|
|
7
|
+
|
|
8
|
+
Validation is local and raises :class:`ArfigyeloValidationError` before any
|
|
9
|
+
request for exactly the arguments the API would answer with a misleading 500
|
|
10
|
+
(docs/adr/0003-client-side-prevalidation.md). ``limit > 48`` is *not*
|
|
11
|
+
rejected: the server silently clips it.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from collections.abc import AsyncIterator, Awaitable, Callable, Iterator, Mapping, Sequence
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
import httpx
|
|
20
|
+
from pydantic import BaseModel, ConfigDict, Field, ValidationError
|
|
21
|
+
|
|
22
|
+
from ._version import __version__
|
|
23
|
+
from .cache import TTLCache
|
|
24
|
+
from .errors import (
|
|
25
|
+
ArfigyeloApiError,
|
|
26
|
+
ArfigyeloConnectionError,
|
|
27
|
+
ArfigyeloUnexpectedResponseError,
|
|
28
|
+
ArfigyeloValidationError,
|
|
29
|
+
)
|
|
30
|
+
from .mapping import CategoryIndex, ChainIndex, ShopIndex
|
|
31
|
+
from .models import (
|
|
32
|
+
Category,
|
|
33
|
+
CategoryOrder,
|
|
34
|
+
Chain,
|
|
35
|
+
ProductDetail,
|
|
36
|
+
ProductPage,
|
|
37
|
+
ProductSummary,
|
|
38
|
+
SearchOrder,
|
|
39
|
+
Shop,
|
|
40
|
+
ShopPriceEntry,
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
DEFAULT_BASE_URL = "https://arfigyelo.gvh.hu/api"
|
|
44
|
+
DEFAULT_TIMEOUT = 10.0
|
|
45
|
+
DEFAULT_TTL = 12 * 3600.0
|
|
46
|
+
LIMIT_CAP = 48 # server clips anything above; the client passes it through
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
# --- shared validation (local, pre-request) -------------------------------------
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _require_non_negative_int(field: str, value: Any) -> int:
|
|
53
|
+
if isinstance(value, bool) or not isinstance(value, int) or value < 0:
|
|
54
|
+
raise ArfigyeloValidationError(field, f"must be a non-negative integer, got {value!r}")
|
|
55
|
+
return value
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _require_order(field: str, order: Any, allowed: type[CategoryOrder] | type[SearchOrder]) -> str:
|
|
59
|
+
value = order.value if isinstance(order, CategoryOrder | SearchOrder) else order
|
|
60
|
+
if isinstance(value, str):
|
|
61
|
+
try:
|
|
62
|
+
order_value: str = allowed(value).value
|
|
63
|
+
return order_value
|
|
64
|
+
except ValueError:
|
|
65
|
+
pass
|
|
66
|
+
raise ArfigyeloValidationError(
|
|
67
|
+
field, f"must be one of {[entry.value for entry in allowed]}, got {order!r}"
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _require_query(q: Any) -> str:
|
|
72
|
+
if isinstance(q, str):
|
|
73
|
+
trimmed = q.strip()
|
|
74
|
+
if len(trimmed) >= 3:
|
|
75
|
+
return trimmed
|
|
76
|
+
raise ArfigyeloValidationError(
|
|
77
|
+
"q", f"must be a string of at least 3 characters after trimming, got {q!r}"
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _require_shop_ids(field: str, shop_ids: Sequence[str] | None) -> str | None:
|
|
82
|
+
if shop_ids is None:
|
|
83
|
+
return None
|
|
84
|
+
ids = list(shop_ids)
|
|
85
|
+
if not ids or any(not isinstance(identifier, str) or not identifier for identifier in ids):
|
|
86
|
+
raise ArfigyeloValidationError(
|
|
87
|
+
field, "must be a non-empty sequence of non-empty shop uuids"
|
|
88
|
+
)
|
|
89
|
+
return ",".join(ids)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _require_non_empty_str(field: str, value: Any) -> str:
|
|
93
|
+
if not isinstance(value, str) or not value:
|
|
94
|
+
raise ArfigyeloValidationError(field, "must be a non-empty string")
|
|
95
|
+
return value
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
# --- shared response handling ---------------------------------------------------
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _decode(response: httpx.Response) -> Any:
|
|
102
|
+
"""Parse a response body, raising for non-JSON bodies and the API error envelope."""
|
|
103
|
+
try:
|
|
104
|
+
data: Any = response.json()
|
|
105
|
+
except ValueError as exc:
|
|
106
|
+
raise ArfigyeloUnexpectedResponseError(response.status_code, response.text) from exc
|
|
107
|
+
if (
|
|
108
|
+
isinstance(data, dict)
|
|
109
|
+
and isinstance(data.get("code"), str)
|
|
110
|
+
and isinstance(data.get("message"), str)
|
|
111
|
+
):
|
|
112
|
+
raise ArfigyeloApiError(data["code"], data["message"], response.status_code)
|
|
113
|
+
return data
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _validate[ModelT: BaseModel](
|
|
117
|
+
model: type[ModelT], data: Any, response: httpx.Response
|
|
118
|
+
) -> ModelT:
|
|
119
|
+
try:
|
|
120
|
+
return model.model_validate(data)
|
|
121
|
+
except ValidationError as exc:
|
|
122
|
+
raise ArfigyeloUnexpectedResponseError(response.status_code, response.text) from exc
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _cached[T](fetch: Callable[[], T], cache: TTLCache[Any], key: Any) -> T:
|
|
126
|
+
cached_value: T | None = cache.get(key)
|
|
127
|
+
if cached_value is None:
|
|
128
|
+
result = fetch()
|
|
129
|
+
cache.set(key, result)
|
|
130
|
+
return result
|
|
131
|
+
return cached_value
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
async def _async_cached[T](fetch: Callable[[], Awaitable[T]], cache: TTLCache[Any], key: Any) -> T:
|
|
135
|
+
"""Async counterpart of _cached; the stored value is the awaited result.
|
|
136
|
+
|
|
137
|
+
Concurrent calls with the same empty-cache key race into redundant
|
|
138
|
+
fetches, never corruption.
|
|
139
|
+
"""
|
|
140
|
+
cached_value: T | None = cache.get(key)
|
|
141
|
+
if cached_value is not None:
|
|
142
|
+
return cached_value
|
|
143
|
+
result = await fetch()
|
|
144
|
+
cache.set(key, result)
|
|
145
|
+
return result
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
# --- private wire envelopes (single-key response wrappers) ----------------------
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
class _CategoryList(BaseModel):
|
|
152
|
+
model_config = ConfigDict(frozen=True)
|
|
153
|
+
|
|
154
|
+
categories: list[Category]
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
class _ChainList(BaseModel):
|
|
158
|
+
model_config = ConfigDict(frozen=True)
|
|
159
|
+
|
|
160
|
+
chain_stores: list[Chain] = Field(alias="chainStores")
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
class _ShopList(BaseModel):
|
|
164
|
+
model_config = ConfigDict(frozen=True)
|
|
165
|
+
|
|
166
|
+
shops: list[Shop]
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
class _ShopPriceList(BaseModel):
|
|
170
|
+
model_config = ConfigDict(frozen=True)
|
|
171
|
+
|
|
172
|
+
shops: list[ShopPriceEntry]
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
class _ClientOptions:
|
|
176
|
+
"""Constructor kwargs shared verbatim by both facades."""
|
|
177
|
+
|
|
178
|
+
def __init__(
|
|
179
|
+
self,
|
|
180
|
+
*,
|
|
181
|
+
base_url: str,
|
|
182
|
+
timeout: float,
|
|
183
|
+
retries: int,
|
|
184
|
+
ttl: float | None,
|
|
185
|
+
cache_prices: bool,
|
|
186
|
+
user_agent: str,
|
|
187
|
+
headers: Mapping[str, str] | None,
|
|
188
|
+
) -> None:
|
|
189
|
+
self.base_url = base_url
|
|
190
|
+
self.timeout = timeout
|
|
191
|
+
self.retries = retries
|
|
192
|
+
self.ttl = ttl
|
|
193
|
+
self.cache_prices = cache_prices
|
|
194
|
+
self.headers: dict[str, str] = {"Accept": "application/json", "User-Agent": user_agent}
|
|
195
|
+
if headers is not None:
|
|
196
|
+
self.headers.update(dict(headers))
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
class ArfigyeloClient:
|
|
200
|
+
"""Synchronous client for the Árfigyelő API."""
|
|
201
|
+
|
|
202
|
+
def __init__(
|
|
203
|
+
self,
|
|
204
|
+
*,
|
|
205
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
206
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
207
|
+
retries: int = 0,
|
|
208
|
+
ttl: float | None = DEFAULT_TTL,
|
|
209
|
+
cache_prices: bool = False,
|
|
210
|
+
user_agent: str = f"arfigyelo-api/{__version__}",
|
|
211
|
+
headers: Mapping[str, str] | None = None,
|
|
212
|
+
transport: httpx.BaseTransport | None = None,
|
|
213
|
+
) -> None:
|
|
214
|
+
options = _ClientOptions(
|
|
215
|
+
base_url=base_url,
|
|
216
|
+
timeout=timeout,
|
|
217
|
+
retries=retries,
|
|
218
|
+
ttl=ttl,
|
|
219
|
+
cache_prices=cache_prices,
|
|
220
|
+
user_agent=user_agent,
|
|
221
|
+
headers=headers,
|
|
222
|
+
)
|
|
223
|
+
self._cache_prices = options.cache_prices
|
|
224
|
+
self._index_cache: TTLCache[Any] = TTLCache[Any](options.ttl)
|
|
225
|
+
self._price_cache: TTLCache[Any] = TTLCache[Any](options.ttl)
|
|
226
|
+
if transport is None:
|
|
227
|
+
transport = httpx.HTTPTransport(retries=options.retries)
|
|
228
|
+
self._http = httpx.Client(
|
|
229
|
+
base_url=options.base_url,
|
|
230
|
+
timeout=options.timeout,
|
|
231
|
+
transport=transport,
|
|
232
|
+
headers=options.headers,
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
# --- lifecycle -----------------------------------------------------------
|
|
236
|
+
|
|
237
|
+
def close(self) -> None:
|
|
238
|
+
self._http.close()
|
|
239
|
+
|
|
240
|
+
def __enter__(self) -> ArfigyeloClient:
|
|
241
|
+
return self
|
|
242
|
+
|
|
243
|
+
def __exit__(self, *args: object) -> None:
|
|
244
|
+
self.close()
|
|
245
|
+
|
|
246
|
+
# --- transport plumbing ----------------------------------------------------
|
|
247
|
+
|
|
248
|
+
def _get(self, path: str, params: Mapping[str, str] | None = None) -> httpx.Response:
|
|
249
|
+
try:
|
|
250
|
+
return self._http.get(path, params=params)
|
|
251
|
+
except httpx.TransportError as exc:
|
|
252
|
+
raise ArfigyeloConnectionError(str(exc)) from exc
|
|
253
|
+
|
|
254
|
+
def _model[ModelT: BaseModel](
|
|
255
|
+
self, model: type[ModelT], path: str, params: Mapping[str, str] | None = None
|
|
256
|
+
) -> ModelT:
|
|
257
|
+
response = self._get(path, params)
|
|
258
|
+
data = _decode(response)
|
|
259
|
+
return _validate(model, data, response)
|
|
260
|
+
|
|
261
|
+
@staticmethod
|
|
262
|
+
def _price_key(path: str, params: Mapping[str, str]) -> tuple[Any, ...]:
|
|
263
|
+
return (path, tuple(sorted(params.items())))
|
|
264
|
+
|
|
265
|
+
# --- structural endpoints (always cached) ----------------------------------
|
|
266
|
+
|
|
267
|
+
def get_categories(self) -> list[Category]:
|
|
268
|
+
"""GET /categories — the full category tree (cached with ttl)."""
|
|
269
|
+
|
|
270
|
+
def fetch() -> list[Category]:
|
|
271
|
+
return self._model(_CategoryList, "categories").categories
|
|
272
|
+
|
|
273
|
+
return _cached(fetch, self._index_cache, "categories")
|
|
274
|
+
|
|
275
|
+
def get_chains(self) -> list[Chain]:
|
|
276
|
+
"""GET /chain-stores — all retail chains (cached with ttl)."""
|
|
277
|
+
|
|
278
|
+
def fetch() -> list[Chain]:
|
|
279
|
+
return self._model(_ChainList, "chain-stores").chain_stores
|
|
280
|
+
|
|
281
|
+
return _cached(fetch, self._index_cache, "chain-stores")
|
|
282
|
+
|
|
283
|
+
def get_shops(self) -> list[Shop]:
|
|
284
|
+
"""GET /shops — all physical shops (cached with ttl)."""
|
|
285
|
+
|
|
286
|
+
def fetch() -> list[Shop]:
|
|
287
|
+
return self._model(_ShopList, "shops").shops
|
|
288
|
+
|
|
289
|
+
return _cached(fetch, self._index_cache, "shops")
|
|
290
|
+
|
|
291
|
+
# --- product endpoints (cached only under cache_prices=True) ---------------
|
|
292
|
+
|
|
293
|
+
def get_products_by_category(
|
|
294
|
+
self,
|
|
295
|
+
category_id: int,
|
|
296
|
+
*,
|
|
297
|
+
limit: int = 12,
|
|
298
|
+
offset: int = 0,
|
|
299
|
+
order: CategoryOrder | str = CategoryOrder.UNIT_AMOUNT_ASC,
|
|
300
|
+
shop_ids: Sequence[str] | None = None,
|
|
301
|
+
) -> ProductPage:
|
|
302
|
+
"""GET /products-by-category/{id} — one page of a category listing."""
|
|
303
|
+
limit_v = _require_non_negative_int("limit", limit)
|
|
304
|
+
offset_v = _require_non_negative_int("offset", offset)
|
|
305
|
+
order_v = _require_order("order", order, CategoryOrder)
|
|
306
|
+
shop_ids_v = _require_shop_ids("shop_ids", shop_ids)
|
|
307
|
+
path = f"products-by-category/{category_id}"
|
|
308
|
+
params: dict[str, str] = {"limit": str(limit_v), "offset": str(offset_v), "order": order_v}
|
|
309
|
+
if shop_ids_v is not None:
|
|
310
|
+
params["shopIds"] = shop_ids_v
|
|
311
|
+
|
|
312
|
+
def fetch() -> ProductPage:
|
|
313
|
+
return self._model(ProductPage, path, params)
|
|
314
|
+
|
|
315
|
+
if self._cache_prices:
|
|
316
|
+
return _cached(fetch, self._price_cache, self._price_key(path, params))
|
|
317
|
+
return fetch()
|
|
318
|
+
|
|
319
|
+
def get_products_by_path(
|
|
320
|
+
self,
|
|
321
|
+
path: str | Sequence[str],
|
|
322
|
+
*,
|
|
323
|
+
limit: int = 12,
|
|
324
|
+
offset: int = 0,
|
|
325
|
+
order: CategoryOrder | str = CategoryOrder.UNIT_AMOUNT_ASC,
|
|
326
|
+
shop_ids: Sequence[str] | None = None,
|
|
327
|
+
) -> ProductPage:
|
|
328
|
+
"""Category listing resolved by category path (mapping layer)."""
|
|
329
|
+
category_id = self.get_category_by_path(path).id
|
|
330
|
+
return self.get_products_by_category(
|
|
331
|
+
category_id, limit=limit, offset=offset, order=order, shop_ids=shop_ids
|
|
332
|
+
)
|
|
333
|
+
|
|
334
|
+
def search(
|
|
335
|
+
self,
|
|
336
|
+
q: str,
|
|
337
|
+
*,
|
|
338
|
+
limit: int = 48,
|
|
339
|
+
offset: int = 0,
|
|
340
|
+
order: SearchOrder | str = SearchOrder.RELEVANCE,
|
|
341
|
+
shop_ids: Sequence[str] | None = None,
|
|
342
|
+
) -> ProductPage:
|
|
343
|
+
"""GET /search — text search (accent-insensitive server-side)."""
|
|
344
|
+
query = _require_query(q)
|
|
345
|
+
limit_v = _require_non_negative_int("limit", limit)
|
|
346
|
+
offset_v = _require_non_negative_int("offset", offset)
|
|
347
|
+
order_v = _require_order("order", order, SearchOrder)
|
|
348
|
+
shop_ids_v = _require_shop_ids("shop_ids", shop_ids)
|
|
349
|
+
params: dict[str, str] = {
|
|
350
|
+
"q": query,
|
|
351
|
+
"limit": str(limit_v),
|
|
352
|
+
"offset": str(offset_v),
|
|
353
|
+
"order": order_v,
|
|
354
|
+
}
|
|
355
|
+
if shop_ids_v is not None:
|
|
356
|
+
params["shopIds"] = shop_ids_v
|
|
357
|
+
|
|
358
|
+
def fetch() -> ProductPage:
|
|
359
|
+
return self._model(ProductPage, "search", params)
|
|
360
|
+
|
|
361
|
+
if self._cache_prices:
|
|
362
|
+
return _cached(fetch, self._price_cache, self._price_key("search", params))
|
|
363
|
+
return fetch()
|
|
364
|
+
|
|
365
|
+
def get_product(self, product_id: str) -> ProductDetail:
|
|
366
|
+
"""GET /product/{id} — product detail with chain-level prices."""
|
|
367
|
+
product_id = _require_non_empty_str("product_id", product_id)
|
|
368
|
+
path = f"product/{product_id}"
|
|
369
|
+
|
|
370
|
+
def fetch() -> ProductDetail:
|
|
371
|
+
return self._model(ProductDetail, path)
|
|
372
|
+
|
|
373
|
+
if self._cache_prices:
|
|
374
|
+
return _cached(fetch, self._price_cache, self._price_key(path, {}))
|
|
375
|
+
return fetch()
|
|
376
|
+
|
|
377
|
+
def get_product_shop_prices(
|
|
378
|
+
self, product_id: str, shop_uuids: Sequence[str]
|
|
379
|
+
) -> list[ShopPriceEntry]:
|
|
380
|
+
"""GET /product/{id}/shop/{shopUuids} — per-shop prices for one product.
|
|
381
|
+
|
|
382
|
+
Only shops that have a price are returned; loyalty prices never appear
|
|
383
|
+
here (NORMAL and DISCOUNTED only).
|
|
384
|
+
"""
|
|
385
|
+
product_id = _require_non_empty_str("product_id", product_id)
|
|
386
|
+
joined = _require_shop_ids("shop_uuids", shop_uuids)
|
|
387
|
+
assert joined is not None # _require_shop_ids raises on empty/None input
|
|
388
|
+
path = f"product/{product_id}/shop/{joined}"
|
|
389
|
+
|
|
390
|
+
def fetch() -> list[ShopPriceEntry]:
|
|
391
|
+
return self._model(_ShopPriceList, path).shops
|
|
392
|
+
|
|
393
|
+
if self._cache_prices:
|
|
394
|
+
return _cached(fetch, self._price_cache, self._price_key(path, {}))
|
|
395
|
+
return fetch()
|
|
396
|
+
|
|
397
|
+
# --- pagination iterators (stop on empty page, never on count) -------------
|
|
398
|
+
|
|
399
|
+
def iter_products_by_category(
|
|
400
|
+
self,
|
|
401
|
+
category_id: int,
|
|
402
|
+
*,
|
|
403
|
+
limit: int = LIMIT_CAP,
|
|
404
|
+
order: CategoryOrder | str = CategoryOrder.UNIT_AMOUNT_ASC,
|
|
405
|
+
shop_ids: Sequence[str] | None = None,
|
|
406
|
+
) -> Iterator[ProductSummary]:
|
|
407
|
+
"""Yield every product of a category, paging internally.
|
|
408
|
+
|
|
409
|
+
Terminates on an empty ``products`` page; ``count`` is unreliable on
|
|
410
|
+
empty pages (API quirk #1).
|
|
411
|
+
"""
|
|
412
|
+
offset = 0
|
|
413
|
+
while True:
|
|
414
|
+
page = self.get_products_by_category(
|
|
415
|
+
category_id, limit=limit, offset=offset, order=order, shop_ids=shop_ids
|
|
416
|
+
)
|
|
417
|
+
yield from page.products
|
|
418
|
+
if not page.products:
|
|
419
|
+
return
|
|
420
|
+
offset += len(page.products)
|
|
421
|
+
|
|
422
|
+
def iter_products_by_path(
|
|
423
|
+
self,
|
|
424
|
+
path: str | Sequence[str],
|
|
425
|
+
*,
|
|
426
|
+
limit: int = LIMIT_CAP,
|
|
427
|
+
order: CategoryOrder | str = CategoryOrder.UNIT_AMOUNT_ASC,
|
|
428
|
+
shop_ids: Sequence[str] | None = None,
|
|
429
|
+
) -> Iterator[ProductSummary]:
|
|
430
|
+
"""Category listing iterator resolved by category path."""
|
|
431
|
+
category_id = self.get_category_by_path(path).id
|
|
432
|
+
yield from self.iter_products_by_category(
|
|
433
|
+
category_id, limit=limit, order=order, shop_ids=shop_ids
|
|
434
|
+
)
|
|
435
|
+
|
|
436
|
+
def iter_search(
|
|
437
|
+
self,
|
|
438
|
+
q: str,
|
|
439
|
+
*,
|
|
440
|
+
limit: int = LIMIT_CAP,
|
|
441
|
+
order: SearchOrder | str = SearchOrder.RELEVANCE,
|
|
442
|
+
shop_ids: Sequence[str] | None = None,
|
|
443
|
+
) -> Iterator[ProductSummary]:
|
|
444
|
+
"""Yield every search result, paging internally."""
|
|
445
|
+
offset = 0
|
|
446
|
+
while True:
|
|
447
|
+
page = self.search(q, limit=limit, offset=offset, order=order, shop_ids=shop_ids)
|
|
448
|
+
yield from page.products
|
|
449
|
+
if not page.products:
|
|
450
|
+
return
|
|
451
|
+
offset += len(page.products)
|
|
452
|
+
|
|
453
|
+
# --- mapping layer ---------------------------------------------------------
|
|
454
|
+
|
|
455
|
+
def category_index(self) -> CategoryIndex:
|
|
456
|
+
"""Category path/id index over the (cached) category tree."""
|
|
457
|
+
return CategoryIndex(self.get_categories())
|
|
458
|
+
|
|
459
|
+
def chain_index(self) -> ChainIndex:
|
|
460
|
+
"""Chain index over the (cached) chain list."""
|
|
461
|
+
return ChainIndex(self.get_chains())
|
|
462
|
+
|
|
463
|
+
def shop_index(self) -> ShopIndex:
|
|
464
|
+
"""Shop index over the (cached) shop list."""
|
|
465
|
+
return ShopIndex(self.get_shops())
|
|
466
|
+
|
|
467
|
+
def get_category_by_path(self, path: str | Sequence[str]) -> Category:
|
|
468
|
+
"""Resolve a category by slug path: ``"tejtermek_sajt_tojas/sajt/ementali"``."""
|
|
469
|
+
return self.category_index().by_path(path)
|
|
470
|
+
|
|
471
|
+
def get_chain(self, *, uuid: str | None = None, name: str | None = None) -> Chain:
|
|
472
|
+
"""Resolve a chain by uuid or (case-insensitive) name; uuid wins when both."""
|
|
473
|
+
return self.chain_index().get(uuid=uuid, name=name)
|
|
474
|
+
|
|
475
|
+
def get_shop(self, uuid: str) -> Shop:
|
|
476
|
+
"""Resolve a shop by its uuid (e.g. ``spar-110``)."""
|
|
477
|
+
return self.shop_index().get(uuid)
|
|
478
|
+
|
|
479
|
+
def find_shops(
|
|
480
|
+
self,
|
|
481
|
+
*,
|
|
482
|
+
city: str | None = None,
|
|
483
|
+
postal_code: str | None = None,
|
|
484
|
+
chain_uuid: str | None = None,
|
|
485
|
+
) -> list[Shop]:
|
|
486
|
+
"""AND-combined shop filters; ``city`` is a case-insensitive prefix match."""
|
|
487
|
+
return self.shop_index().find(city=city, postal_code=postal_code, chain_uuid=chain_uuid)
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
class AsyncArfigyeloClient:
|
|
491
|
+
"""Asynchronous client for the Árfigyelő API (mirrors ArfigyeloClient)."""
|
|
492
|
+
|
|
493
|
+
def __init__(
|
|
494
|
+
self,
|
|
495
|
+
*,
|
|
496
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
497
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
498
|
+
retries: int = 0,
|
|
499
|
+
ttl: float | None = DEFAULT_TTL,
|
|
500
|
+
cache_prices: bool = False,
|
|
501
|
+
user_agent: str = f"arfigyelo-api/{__version__}",
|
|
502
|
+
headers: Mapping[str, str] | None = None,
|
|
503
|
+
transport: httpx.AsyncBaseTransport | None = None,
|
|
504
|
+
) -> None:
|
|
505
|
+
options = _ClientOptions(
|
|
506
|
+
base_url=base_url,
|
|
507
|
+
timeout=timeout,
|
|
508
|
+
retries=retries,
|
|
509
|
+
ttl=ttl,
|
|
510
|
+
cache_prices=cache_prices,
|
|
511
|
+
user_agent=user_agent,
|
|
512
|
+
headers=headers,
|
|
513
|
+
)
|
|
514
|
+
self._cache_prices = options.cache_prices
|
|
515
|
+
self._index_cache: TTLCache[Any] = TTLCache[Any](options.ttl)
|
|
516
|
+
self._price_cache: TTLCache[Any] = TTLCache[Any](options.ttl)
|
|
517
|
+
if transport is None:
|
|
518
|
+
transport = httpx.AsyncHTTPTransport(retries=options.retries)
|
|
519
|
+
self._http = httpx.AsyncClient(
|
|
520
|
+
base_url=options.base_url,
|
|
521
|
+
timeout=options.timeout,
|
|
522
|
+
transport=transport,
|
|
523
|
+
headers=options.headers,
|
|
524
|
+
)
|
|
525
|
+
|
|
526
|
+
# --- lifecycle -----------------------------------------------------------
|
|
527
|
+
|
|
528
|
+
async def aclose(self) -> None:
|
|
529
|
+
await self._http.aclose()
|
|
530
|
+
|
|
531
|
+
async def __aenter__(self) -> AsyncArfigyeloClient:
|
|
532
|
+
return self
|
|
533
|
+
|
|
534
|
+
async def __aexit__(self, *args: object) -> None:
|
|
535
|
+
await self.aclose()
|
|
536
|
+
|
|
537
|
+
# --- transport plumbing ----------------------------------------------------
|
|
538
|
+
|
|
539
|
+
async def _get(self, path: str, params: Mapping[str, str] | None = None) -> httpx.Response:
|
|
540
|
+
try:
|
|
541
|
+
return await self._http.get(path, params=params)
|
|
542
|
+
except httpx.TransportError as exc:
|
|
543
|
+
raise ArfigyeloConnectionError(str(exc)) from exc
|
|
544
|
+
|
|
545
|
+
async def _model[ModelT: BaseModel](
|
|
546
|
+
self, model: type[ModelT], path: str, params: Mapping[str, str] | None = None
|
|
547
|
+
) -> ModelT:
|
|
548
|
+
response = await self._get(path, params)
|
|
549
|
+
data = _decode(response)
|
|
550
|
+
return _validate(model, data, response)
|
|
551
|
+
|
|
552
|
+
@staticmethod
|
|
553
|
+
def _price_key(path: str, params: Mapping[str, str]) -> tuple[Any, ...]:
|
|
554
|
+
return (path, tuple(sorted(params.items())))
|
|
555
|
+
|
|
556
|
+
# --- structural endpoints (always cached) ----------------------------------
|
|
557
|
+
|
|
558
|
+
async def get_categories(self) -> list[Category]:
|
|
559
|
+
"""GET /categories — the full category tree (cached with ttl)."""
|
|
560
|
+
|
|
561
|
+
async def fetch() -> list[Category]:
|
|
562
|
+
return (await self._model(_CategoryList, "categories")).categories
|
|
563
|
+
|
|
564
|
+
return await _async_cached(fetch, self._index_cache, "categories")
|
|
565
|
+
|
|
566
|
+
async def get_chains(self) -> list[Chain]:
|
|
567
|
+
"""GET /chain-stores — all retail chains (cached with ttl)."""
|
|
568
|
+
|
|
569
|
+
async def fetch() -> list[Chain]:
|
|
570
|
+
return (await self._model(_ChainList, "chain-stores")).chain_stores
|
|
571
|
+
|
|
572
|
+
return await _async_cached(fetch, self._index_cache, "chain-stores")
|
|
573
|
+
|
|
574
|
+
async def get_shops(self) -> list[Shop]:
|
|
575
|
+
"""GET /shops — all physical shops (cached with ttl)."""
|
|
576
|
+
|
|
577
|
+
async def fetch() -> list[Shop]:
|
|
578
|
+
return (await self._model(_ShopList, "shops")).shops
|
|
579
|
+
|
|
580
|
+
return await _async_cached(fetch, self._index_cache, "shops")
|
|
581
|
+
|
|
582
|
+
# --- product endpoints (cached only under cache_prices=True) ---------------
|
|
583
|
+
|
|
584
|
+
async def get_products_by_category(
|
|
585
|
+
self,
|
|
586
|
+
category_id: int,
|
|
587
|
+
*,
|
|
588
|
+
limit: int = 12,
|
|
589
|
+
offset: int = 0,
|
|
590
|
+
order: CategoryOrder | str = CategoryOrder.UNIT_AMOUNT_ASC,
|
|
591
|
+
shop_ids: Sequence[str] | None = None,
|
|
592
|
+
) -> ProductPage:
|
|
593
|
+
"""GET /products-by-category/{id} — one page of a category listing."""
|
|
594
|
+
limit_v = _require_non_negative_int("limit", limit)
|
|
595
|
+
offset_v = _require_non_negative_int("offset", offset)
|
|
596
|
+
order_v = _require_order("order", order, CategoryOrder)
|
|
597
|
+
shop_ids_v = _require_shop_ids("shop_ids", shop_ids)
|
|
598
|
+
path = f"products-by-category/{category_id}"
|
|
599
|
+
params: dict[str, str] = {"limit": str(limit_v), "offset": str(offset_v), "order": order_v}
|
|
600
|
+
if shop_ids_v is not None:
|
|
601
|
+
params["shopIds"] = shop_ids_v
|
|
602
|
+
|
|
603
|
+
async def fetch() -> ProductPage:
|
|
604
|
+
return await self._model(ProductPage, path, params)
|
|
605
|
+
|
|
606
|
+
if self._cache_prices:
|
|
607
|
+
return await _async_cached(fetch, self._price_cache, self._price_key(path, params))
|
|
608
|
+
return await fetch()
|
|
609
|
+
|
|
610
|
+
async def get_products_by_path(
|
|
611
|
+
self,
|
|
612
|
+
path: str | Sequence[str],
|
|
613
|
+
*,
|
|
614
|
+
limit: int = 12,
|
|
615
|
+
offset: int = 0,
|
|
616
|
+
order: CategoryOrder | str = CategoryOrder.UNIT_AMOUNT_ASC,
|
|
617
|
+
shop_ids: Sequence[str] | None = None,
|
|
618
|
+
) -> ProductPage:
|
|
619
|
+
"""Category listing resolved by category path (mapping layer)."""
|
|
620
|
+
category = await self.get_category_by_path(path)
|
|
621
|
+
return await self.get_products_by_category(
|
|
622
|
+
category.id, limit=limit, offset=offset, order=order, shop_ids=shop_ids
|
|
623
|
+
)
|
|
624
|
+
|
|
625
|
+
async def search(
|
|
626
|
+
self,
|
|
627
|
+
q: str,
|
|
628
|
+
*,
|
|
629
|
+
limit: int = 48,
|
|
630
|
+
offset: int = 0,
|
|
631
|
+
order: SearchOrder | str = SearchOrder.RELEVANCE,
|
|
632
|
+
shop_ids: Sequence[str] | None = None,
|
|
633
|
+
) -> ProductPage:
|
|
634
|
+
"""GET /search — text search (accent-insensitive server-side)."""
|
|
635
|
+
query = _require_query(q)
|
|
636
|
+
limit_v = _require_non_negative_int("limit", limit)
|
|
637
|
+
offset_v = _require_non_negative_int("offset", offset)
|
|
638
|
+
order_v = _require_order("order", order, SearchOrder)
|
|
639
|
+
shop_ids_v = _require_shop_ids("shop_ids", shop_ids)
|
|
640
|
+
params: dict[str, str] = {
|
|
641
|
+
"q": query,
|
|
642
|
+
"limit": str(limit_v),
|
|
643
|
+
"offset": str(offset_v),
|
|
644
|
+
"order": order_v,
|
|
645
|
+
}
|
|
646
|
+
if shop_ids_v is not None:
|
|
647
|
+
params["shopIds"] = shop_ids_v
|
|
648
|
+
|
|
649
|
+
async def fetch() -> ProductPage:
|
|
650
|
+
return await self._model(ProductPage, "search", params)
|
|
651
|
+
|
|
652
|
+
if self._cache_prices:
|
|
653
|
+
return await _async_cached(fetch, self._price_cache, self._price_key("search", params))
|
|
654
|
+
return await fetch()
|
|
655
|
+
|
|
656
|
+
async def get_product(self, product_id: str) -> ProductDetail:
|
|
657
|
+
"""GET /product/{id} — product detail with chain-level prices."""
|
|
658
|
+
product_id = _require_non_empty_str("product_id", product_id)
|
|
659
|
+
path = f"product/{product_id}"
|
|
660
|
+
|
|
661
|
+
async def fetch() -> ProductDetail:
|
|
662
|
+
return await self._model(ProductDetail, path)
|
|
663
|
+
|
|
664
|
+
if self._cache_prices:
|
|
665
|
+
return await _async_cached(fetch, self._price_cache, self._price_key(path, {}))
|
|
666
|
+
return await fetch()
|
|
667
|
+
|
|
668
|
+
async def get_product_shop_prices(
|
|
669
|
+
self, product_id: str, shop_uuids: Sequence[str]
|
|
670
|
+
) -> list[ShopPriceEntry]:
|
|
671
|
+
"""GET /product/{id}/shop/{shopUuids} — per-shop prices for one product.
|
|
672
|
+
|
|
673
|
+
Only shops that have a price are returned; loyalty prices never appear
|
|
674
|
+
here (NORMAL and DISCOUNTED only).
|
|
675
|
+
"""
|
|
676
|
+
product_id = _require_non_empty_str("product_id", product_id)
|
|
677
|
+
joined = _require_shop_ids("shop_uuids", shop_uuids)
|
|
678
|
+
assert joined is not None # _require_shop_ids raises on empty/None input
|
|
679
|
+
path = f"product/{product_id}/shop/{joined}"
|
|
680
|
+
|
|
681
|
+
async def fetch() -> list[ShopPriceEntry]:
|
|
682
|
+
return (await self._model(_ShopPriceList, path)).shops
|
|
683
|
+
|
|
684
|
+
if self._cache_prices:
|
|
685
|
+
return await _async_cached(fetch, self._price_cache, self._price_key(path, {}))
|
|
686
|
+
return await fetch()
|
|
687
|
+
|
|
688
|
+
# --- pagination iterators (stop on empty page, never on count) -------------
|
|
689
|
+
|
|
690
|
+
async def iter_products_by_category(
|
|
691
|
+
self,
|
|
692
|
+
category_id: int,
|
|
693
|
+
*,
|
|
694
|
+
limit: int = LIMIT_CAP,
|
|
695
|
+
order: CategoryOrder | str = CategoryOrder.UNIT_AMOUNT_ASC,
|
|
696
|
+
shop_ids: Sequence[str] | None = None,
|
|
697
|
+
) -> AsyncIterator[ProductSummary]:
|
|
698
|
+
"""Yield every product of a category, paging internally (async).
|
|
699
|
+
|
|
700
|
+
Terminates on an empty ``products`` page; ``count`` is unreliable on
|
|
701
|
+
empty pages (API quirk #1).
|
|
702
|
+
"""
|
|
703
|
+
offset = 0
|
|
704
|
+
while True:
|
|
705
|
+
page = await self.get_products_by_category(
|
|
706
|
+
category_id, limit=limit, offset=offset, order=order, shop_ids=shop_ids
|
|
707
|
+
)
|
|
708
|
+
for product in page.products:
|
|
709
|
+
yield product
|
|
710
|
+
if not page.products:
|
|
711
|
+
return
|
|
712
|
+
offset += len(page.products)
|
|
713
|
+
|
|
714
|
+
async def iter_products_by_path(
|
|
715
|
+
self,
|
|
716
|
+
path: str | Sequence[str],
|
|
717
|
+
*,
|
|
718
|
+
limit: int = LIMIT_CAP,
|
|
719
|
+
order: CategoryOrder | str = CategoryOrder.UNIT_AMOUNT_ASC,
|
|
720
|
+
shop_ids: Sequence[str] | None = None,
|
|
721
|
+
) -> AsyncIterator[ProductSummary]:
|
|
722
|
+
"""Category listing iterator resolved by category path (async)."""
|
|
723
|
+
category = await self.get_category_by_path(path)
|
|
724
|
+
async for product in self.iter_products_by_category(
|
|
725
|
+
category.id, limit=limit, order=order, shop_ids=shop_ids
|
|
726
|
+
):
|
|
727
|
+
yield product
|
|
728
|
+
|
|
729
|
+
async def iter_search(
|
|
730
|
+
self,
|
|
731
|
+
q: str,
|
|
732
|
+
*,
|
|
733
|
+
limit: int = LIMIT_CAP,
|
|
734
|
+
order: SearchOrder | str = SearchOrder.RELEVANCE,
|
|
735
|
+
shop_ids: Sequence[str] | None = None,
|
|
736
|
+
) -> AsyncIterator[ProductSummary]:
|
|
737
|
+
"""Yield every search result, paging internally (async)."""
|
|
738
|
+
offset = 0
|
|
739
|
+
while True:
|
|
740
|
+
page = await self.search(q, limit=limit, offset=offset, order=order, shop_ids=shop_ids)
|
|
741
|
+
for product in page.products:
|
|
742
|
+
yield product
|
|
743
|
+
if not page.products:
|
|
744
|
+
return
|
|
745
|
+
offset += len(page.products)
|
|
746
|
+
|
|
747
|
+
# --- mapping layer ---------------------------------------------------------
|
|
748
|
+
|
|
749
|
+
async def category_index(self) -> CategoryIndex:
|
|
750
|
+
"""Category path/id index over the (cached) category tree."""
|
|
751
|
+
return CategoryIndex(await self.get_categories())
|
|
752
|
+
|
|
753
|
+
async def chain_index(self) -> ChainIndex:
|
|
754
|
+
"""Chain index over the (cached) chain list."""
|
|
755
|
+
return ChainIndex(await self.get_chains())
|
|
756
|
+
|
|
757
|
+
async def shop_index(self) -> ShopIndex:
|
|
758
|
+
"""Shop index over the (cached) shop list."""
|
|
759
|
+
return ShopIndex(await self.get_shops())
|
|
760
|
+
|
|
761
|
+
async def get_category_by_path(self, path: str | Sequence[str]) -> Category:
|
|
762
|
+
"""Resolve a category by slug path: ``"tejtermek_sajt_tojas/sajt/ementali"``."""
|
|
763
|
+
index = await self.category_index()
|
|
764
|
+
return index.by_path(path)
|
|
765
|
+
|
|
766
|
+
async def get_chain(self, *, uuid: str | None = None, name: str | None = None) -> Chain:
|
|
767
|
+
"""Resolve a chain by uuid or (case-insensitive) name; uuid wins when both."""
|
|
768
|
+
index = await self.chain_index()
|
|
769
|
+
return index.get(uuid=uuid, name=name)
|
|
770
|
+
|
|
771
|
+
async def get_shop(self, uuid: str) -> Shop:
|
|
772
|
+
"""Resolve a shop by its uuid (e.g. ``spar-110``)."""
|
|
773
|
+
index = await self.shop_index()
|
|
774
|
+
return index.get(uuid)
|
|
775
|
+
|
|
776
|
+
async def find_shops(
|
|
777
|
+
self,
|
|
778
|
+
*,
|
|
779
|
+
city: str | None = None,
|
|
780
|
+
postal_code: str | None = None,
|
|
781
|
+
chain_uuid: str | None = None,
|
|
782
|
+
) -> list[Shop]:
|
|
783
|
+
"""AND-combined shop filters; ``city`` is a case-insensitive prefix match."""
|
|
784
|
+
index = await self.shop_index()
|
|
785
|
+
return index.find(city=city, postal_code=postal_code, chain_uuid=chain_uuid)
|