recapi 0.4.8__tar.gz → 0.4.9__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.
- {recapi-0.4.8/recapi.egg-info → recapi-0.4.9}/PKG-INFO +3 -3
- {recapi-0.4.8 → recapi-0.4.9}/README.md +2 -2
- {recapi-0.4.8 → recapi-0.4.9}/pyproject.toml +1 -1
- {recapi-0.4.8 → recapi-0.4.9}/recapi/__init__.py +11 -1
- {recapi-0.4.8 → recapi-0.4.9}/recapi/async_client.py +2 -2
- {recapi-0.4.8 → recapi-0.4.9}/recapi/client.py +39 -13
- {recapi-0.4.8 → recapi-0.4.9/recapi.egg-info}/PKG-INFO +3 -3
- {recapi-0.4.8 → recapi-0.4.9}/tests/test_client_vectors.py +22 -0
- {recapi-0.4.8 → recapi-0.4.9}/LICENSE +0 -0
- {recapi-0.4.8 → recapi-0.4.9}/recapi/history.py +0 -0
- {recapi-0.4.8 → recapi-0.4.9}/recapi.egg-info/SOURCES.txt +0 -0
- {recapi-0.4.8 → recapi-0.4.9}/recapi.egg-info/dependency_links.txt +0 -0
- {recapi-0.4.8 → recapi-0.4.9}/recapi.egg-info/top_level.txt +0 -0
- {recapi-0.4.8 → recapi-0.4.9}/setup.cfg +0 -0
- {recapi-0.4.8 → recapi-0.4.9}/tests/test_async_client.py +0 -0
- {recapi-0.4.8 → recapi-0.4.9}/tests/test_client.py +0 -0
- {recapi-0.4.8 → recapi-0.4.9}/tests/test_history.py +0 -0
- {recapi-0.4.8 → recapi-0.4.9}/tests/test_stores.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: recapi
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.9
|
|
4
4
|
Summary: Python client for the recapi recommendation API: per-user history, event batching, retries, popular fallback.
|
|
5
5
|
License: MIT
|
|
6
6
|
Requires-Python: >=3.11
|
|
@@ -37,7 +37,7 @@ Your recapi API serves the same library, for servers that can't reach PyPI
|
|
|
37
37
|
(the dashboard's quick start shows the line with your API's address):
|
|
38
38
|
|
|
39
39
|
```sh
|
|
40
|
-
pip install https://api.<your-domain>/sdk/python/recapi-0.4.
|
|
40
|
+
pip install https://api.<your-domain>/sdk/python/recapi-0.4.9-py3-none-any.whl
|
|
41
41
|
```
|
|
42
42
|
|
|
43
43
|
To work on the library itself, install it from a checkout of this repository
|
|
@@ -210,7 +210,7 @@ one recommendation id collects the events of many users ("Page caches").
|
|
|
210
210
|
| `track(item_id, level, *, user_id=None, anon_id=None, recommendation_id=None)` | Updates the user's history at once and queues the event. `recommendation_id` overrides the automatic attribution. Raises `ValueError` for an invalid level or user, visitor or recommendation id. An `item_id` the API would refuse (1-256 bytes of UTF-8, no control character; `None` or no string at all too) drops the event with a log line: no exception, and the other events are sent as usual |
|
|
211
211
|
| `recommend(*, user_id=None, anon_id=None, count=0, placement=None, tags_any=None, tags_all=None, exclude=None, context_item_id=None, discovery=None)` | Returns `Recommendations(recommendation_id, fallback, items)`, each item `Item(item_id, score, slot, metadata, why)`. `metadata` is the dict stored with the item ([Item metadata](../../docs/api.md#item-metadata)), None when it has none; `why` its [reason code](../../docs/api.md#reason-codes). The user's rejected items are added to `exclude`. At most 1.5 s; on a network error, timeout, 5xx or 429 it returns popular items (`fallback` True, no id), or no item when those fail too; on a 401 or 403 no item at once. A `context_item_id` the API would refuse (no string at all too) isn't sent: you get the same popular list and a log line, with no recommendation request. Any other failure (a bad request, a reply that isn't the API's) raises |
|
|
212
212
|
| `popular(*, count=10, tags_any=None, tags_all=None)` | Popular items (`Item`, metadata and `why` included), for pages without a user. On a network error, timeout, 5xx, 429, 401 or 403: an empty list and a log line. Other failures as in `recommend` |
|
|
213
|
-
| `upsert_items(items)` | Creates or replaces items (dicts with the [item fields](../../docs/api.md#put-v1itemsitem_id--secret-key)), 1,000 per request, with retries. Returns how many were stored |
|
|
213
|
+
| `upsert_items(items, *, merge=False)` | Creates or replaces items (dicts with the [item fields](../../docs/api.md#put-v1itemsitem_id--secret-key)), 1,000 per request, with retries. Returns how many were stored. With `merge=True` only the fields an item has are sent and changed, the others keep their stored values (a tags-only sync keeps titles and metadata); to clear a field, replace the item or set it to `None`, which resets it to its default. A bad item doesn't keep the others out: once all are sent, `recapi.RejectedItemsError` (a `RecapiError`, code `invalid_request`) lists them in `rejected` as `(index, error)` pairs, with the count stored in `upserted` |
|
|
214
214
|
| `identify(anon_id, user_id)` | At login: merges the visitor's history and shown items into the user's, then deletes the visitor's entry. The user's first restore from recapi then leaves that visitor's browsing out, so it doesn't count twice |
|
|
215
215
|
| `delete_user(user_id)` | Erases the user's events in recapi (GDPR) and their state in the store |
|
|
216
216
|
| `flush()` / `close()` | Send queued events now; `close()` also stops the background sender |
|
|
@@ -27,7 +27,7 @@ Your recapi API serves the same library, for servers that can't reach PyPI
|
|
|
27
27
|
(the dashboard's quick start shows the line with your API's address):
|
|
28
28
|
|
|
29
29
|
```sh
|
|
30
|
-
pip install https://api.<your-domain>/sdk/python/recapi-0.4.
|
|
30
|
+
pip install https://api.<your-domain>/sdk/python/recapi-0.4.9-py3-none-any.whl
|
|
31
31
|
```
|
|
32
32
|
|
|
33
33
|
To work on the library itself, install it from a checkout of this repository
|
|
@@ -200,7 +200,7 @@ one recommendation id collects the events of many users ("Page caches").
|
|
|
200
200
|
| `track(item_id, level, *, user_id=None, anon_id=None, recommendation_id=None)` | Updates the user's history at once and queues the event. `recommendation_id` overrides the automatic attribution. Raises `ValueError` for an invalid level or user, visitor or recommendation id. An `item_id` the API would refuse (1-256 bytes of UTF-8, no control character; `None` or no string at all too) drops the event with a log line: no exception, and the other events are sent as usual |
|
|
201
201
|
| `recommend(*, user_id=None, anon_id=None, count=0, placement=None, tags_any=None, tags_all=None, exclude=None, context_item_id=None, discovery=None)` | Returns `Recommendations(recommendation_id, fallback, items)`, each item `Item(item_id, score, slot, metadata, why)`. `metadata` is the dict stored with the item ([Item metadata](../../docs/api.md#item-metadata)), None when it has none; `why` its [reason code](../../docs/api.md#reason-codes). The user's rejected items are added to `exclude`. At most 1.5 s; on a network error, timeout, 5xx or 429 it returns popular items (`fallback` True, no id), or no item when those fail too; on a 401 or 403 no item at once. A `context_item_id` the API would refuse (no string at all too) isn't sent: you get the same popular list and a log line, with no recommendation request. Any other failure (a bad request, a reply that isn't the API's) raises |
|
|
202
202
|
| `popular(*, count=10, tags_any=None, tags_all=None)` | Popular items (`Item`, metadata and `why` included), for pages without a user. On a network error, timeout, 5xx, 429, 401 or 403: an empty list and a log line. Other failures as in `recommend` |
|
|
203
|
-
| `upsert_items(items)` | Creates or replaces items (dicts with the [item fields](../../docs/api.md#put-v1itemsitem_id--secret-key)), 1,000 per request, with retries. Returns how many were stored |
|
|
203
|
+
| `upsert_items(items, *, merge=False)` | Creates or replaces items (dicts with the [item fields](../../docs/api.md#put-v1itemsitem_id--secret-key)), 1,000 per request, with retries. Returns how many were stored. With `merge=True` only the fields an item has are sent and changed, the others keep their stored values (a tags-only sync keeps titles and metadata); to clear a field, replace the item or set it to `None`, which resets it to its default. A bad item doesn't keep the others out: once all are sent, `recapi.RejectedItemsError` (a `RecapiError`, code `invalid_request`) lists them in `rejected` as `(index, error)` pairs, with the count stored in `upserted` |
|
|
204
204
|
| `identify(anon_id, user_id)` | At login: merges the visitor's history and shown items into the user's, then deletes the visitor's entry. The user's first restore from recapi then leaves that visitor's browsing out, so it doesn't count twice |
|
|
205
205
|
| `delete_user(user_id)` | Erases the user's events in recapi (GDPR) and their state in the store |
|
|
206
206
|
| `flush()` / `close()` | Send queued events now; `close()` also stops the background sender |
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "recapi"
|
|
7
|
-
version = "0.4.
|
|
7
|
+
version = "0.4.9"
|
|
8
8
|
description = "Python client for the recapi recommendation API: per-user history, event batching, retries, popular fallback."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.11"
|
|
@@ -14,7 +14,16 @@ coroutines. See ``sdk/python/README.md``.
|
|
|
14
14
|
|
|
15
15
|
from typing import Any
|
|
16
16
|
|
|
17
|
-
from .client import
|
|
17
|
+
from .client import (
|
|
18
|
+
Client,
|
|
19
|
+
Item,
|
|
20
|
+
MemoryStore,
|
|
21
|
+
RecapiError,
|
|
22
|
+
Recommendations,
|
|
23
|
+
RejectedItemsError,
|
|
24
|
+
Store,
|
|
25
|
+
__version__,
|
|
26
|
+
)
|
|
18
27
|
|
|
19
28
|
__all__ = [
|
|
20
29
|
"AsyncClient",
|
|
@@ -23,6 +32,7 @@ __all__ = [
|
|
|
23
32
|
"MemoryStore",
|
|
24
33
|
"RecapiError",
|
|
25
34
|
"Recommendations",
|
|
35
|
+
"RejectedItemsError",
|
|
26
36
|
"Store",
|
|
27
37
|
"__version__",
|
|
28
38
|
]
|
|
@@ -75,9 +75,9 @@ class AsyncClient:
|
|
|
75
75
|
"""Popular items: :meth:`Client.popular`."""
|
|
76
76
|
return await self._run(self._client.popular, **params)
|
|
77
77
|
|
|
78
|
-
async def upsert_items(self, items: Any) -> int:
|
|
78
|
+
async def upsert_items(self, items: Any, *, merge: bool = False) -> int:
|
|
79
79
|
"""Create or replace items: :meth:`Client.upsert_items`."""
|
|
80
|
-
return await self._run(self._client.upsert_items, items)
|
|
80
|
+
return await self._run(self._client.upsert_items, items, merge=merge)
|
|
81
81
|
|
|
82
82
|
async def delete_user(self, user_id: str) -> None:
|
|
83
83
|
"""Erase a user (GDPR): :meth:`Client.delete_user`."""
|
|
@@ -29,7 +29,7 @@ from typing import Any, Protocol
|
|
|
29
29
|
|
|
30
30
|
from .history import History, is_id
|
|
31
31
|
|
|
32
|
-
__version__ = "0.4.
|
|
32
|
+
__version__ = "0.4.9"
|
|
33
33
|
|
|
34
34
|
log = logging.getLogger("recapi")
|
|
35
35
|
Tags = Sequence[str] | None
|
|
@@ -153,6 +153,21 @@ class RecapiError(Exception):
|
|
|
153
153
|
return self.status in (401, 403)
|
|
154
154
|
|
|
155
155
|
|
|
156
|
+
class RejectedItemsError(RecapiError):
|
|
157
|
+
"""upsert_items' error when the API refused some items: the others were stored.
|
|
158
|
+
|
|
159
|
+
``upserted`` is how many were stored, ``rejected`` the refused ones as
|
|
160
|
+
(index in the list given to upsert_items, error) pairs.
|
|
161
|
+
"""
|
|
162
|
+
|
|
163
|
+
def __init__(self, upserted: int, rejected: list[tuple[int, str]]) -> None:
|
|
164
|
+
index, error = rejected[0]
|
|
165
|
+
message = f"{len(rejected)} items refused, the first items[{index}]: {error}"
|
|
166
|
+
super().__init__("invalid_request", message, status=200)
|
|
167
|
+
self.upserted = upserted
|
|
168
|
+
self.rejected = rejected
|
|
169
|
+
|
|
170
|
+
|
|
156
171
|
@dataclass(frozen=True)
|
|
157
172
|
class Item:
|
|
158
173
|
"""One recommended or popular item."""
|
|
@@ -872,28 +887,39 @@ class Client:
|
|
|
872
887
|
|
|
873
888
|
# --- catalog and users --------------------------------------------------
|
|
874
889
|
|
|
875
|
-
def upsert_items(self, items: Iterable[Mapping[str, Any]]) -> int:
|
|
890
|
+
def upsert_items(self, items: Iterable[Mapping[str, Any]], *, merge: bool = False) -> int:
|
|
876
891
|
"""Create or replace items (dicts of the API's item fields), 1,000 per request.
|
|
877
892
|
|
|
878
|
-
|
|
879
|
-
|
|
893
|
+
With ``merge``, each item changes only the fields it has and keeps the
|
|
894
|
+
others' stored values (a field set to None goes back to its default).
|
|
895
|
+
Retried like events. Returns how many were stored. An invalid item
|
|
896
|
+
doesn't keep the others out: once every request is sent,
|
|
897
|
+
:class:`RejectedItemsError` lists the refused ones.
|
|
880
898
|
"""
|
|
881
899
|
batch: list[dict[str, Any]] = []
|
|
882
|
-
upserted = 0
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
900
|
+
upserted, sent = 0, 0
|
|
901
|
+
rejected: list[tuple[int, str]] = []
|
|
902
|
+
|
|
903
|
+
def send() -> None:
|
|
904
|
+
nonlocal upserted, sent
|
|
905
|
+
# "merge" only when asked: an older API refuses the field.
|
|
906
|
+
body = {"items": batch, "merge": True} if merge else {"items": batch}
|
|
907
|
+
response = _with_retry(lambda: self._request("POST", "/v1/items:batch", body=body))
|
|
908
|
+
if isinstance(response, dict):
|
|
909
|
+
upserted += int(response.get("upserted", 0))
|
|
910
|
+
for entry in response.get("rejected") or []:
|
|
911
|
+
rejected.append((sent + int(entry["index"]), str(entry.get("error", ""))))
|
|
912
|
+
sent += len(batch)
|
|
889
913
|
|
|
890
914
|
for item in items:
|
|
891
915
|
batch.append(dict(item))
|
|
892
916
|
if len(batch) == MAX_ITEMS_PER_REQUEST:
|
|
893
|
-
|
|
917
|
+
send()
|
|
894
918
|
batch = []
|
|
895
919
|
if batch:
|
|
896
|
-
|
|
920
|
+
send()
|
|
921
|
+
if rejected:
|
|
922
|
+
raise RejectedItemsError(upserted, rejected)
|
|
897
923
|
return upserted
|
|
898
924
|
|
|
899
925
|
def delete_user(self, user_id: str) -> None:
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: recapi
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.9
|
|
4
4
|
Summary: Python client for the recapi recommendation API: per-user history, event batching, retries, popular fallback.
|
|
5
5
|
License: MIT
|
|
6
6
|
Requires-Python: >=3.11
|
|
@@ -37,7 +37,7 @@ Your recapi API serves the same library, for servers that can't reach PyPI
|
|
|
37
37
|
(the dashboard's quick start shows the line with your API's address):
|
|
38
38
|
|
|
39
39
|
```sh
|
|
40
|
-
pip install https://api.<your-domain>/sdk/python/recapi-0.4.
|
|
40
|
+
pip install https://api.<your-domain>/sdk/python/recapi-0.4.9-py3-none-any.whl
|
|
41
41
|
```
|
|
42
42
|
|
|
43
43
|
To work on the library itself, install it from a checkout of this repository
|
|
@@ -210,7 +210,7 @@ one recommendation id collects the events of many users ("Page caches").
|
|
|
210
210
|
| `track(item_id, level, *, user_id=None, anon_id=None, recommendation_id=None)` | Updates the user's history at once and queues the event. `recommendation_id` overrides the automatic attribution. Raises `ValueError` for an invalid level or user, visitor or recommendation id. An `item_id` the API would refuse (1-256 bytes of UTF-8, no control character; `None` or no string at all too) drops the event with a log line: no exception, and the other events are sent as usual |
|
|
211
211
|
| `recommend(*, user_id=None, anon_id=None, count=0, placement=None, tags_any=None, tags_all=None, exclude=None, context_item_id=None, discovery=None)` | Returns `Recommendations(recommendation_id, fallback, items)`, each item `Item(item_id, score, slot, metadata, why)`. `metadata` is the dict stored with the item ([Item metadata](../../docs/api.md#item-metadata)), None when it has none; `why` its [reason code](../../docs/api.md#reason-codes). The user's rejected items are added to `exclude`. At most 1.5 s; on a network error, timeout, 5xx or 429 it returns popular items (`fallback` True, no id), or no item when those fail too; on a 401 or 403 no item at once. A `context_item_id` the API would refuse (no string at all too) isn't sent: you get the same popular list and a log line, with no recommendation request. Any other failure (a bad request, a reply that isn't the API's) raises |
|
|
212
212
|
| `popular(*, count=10, tags_any=None, tags_all=None)` | Popular items (`Item`, metadata and `why` included), for pages without a user. On a network error, timeout, 5xx, 429, 401 or 403: an empty list and a log line. Other failures as in `recommend` |
|
|
213
|
-
| `upsert_items(items)` | Creates or replaces items (dicts with the [item fields](../../docs/api.md#put-v1itemsitem_id--secret-key)), 1,000 per request, with retries. Returns how many were stored |
|
|
213
|
+
| `upsert_items(items, *, merge=False)` | Creates or replaces items (dicts with the [item fields](../../docs/api.md#put-v1itemsitem_id--secret-key)), 1,000 per request, with retries. Returns how many were stored. With `merge=True` only the fields an item has are sent and changed, the others keep their stored values (a tags-only sync keeps titles and metadata); to clear a field, replace the item or set it to `None`, which resets it to its default. A bad item doesn't keep the others out: once all are sent, `recapi.RejectedItemsError` (a `RecapiError`, code `invalid_request`) lists them in `rejected` as `(index, error)` pairs, with the count stored in `upserted` |
|
|
214
214
|
| `identify(anon_id, user_id)` | At login: merges the visitor's history and shown items into the user's, then deletes the visitor's entry. The user's first restore from recapi then leaves that visitor's browsing out, so it doesn't count twice |
|
|
215
215
|
| `delete_user(user_id)` | Erases the user's events in recapi (GDPR) and their state in the store |
|
|
216
216
|
| `flush()` / `close()` | Send queued events now; `close()` also stops the background sender |
|
|
@@ -405,3 +405,25 @@ class ClientVectors(APITest):
|
|
|
405
405
|
]
|
|
406
406
|
attributed = [[e["item_id"], e.get("recommendation_id")] for e in events]
|
|
407
407
|
self.assertEqual(attributed, case["attributed"])
|
|
408
|
+
|
|
409
|
+
def test_vector_upsert_items(self) -> None:
|
|
410
|
+
vectors = VECTORS["upsert_items"]
|
|
411
|
+
for case in vectors["cases"]:
|
|
412
|
+
with self.subTest(case=case["name"]):
|
|
413
|
+
self.api.calls.clear()
|
|
414
|
+
replies = iter(case["replies"])
|
|
415
|
+
self.api.on("/v1/items:batch", lambda call, r=replies: Reply(200, next(r)))
|
|
416
|
+
items = [{"item_id": f"i{k}", **vectors["item"]} for k in range(case["count"])]
|
|
417
|
+
rejected = None
|
|
418
|
+
try:
|
|
419
|
+
got = self.client().upsert_items(items, merge=case["merge"])
|
|
420
|
+
except recapi.RejectedItemsError as error:
|
|
421
|
+
self.assertEqual(error.code, "invalid_request")
|
|
422
|
+
got, rejected = error.upserted, [list(r) for r in error.rejected]
|
|
423
|
+
bodies = [c.body for c in self.api.calls if c.path == "/v1/items:batch"]
|
|
424
|
+
self.assertEqual([len(b["items"]) for b in bodies], case["sizes"])
|
|
425
|
+
for body in bodies: # true when asked, else absent
|
|
426
|
+
self.assertEqual(body.get("merge", "absent"), case["merge"] or "absent")
|
|
427
|
+
self.assertEqual([it for b in bodies for it in b["items"]], items)
|
|
428
|
+
self.assertEqual(got, case["upserted"])
|
|
429
|
+
self.assertEqual(rejected, case["rejected"] or None)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|