recapi 0.4.10__tar.gz → 0.4.12__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.10 → recapi-0.4.12}/PKG-INFO +41 -14
- recapi-0.4.10/recapi.egg-info/PKG-INFO → recapi-0.4.12/README.md +27 -23
- {recapi-0.4.10 → recapi-0.4.12}/pyproject.toml +13 -1
- {recapi-0.4.10 → recapi-0.4.12}/recapi/client.py +19 -4
- recapi-0.4.12/recapi/py.typed +0 -0
- recapi-0.4.10/README.md → recapi-0.4.12/recapi.egg-info/PKG-INFO +50 -13
- {recapi-0.4.10 → recapi-0.4.12}/recapi.egg-info/SOURCES.txt +1 -0
- {recapi-0.4.10 → recapi-0.4.12}/tests/test_async_client.py +3 -1
- {recapi-0.4.10 → recapi-0.4.12}/tests/test_client.py +16 -0
- {recapi-0.4.10 → recapi-0.4.12}/tests/test_client_vectors.py +13 -1
- {recapi-0.4.10 → recapi-0.4.12}/LICENSE +0 -0
- {recapi-0.4.10 → recapi-0.4.12}/recapi/__init__.py +0 -0
- {recapi-0.4.10 → recapi-0.4.12}/recapi/async_client.py +0 -0
- {recapi-0.4.10 → recapi-0.4.12}/recapi/history.py +0 -0
- {recapi-0.4.10 → recapi-0.4.12}/recapi.egg-info/dependency_links.txt +0 -0
- {recapi-0.4.10 → recapi-0.4.12}/recapi.egg-info/top_level.txt +0 -0
- {recapi-0.4.10 → recapi-0.4.12}/setup.cfg +0 -0
- {recapi-0.4.10 → recapi-0.4.12}/tests/test_history.py +0 -0
- {recapi-0.4.10 → recapi-0.4.12}/tests/test_stores.py +0 -0
|
@@ -1,8 +1,21 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: recapi
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.12
|
|
4
4
|
Summary: Python client for the recapi recommendation API: per-user history, event batching, retries, popular fallback.
|
|
5
5
|
License: MIT
|
|
6
|
+
Project-URL: Homepage, https://recapi.io
|
|
7
|
+
Project-URL: Documentation, https://recapi.io/docs
|
|
8
|
+
Project-URL: Issues, https://recapi.io/contact
|
|
9
|
+
Keywords: recommendations,recommender,personalization,ecommerce,api-client
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
18
|
+
Classifier: Typing :: Typed
|
|
6
19
|
Requires-Python: >=3.11
|
|
7
20
|
Description-Content-Type: text/markdown
|
|
8
21
|
License-File: LICENSE
|
|
@@ -31,16 +44,15 @@ The library is on PyPI, with no dependencies: install it with pip, or add
|
|
|
31
44
|
pip install recapi
|
|
32
45
|
```
|
|
33
46
|
|
|
34
|
-
Production releases publish each version there
|
|
35
|
-
([docs/deployment.md](../../docs/deployment.md#publishing-the-libraries)).
|
|
47
|
+
Production releases publish each version there.
|
|
36
48
|
Your recapi API serves the same library, for servers that can't reach PyPI
|
|
37
49
|
(the dashboard's quick start shows the line with your API's address):
|
|
38
50
|
|
|
39
51
|
```sh
|
|
40
|
-
pip install https://api.<your-domain>/sdk/python/recapi-0.4.
|
|
52
|
+
pip install https://api.<your-domain>/sdk/python/recapi-0.4.12-py3-none-any.whl
|
|
41
53
|
```
|
|
42
54
|
|
|
43
|
-
To work on the library itself, install it from a checkout of
|
|
55
|
+
To work on the library itself, install it from a checkout of recapi's repository
|
|
44
56
|
(`pip install ./sdk/python`).
|
|
45
57
|
|
|
46
58
|
## Quick start
|
|
@@ -65,8 +77,9 @@ client.track("item-42", "view", user_id="user-881")
|
|
|
65
77
|
# reached, this returns popular items instead (result.fallback is True), and an
|
|
66
78
|
# empty list if those fail too or the key is refused (hide the slot): no
|
|
67
79
|
# try/except.
|
|
68
|
-
# item.why says why it is listed, safe to show anyone
|
|
69
|
-
# codes
|
|
80
|
+
# item.why says why it is listed, safe to show anyone
|
|
81
|
+
# (https://recapi.io/docs/api#reason-codes): pick your own words, no label for
|
|
82
|
+
# codes you don't map.
|
|
70
83
|
LABELS = {
|
|
71
84
|
"for_you": "Picked for you",
|
|
72
85
|
"similar": "Similar items",
|
|
@@ -87,7 +100,7 @@ for item in result.items:
|
|
|
87
100
|
client.track("item-77", "view", user_id="user-881")
|
|
88
101
|
```
|
|
89
102
|
|
|
90
|
-
Levels follow the [recommended scale](
|
|
103
|
+
Levels follow the [recommended scale](https://recapi.io/docs/api#interaction-levels):
|
|
91
104
|
`"view"` (3), `"cart"` (5), `"purchase"` (10), or any integer from -10 to 10
|
|
92
105
|
(`track("article-9", 5, …)` for an article read to the end); 0 is an
|
|
93
106
|
impression. `"reject"` (-10) is an explicit "not interested": the item is never
|
|
@@ -225,10 +238,10 @@ one recommendation id collects the events of many users ("Page caches").
|
|
|
225
238
|
| Method | What it does |
|
|
226
239
|
|---|---|
|
|
227
240
|
| `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 |
|
|
228
|
-
| `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](
|
|
241
|
+
| `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](https://recapi.io/docs/api#item-metadata)), None when it has none; `why` its [reason code](https://recapi.io/docs/api#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 |
|
|
229
242
|
| `recommend_lists(lists, *, user_id=None, anon_id=None, exclude=None, allow_repeats=False)` | One `Recommendations` per list, in order, from one call billed as one recommendation. Each list is a dict of `recommend`'s list keywords (`placement`, `count`, `tags_any`, `tags_all`, `exclude`, `context_item_id`, `discovery`); `exclude` applies to every list. A list holds none of the items of the lists before it unless `allow_repeats`. Fails and falls back as `recommend` does, popular items asked list by list |
|
|
230
243
|
| `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` |
|
|
231
|
-
| `upsert_items(items, *, merge=False)` | Creates or replaces items (dicts with the [item fields](
|
|
244
|
+
| `upsert_items(items, *, merge=False)` | Creates or replaces items (dicts with the [item fields](https://recapi.io/docs/api#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. Metadata merges key by key: the keys sent are set, the others kept, a key set to `None` is removed (`"metadata": {"old_price": None}`) and `"metadata": None` removes them all. 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` |
|
|
232
245
|
| `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 |
|
|
233
246
|
| `delete_user(user_id)` | Erases the user's events in recapi (GDPR) and their state in the store |
|
|
234
247
|
| `flush()` / `close()` | Send queued events now; `close()` also stops the background sender |
|
|
@@ -253,6 +266,21 @@ alone. Each logs one warning, which never quotes the id. An empty or `None`
|
|
|
253
266
|
Background failures go to the `recapi` logger: refused events are dropped, a
|
|
254
267
|
batch that can succeed later is retried with backoff (up to 10,000 queued).
|
|
255
268
|
|
|
269
|
+
## Errors and troubleshooting
|
|
270
|
+
|
|
271
|
+
`recommend` never raises for an outage: it returns popular items, or an empty
|
|
272
|
+
list on a 401 or 403, and logs one warning to the `recapi` logger. A bad
|
|
273
|
+
request or a reply that isn't the API's raises `recapi.RecapiError` (`code`,
|
|
274
|
+
`status`, `retryable`); `upsert_items` raises `recapi.RejectedItemsError` for
|
|
275
|
+
the items the API refused. An API error also carries `docs_url`, the address
|
|
276
|
+
of its section on the errors page; its message ends with it.
|
|
277
|
+
|
|
278
|
+
- [Errors](https://recapi.io/docs/errors): each error code, its cause and fix.
|
|
279
|
+
- [Troubleshooting](https://recapi.io/docs/troubleshooting): no lists yet,
|
|
280
|
+
empty lists, only popular items, key errors.
|
|
281
|
+
|
|
282
|
+
## Development
|
|
283
|
+
|
|
256
284
|
The API builds the wheel from `recapi/*.py` and `pyproject.toml`, and pip
|
|
257
285
|
caches its URL for a year: a change there needs a new `version` in
|
|
258
286
|
`pyproject.toml` and `__version__` in `recapi/client.py`, and a new entry in
|
|
@@ -260,7 +288,6 @@ caches its URL for a year: a change there needs a new `version` in
|
|
|
260
288
|
An older version's URL then installs the new one, so the library's public
|
|
261
289
|
methods and their arguments only grow.
|
|
262
290
|
|
|
263
|
-
Tests: `cd sdk/python && python3 -m
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
HTTP server.
|
|
291
|
+
Tests, from a checkout of recapi's repository: `cd sdk/python && python3 -m
|
|
292
|
+
unittest discover -s tests`. They run recapi's shared test vectors (history
|
|
293
|
+
and client behaviour) against a local HTTP server.
|
|
@@ -1,13 +1,3 @@
|
|
|
1
|
-
Metadata-Version: 2.4
|
|
2
|
-
Name: recapi
|
|
3
|
-
Version: 0.4.10
|
|
4
|
-
Summary: Python client for the recapi recommendation API: per-user history, event batching, retries, popular fallback.
|
|
5
|
-
License: MIT
|
|
6
|
-
Requires-Python: >=3.11
|
|
7
|
-
Description-Content-Type: text/markdown
|
|
8
|
-
License-File: LICENSE
|
|
9
|
-
Dynamic: license-file
|
|
10
|
-
|
|
11
1
|
# recapi for Python
|
|
12
2
|
|
|
13
3
|
Python client for the recapi recommendation API, for servers: Django,
|
|
@@ -31,16 +21,15 @@ The library is on PyPI, with no dependencies: install it with pip, or add
|
|
|
31
21
|
pip install recapi
|
|
32
22
|
```
|
|
33
23
|
|
|
34
|
-
Production releases publish each version there
|
|
35
|
-
([docs/deployment.md](../../docs/deployment.md#publishing-the-libraries)).
|
|
24
|
+
Production releases publish each version there.
|
|
36
25
|
Your recapi API serves the same library, for servers that can't reach PyPI
|
|
37
26
|
(the dashboard's quick start shows the line with your API's address):
|
|
38
27
|
|
|
39
28
|
```sh
|
|
40
|
-
pip install https://api.<your-domain>/sdk/python/recapi-0.4.
|
|
29
|
+
pip install https://api.<your-domain>/sdk/python/recapi-0.4.12-py3-none-any.whl
|
|
41
30
|
```
|
|
42
31
|
|
|
43
|
-
To work on the library itself, install it from a checkout of
|
|
32
|
+
To work on the library itself, install it from a checkout of recapi's repository
|
|
44
33
|
(`pip install ./sdk/python`).
|
|
45
34
|
|
|
46
35
|
## Quick start
|
|
@@ -65,8 +54,9 @@ client.track("item-42", "view", user_id="user-881")
|
|
|
65
54
|
# reached, this returns popular items instead (result.fallback is True), and an
|
|
66
55
|
# empty list if those fail too or the key is refused (hide the slot): no
|
|
67
56
|
# try/except.
|
|
68
|
-
# item.why says why it is listed, safe to show anyone
|
|
69
|
-
# codes
|
|
57
|
+
# item.why says why it is listed, safe to show anyone
|
|
58
|
+
# (https://recapi.io/docs/api#reason-codes): pick your own words, no label for
|
|
59
|
+
# codes you don't map.
|
|
70
60
|
LABELS = {
|
|
71
61
|
"for_you": "Picked for you",
|
|
72
62
|
"similar": "Similar items",
|
|
@@ -87,7 +77,7 @@ for item in result.items:
|
|
|
87
77
|
client.track("item-77", "view", user_id="user-881")
|
|
88
78
|
```
|
|
89
79
|
|
|
90
|
-
Levels follow the [recommended scale](
|
|
80
|
+
Levels follow the [recommended scale](https://recapi.io/docs/api#interaction-levels):
|
|
91
81
|
`"view"` (3), `"cart"` (5), `"purchase"` (10), or any integer from -10 to 10
|
|
92
82
|
(`track("article-9", 5, …)` for an article read to the end); 0 is an
|
|
93
83
|
impression. `"reject"` (-10) is an explicit "not interested": the item is never
|
|
@@ -225,10 +215,10 @@ one recommendation id collects the events of many users ("Page caches").
|
|
|
225
215
|
| Method | What it does |
|
|
226
216
|
|---|---|
|
|
227
217
|
| `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 |
|
|
228
|
-
| `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](
|
|
218
|
+
| `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](https://recapi.io/docs/api#item-metadata)), None when it has none; `why` its [reason code](https://recapi.io/docs/api#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 |
|
|
229
219
|
| `recommend_lists(lists, *, user_id=None, anon_id=None, exclude=None, allow_repeats=False)` | One `Recommendations` per list, in order, from one call billed as one recommendation. Each list is a dict of `recommend`'s list keywords (`placement`, `count`, `tags_any`, `tags_all`, `exclude`, `context_item_id`, `discovery`); `exclude` applies to every list. A list holds none of the items of the lists before it unless `allow_repeats`. Fails and falls back as `recommend` does, popular items asked list by list |
|
|
230
220
|
| `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` |
|
|
231
|
-
| `upsert_items(items, *, merge=False)` | Creates or replaces items (dicts with the [item fields](
|
|
221
|
+
| `upsert_items(items, *, merge=False)` | Creates or replaces items (dicts with the [item fields](https://recapi.io/docs/api#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. Metadata merges key by key: the keys sent are set, the others kept, a key set to `None` is removed (`"metadata": {"old_price": None}`) and `"metadata": None` removes them all. 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` |
|
|
232
222
|
| `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 |
|
|
233
223
|
| `delete_user(user_id)` | Erases the user's events in recapi (GDPR) and their state in the store |
|
|
234
224
|
| `flush()` / `close()` | Send queued events now; `close()` also stops the background sender |
|
|
@@ -253,6 +243,21 @@ alone. Each logs one warning, which never quotes the id. An empty or `None`
|
|
|
253
243
|
Background failures go to the `recapi` logger: refused events are dropped, a
|
|
254
244
|
batch that can succeed later is retried with backoff (up to 10,000 queued).
|
|
255
245
|
|
|
246
|
+
## Errors and troubleshooting
|
|
247
|
+
|
|
248
|
+
`recommend` never raises for an outage: it returns popular items, or an empty
|
|
249
|
+
list on a 401 or 403, and logs one warning to the `recapi` logger. A bad
|
|
250
|
+
request or a reply that isn't the API's raises `recapi.RecapiError` (`code`,
|
|
251
|
+
`status`, `retryable`); `upsert_items` raises `recapi.RejectedItemsError` for
|
|
252
|
+
the items the API refused. An API error also carries `docs_url`, the address
|
|
253
|
+
of its section on the errors page; its message ends with it.
|
|
254
|
+
|
|
255
|
+
- [Errors](https://recapi.io/docs/errors): each error code, its cause and fix.
|
|
256
|
+
- [Troubleshooting](https://recapi.io/docs/troubleshooting): no lists yet,
|
|
257
|
+
empty lists, only popular items, key errors.
|
|
258
|
+
|
|
259
|
+
## Development
|
|
260
|
+
|
|
256
261
|
The API builds the wheel from `recapi/*.py` and `pyproject.toml`, and pip
|
|
257
262
|
caches its URL for a year: a change there needs a new `version` in
|
|
258
263
|
`pyproject.toml` and `__version__` in `recapi/client.py`, and a new entry in
|
|
@@ -260,7 +265,6 @@ caches its URL for a year: a change there needs a new `version` in
|
|
|
260
265
|
An older version's URL then installs the new one, so the library's public
|
|
261
266
|
methods and their arguments only grow.
|
|
262
267
|
|
|
263
|
-
Tests: `cd sdk/python && python3 -m
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
HTTP server.
|
|
268
|
+
Tests, from a checkout of recapi's repository: `cd sdk/python && python3 -m
|
|
269
|
+
unittest discover -s tests`. They run recapi's shared test vectors (history
|
|
270
|
+
and client behaviour) against a local HTTP server.
|
|
@@ -4,16 +4,28 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "recapi"
|
|
7
|
-
version = "0.4.
|
|
7
|
+
version = "0.4.12"
|
|
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"
|
|
11
11
|
dependencies = []
|
|
12
12
|
license = { text = "MIT" }
|
|
13
|
+
keywords = ["recommendations", "recommender", "personalization", "ecommerce", "api-client"]
|
|
14
|
+
# One line each: the API builds its wheel with a line-by-line read of this table.
|
|
15
|
+
classifiers = ["Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", "Topic :: Internet :: WWW/HTTP", "Typing :: Typed"]
|
|
16
|
+
|
|
17
|
+
[project.urls]
|
|
18
|
+
Homepage = "https://recapi.io"
|
|
19
|
+
Documentation = "https://recapi.io/docs"
|
|
20
|
+
Issues = "https://recapi.io/contact"
|
|
13
21
|
|
|
14
22
|
[tool.setuptools]
|
|
15
23
|
packages = ["recapi"]
|
|
16
24
|
|
|
25
|
+
# py.typed tells mypy and pyright that the package carries its own types.
|
|
26
|
+
[tool.setuptools.package-data]
|
|
27
|
+
recapi = ["py.typed"]
|
|
28
|
+
|
|
17
29
|
[tool.ruff]
|
|
18
30
|
line-length = 100
|
|
19
31
|
target-version = "py311"
|
|
@@ -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.12"
|
|
33
33
|
|
|
34
34
|
log = logging.getLogger("recapi")
|
|
35
35
|
Tags = Sequence[str] | None
|
|
@@ -114,16 +114,27 @@ class RecapiError(Exception):
|
|
|
114
114
|
|
|
115
115
|
``code`` is the API's error code (``invalid_request``, ``rate_limited``,
|
|
116
116
|
``quota_exceeded``...) or a client one: ``network``, ``timeout``,
|
|
117
|
-
``invalid_response``.
|
|
117
|
+
``invalid_response``. ``docs_url`` is the errors page's section for an
|
|
118
|
+
API error, from its body (None when the API sent none, and for a client
|
|
119
|
+
code); the error's text then ends with ``, see <docs_url>``.
|
|
118
120
|
"""
|
|
119
121
|
|
|
120
122
|
def __init__(
|
|
121
|
-
self,
|
|
123
|
+
self,
|
|
124
|
+
code: str,
|
|
125
|
+
message: str,
|
|
126
|
+
*,
|
|
127
|
+
status: int = 0,
|
|
128
|
+
retry_after: float | None = None,
|
|
129
|
+
docs_url: str | None = None,
|
|
122
130
|
) -> None:
|
|
123
|
-
|
|
131
|
+
# The address ends the text, so the log line or traceback that
|
|
132
|
+
# prints the error names its fix.
|
|
133
|
+
super().__init__(f"{message}, see {docs_url}" if docs_url else message)
|
|
124
134
|
self.code = code
|
|
125
135
|
self.status = status
|
|
126
136
|
self.retry_after = retry_after
|
|
137
|
+
self.docs_url = docs_url or None
|
|
127
138
|
|
|
128
139
|
@property
|
|
129
140
|
def retryable(self) -> bool:
|
|
@@ -1211,11 +1222,15 @@ def _http_error(status: int, headers: Any, text: bytes) -> RecapiError:
|
|
|
1211
1222
|
or _CODE_BY_STATUS.get(status)
|
|
1212
1223
|
or ("internal" if status >= 500 else "http_error")
|
|
1213
1224
|
)
|
|
1225
|
+
# Only a string: an older server sends none, and a proxy's odd body must
|
|
1226
|
+
# not put an object in the text.
|
|
1227
|
+
docs_url = body.get("docs_url")
|
|
1214
1228
|
return RecapiError(
|
|
1215
1229
|
str(code),
|
|
1216
1230
|
str(body.get("message") or f"HTTP {status}"),
|
|
1217
1231
|
status=status,
|
|
1218
1232
|
retry_after=_retry_after(headers.get("Retry-After")),
|
|
1233
|
+
docs_url=docs_url if isinstance(docs_url, str) else None,
|
|
1219
1234
|
)
|
|
1220
1235
|
|
|
1221
1236
|
|
|
File without changes
|
|
@@ -1,3 +1,26 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: recapi
|
|
3
|
+
Version: 0.4.12
|
|
4
|
+
Summary: Python client for the recapi recommendation API: per-user history, event batching, retries, popular fallback.
|
|
5
|
+
License: MIT
|
|
6
|
+
Project-URL: Homepage, https://recapi.io
|
|
7
|
+
Project-URL: Documentation, https://recapi.io/docs
|
|
8
|
+
Project-URL: Issues, https://recapi.io/contact
|
|
9
|
+
Keywords: recommendations,recommender,personalization,ecommerce,api-client
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
18
|
+
Classifier: Typing :: Typed
|
|
19
|
+
Requires-Python: >=3.11
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
1
24
|
# recapi for Python
|
|
2
25
|
|
|
3
26
|
Python client for the recapi recommendation API, for servers: Django,
|
|
@@ -21,16 +44,15 @@ The library is on PyPI, with no dependencies: install it with pip, or add
|
|
|
21
44
|
pip install recapi
|
|
22
45
|
```
|
|
23
46
|
|
|
24
|
-
Production releases publish each version there
|
|
25
|
-
([docs/deployment.md](../../docs/deployment.md#publishing-the-libraries)).
|
|
47
|
+
Production releases publish each version there.
|
|
26
48
|
Your recapi API serves the same library, for servers that can't reach PyPI
|
|
27
49
|
(the dashboard's quick start shows the line with your API's address):
|
|
28
50
|
|
|
29
51
|
```sh
|
|
30
|
-
pip install https://api.<your-domain>/sdk/python/recapi-0.4.
|
|
52
|
+
pip install https://api.<your-domain>/sdk/python/recapi-0.4.12-py3-none-any.whl
|
|
31
53
|
```
|
|
32
54
|
|
|
33
|
-
To work on the library itself, install it from a checkout of
|
|
55
|
+
To work on the library itself, install it from a checkout of recapi's repository
|
|
34
56
|
(`pip install ./sdk/python`).
|
|
35
57
|
|
|
36
58
|
## Quick start
|
|
@@ -55,8 +77,9 @@ client.track("item-42", "view", user_id="user-881")
|
|
|
55
77
|
# reached, this returns popular items instead (result.fallback is True), and an
|
|
56
78
|
# empty list if those fail too or the key is refused (hide the slot): no
|
|
57
79
|
# try/except.
|
|
58
|
-
# item.why says why it is listed, safe to show anyone
|
|
59
|
-
# codes
|
|
80
|
+
# item.why says why it is listed, safe to show anyone
|
|
81
|
+
# (https://recapi.io/docs/api#reason-codes): pick your own words, no label for
|
|
82
|
+
# codes you don't map.
|
|
60
83
|
LABELS = {
|
|
61
84
|
"for_you": "Picked for you",
|
|
62
85
|
"similar": "Similar items",
|
|
@@ -77,7 +100,7 @@ for item in result.items:
|
|
|
77
100
|
client.track("item-77", "view", user_id="user-881")
|
|
78
101
|
```
|
|
79
102
|
|
|
80
|
-
Levels follow the [recommended scale](
|
|
103
|
+
Levels follow the [recommended scale](https://recapi.io/docs/api#interaction-levels):
|
|
81
104
|
`"view"` (3), `"cart"` (5), `"purchase"` (10), or any integer from -10 to 10
|
|
82
105
|
(`track("article-9", 5, …)` for an article read to the end); 0 is an
|
|
83
106
|
impression. `"reject"` (-10) is an explicit "not interested": the item is never
|
|
@@ -215,10 +238,10 @@ one recommendation id collects the events of many users ("Page caches").
|
|
|
215
238
|
| Method | What it does |
|
|
216
239
|
|---|---|
|
|
217
240
|
| `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 |
|
|
218
|
-
| `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](
|
|
241
|
+
| `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](https://recapi.io/docs/api#item-metadata)), None when it has none; `why` its [reason code](https://recapi.io/docs/api#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 |
|
|
219
242
|
| `recommend_lists(lists, *, user_id=None, anon_id=None, exclude=None, allow_repeats=False)` | One `Recommendations` per list, in order, from one call billed as one recommendation. Each list is a dict of `recommend`'s list keywords (`placement`, `count`, `tags_any`, `tags_all`, `exclude`, `context_item_id`, `discovery`); `exclude` applies to every list. A list holds none of the items of the lists before it unless `allow_repeats`. Fails and falls back as `recommend` does, popular items asked list by list |
|
|
220
243
|
| `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` |
|
|
221
|
-
| `upsert_items(items, *, merge=False)` | Creates or replaces items (dicts with the [item fields](
|
|
244
|
+
| `upsert_items(items, *, merge=False)` | Creates or replaces items (dicts with the [item fields](https://recapi.io/docs/api#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. Metadata merges key by key: the keys sent are set, the others kept, a key set to `None` is removed (`"metadata": {"old_price": None}`) and `"metadata": None` removes them all. 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` |
|
|
222
245
|
| `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 |
|
|
223
246
|
| `delete_user(user_id)` | Erases the user's events in recapi (GDPR) and their state in the store |
|
|
224
247
|
| `flush()` / `close()` | Send queued events now; `close()` also stops the background sender |
|
|
@@ -243,6 +266,21 @@ alone. Each logs one warning, which never quotes the id. An empty or `None`
|
|
|
243
266
|
Background failures go to the `recapi` logger: refused events are dropped, a
|
|
244
267
|
batch that can succeed later is retried with backoff (up to 10,000 queued).
|
|
245
268
|
|
|
269
|
+
## Errors and troubleshooting
|
|
270
|
+
|
|
271
|
+
`recommend` never raises for an outage: it returns popular items, or an empty
|
|
272
|
+
list on a 401 or 403, and logs one warning to the `recapi` logger. A bad
|
|
273
|
+
request or a reply that isn't the API's raises `recapi.RecapiError` (`code`,
|
|
274
|
+
`status`, `retryable`); `upsert_items` raises `recapi.RejectedItemsError` for
|
|
275
|
+
the items the API refused. An API error also carries `docs_url`, the address
|
|
276
|
+
of its section on the errors page; its message ends with it.
|
|
277
|
+
|
|
278
|
+
- [Errors](https://recapi.io/docs/errors): each error code, its cause and fix.
|
|
279
|
+
- [Troubleshooting](https://recapi.io/docs/troubleshooting): no lists yet,
|
|
280
|
+
empty lists, only popular items, key errors.
|
|
281
|
+
|
|
282
|
+
## Development
|
|
283
|
+
|
|
246
284
|
The API builds the wheel from `recapi/*.py` and `pyproject.toml`, and pip
|
|
247
285
|
caches its URL for a year: a change there needs a new `version` in
|
|
248
286
|
`pyproject.toml` and `__version__` in `recapi/client.py`, and a new entry in
|
|
@@ -250,7 +288,6 @@ caches its URL for a year: a change there needs a new `version` in
|
|
|
250
288
|
An older version's URL then installs the new one, so the library's public
|
|
251
289
|
methods and their arguments only grow.
|
|
252
290
|
|
|
253
|
-
Tests: `cd sdk/python && python3 -m
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
HTTP server.
|
|
291
|
+
Tests, from a checkout of recapi's repository: `cd sdk/python && python3 -m
|
|
292
|
+
unittest discover -s tests`. They run recapi's shared test vectors (history
|
|
293
|
+
and client behaviour) against a local HTTP server.
|
|
@@ -165,7 +165,9 @@ class AsyncClient(APITest):
|
|
|
165
165
|
self.api.on("/v1/recommendations", Reply(200, recs(["r1"]), delay=0.3))
|
|
166
166
|
client = self.async_client()
|
|
167
167
|
worst, results = self.worst_loop_delay(lambda u: client.recommend(user_id=u), 20)
|
|
168
|
-
|
|
168
|
+
# A blocking call stalls the loop for the whole 0.3 s reply; 0.1 s tells the two apart
|
|
169
|
+
# while leaving room for a busy host's scheduler, which measured up to 24 ms (AP-0729).
|
|
170
|
+
self.assertLess(worst, 0.1)
|
|
169
171
|
self.assertEqual([r.recommendation_id for r in results], ["rec_1"] * 20)
|
|
170
172
|
|
|
171
173
|
sync = self.client()
|
|
@@ -392,6 +392,22 @@ class Recommend(APITest):
|
|
|
392
392
|
self.assertIn("recs down", logs.output[0])
|
|
393
393
|
self.assertIn("pop down", logs.output[0])
|
|
394
394
|
|
|
395
|
+
def test_the_log_line_for_a_refused_key_ends_with_the_address_of_its_fix(self) -> None:
|
|
396
|
+
docs_url = "https://app.recapi.io/docs/errors#401-unauthorized"
|
|
397
|
+
error = {"code": "unauthorized", "message": "missing or invalid API key"}
|
|
398
|
+
self.api.handler = lambda call: Reply(401, {"error": {**error, "docs_url": docs_url}})
|
|
399
|
+
client = self.client()
|
|
400
|
+
client.track("a", 1, user_id="u")
|
|
401
|
+
with self.assertLogs("recapi", "WARNING") as logs:
|
|
402
|
+
client.flush()
|
|
403
|
+
client.recommend(user_id="u", count=3)
|
|
404
|
+
self.assertTrue(logs.output)
|
|
405
|
+
for line in logs.output:
|
|
406
|
+
self.assertTrue(line.endswith(f"missing or invalid API key, see {docs_url}"), line)
|
|
407
|
+
with self.assertRaises(recapi.RecapiError) as caught:
|
|
408
|
+
client._popular(1, None, None, None)
|
|
409
|
+
self.assertEqual(caught.exception.docs_url, docs_url)
|
|
410
|
+
|
|
395
411
|
def test_an_unusable_context_item_id_is_reported_without_the_id(self) -> None:
|
|
396
412
|
# A page takes the id from a visitor's URL: the visitor must not reach
|
|
397
413
|
# the log, the rejected item still leaves the list, and the history
|
|
@@ -25,6 +25,8 @@ def error_reply(case: dict) -> Reply:
|
|
|
25
25
|
body = None
|
|
26
26
|
if case.get("body_code"):
|
|
27
27
|
body = {"error": {"code": case["body_code"], "message": "from the vector"}}
|
|
28
|
+
if "docs_url" in case:
|
|
29
|
+
body["error"]["docs_url"] = case["docs_url"]
|
|
28
30
|
headers = {"Retry-After": case["retry_after"]} if "retry_after" in case else {}
|
|
29
31
|
if "retry_after_ms" in case and case["retry_after_ms"] is not None and not headers:
|
|
30
32
|
headers = {"Retry-After": str(case["retry_after_ms"] / 1000)}
|
|
@@ -84,6 +86,12 @@ class ClientVectors(APITest):
|
|
|
84
86
|
if "retry_after_ms" in case:
|
|
85
87
|
want = case["retry_after_ms"]
|
|
86
88
|
self.assertEqual(error.retry_after, None if want is None else want / 1000)
|
|
89
|
+
self.assertEqual(error.docs_url, case.get("docs_url"))
|
|
90
|
+
# An older server sends no docs_url: no address, and the message as sent.
|
|
91
|
+
if "docs_url" in case:
|
|
92
|
+
self.assertTrue(str(error).endswith(", see " + case["docs_url"]), str(error))
|
|
93
|
+
elif case.get("body_code"):
|
|
94
|
+
self.assertEqual(str(error), "from the vector")
|
|
87
95
|
|
|
88
96
|
def test_vector_list_calls_keep_the_page_up(self) -> None:
|
|
89
97
|
for case in VECTORS["errors"]:
|
|
@@ -454,7 +462,10 @@ class ClientVectors(APITest):
|
|
|
454
462
|
self.api.calls.clear()
|
|
455
463
|
replies = iter(case["replies"])
|
|
456
464
|
self.api.on("/v1/items:batch", lambda call, r=replies: Reply(200, next(r)))
|
|
457
|
-
|
|
465
|
+
template = case.get(
|
|
466
|
+
"item", vectors["item"]
|
|
467
|
+
) # a case's own item replaces the section's
|
|
468
|
+
items = [{"item_id": f"i{k}", **template} for k in range(case["count"])]
|
|
458
469
|
rejected = None
|
|
459
470
|
try:
|
|
460
471
|
got = self.client().upsert_items(items, merge=case["merge"])
|
|
@@ -465,6 +476,7 @@ class ClientVectors(APITest):
|
|
|
465
476
|
self.assertEqual([len(b["items"]) for b in bodies], case["sizes"])
|
|
466
477
|
for body in bodies: # true when asked, else absent
|
|
467
478
|
self.assertEqual(body.get("merge", "absent"), case["merge"] or "absent")
|
|
479
|
+
# Every item as given: a metadata key set to None goes out as null.
|
|
468
480
|
self.assertEqual([it for b in bodies for it in b["items"]], items)
|
|
469
481
|
self.assertEqual(got, case["upserted"])
|
|
470
482
|
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
|