recapi 0.4.12__tar.gz → 0.4.13__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: recapi
3
- Version: 0.4.12
3
+ Version: 0.4.13
4
4
  Summary: Python client for the recapi recommendation API: per-user history, event batching, retries, popular fallback.
5
5
  License: MIT
6
6
  Project-URL: Homepage, https://recapi.io
@@ -49,7 +49,7 @@ Your recapi API serves the same library, for servers that can't reach PyPI
49
49
  (the dashboard's quick start shows the line with your API's address):
50
50
 
51
51
  ```sh
52
- pip install https://api.<your-domain>/sdk/python/recapi-0.4.12-py3-none-any.whl
52
+ pip install https://api.<your-domain>/sdk/python/recapi-0.4.13-py3-none-any.whl
53
53
  ```
54
54
 
55
55
  To work on the library itself, install it from a checkout of recapi's repository
@@ -237,7 +237,7 @@ one recommendation id collects the events of many users ("Page caches").
237
237
 
238
238
  | Method | What it does |
239
239
  |---|---|
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 |
240
+ | `track(item_id, level, *, user_id=None, anon_id=None, recommendation_id=None, value=None, currency=None)` | Updates the user's history at once and queues the event. `recommendation_id` overrides the automatic attribution. A purchase may carry `value` (what the buyer paid for the line) and `currency` (ISO 4217, such as `"EUR"`), kept for the sales figure of a lift test. Raises `ValueError` for an invalid level or user, visitor or recommendation id, and for a negative or non-finite value or a currency without a value or not of three letters. 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 |
241
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 |
242
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 |
243
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` |
@@ -26,7 +26,7 @@ Your recapi API serves the same library, for servers that can't reach PyPI
26
26
  (the dashboard's quick start shows the line with your API's address):
27
27
 
28
28
  ```sh
29
- pip install https://api.<your-domain>/sdk/python/recapi-0.4.12-py3-none-any.whl
29
+ pip install https://api.<your-domain>/sdk/python/recapi-0.4.13-py3-none-any.whl
30
30
  ```
31
31
 
32
32
  To work on the library itself, install it from a checkout of recapi's repository
@@ -214,7 +214,7 @@ one recommendation id collects the events of many users ("Page caches").
214
214
 
215
215
  | Method | What it does |
216
216
  |---|---|
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 |
217
+ | `track(item_id, level, *, user_id=None, anon_id=None, recommendation_id=None, value=None, currency=None)` | Updates the user's history at once and queues the event. `recommendation_id` overrides the automatic attribution. A purchase may carry `value` (what the buyer paid for the line) and `currency` (ISO 4217, such as `"EUR"`), kept for the sales figure of a lift test. Raises `ValueError` for an invalid level or user, visitor or recommendation id, and for a negative or non-finite value or a currency without a value or not of three letters. 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
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 |
219
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 |
220
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` |
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "recapi"
7
- version = "0.4.12"
7
+ version = "0.4.13"
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"
@@ -70,9 +70,9 @@ class AsyncClient:
70
70
  # serve the fallback. Past its deadline, the call asks only for popular items.
71
71
  return await asyncio.to_thread(fn, deadline, *args, **params)
72
72
 
73
- async def track(self, item_id: str, level: int | str, **ids: str | None) -> None:
74
- """Record an interaction: :meth:`Client.track`."""
75
- await self._run(self._client.track, item_id, level, **ids)
73
+ async def track(self, item_id: str, level: int | str, **fields: Any) -> None:
74
+ """Record an interaction (ids, value, currency): :meth:`Client.track`."""
75
+ await self._run(self._client.track, item_id, level, **fields)
76
76
 
77
77
  async def identify(self, anon_id: str, user_id: str) -> None:
78
78
  """At login, the visitor's history becomes the user's: :meth:`Client.identify`."""
@@ -14,6 +14,7 @@ import hashlib
14
14
  import http.client
15
15
  import json
16
16
  import logging
17
+ import math
17
18
  import os
18
19
  import random
19
20
  import threading
@@ -29,7 +30,7 @@ from typing import Any, Protocol
29
30
 
30
31
  from .history import History, is_id
31
32
 
32
- __version__ = "0.4.12"
33
+ __version__ = "0.4.13"
33
34
 
34
35
  log = logging.getLogger("recapi")
35
36
  Tags = Sequence[str] | None
@@ -478,19 +479,24 @@ class Client:
478
479
  user_id: str | None = None,
479
480
  anon_id: str | None = None,
480
481
  recommendation_id: str | None = None,
482
+ value: float | None = None,
483
+ currency: str | None = None,
481
484
  ) -> None:
482
485
  """Record an interaction: the user's history changes at once, the event is queued.
483
486
 
484
487
  ``level`` is an integer -10 to 10 or ``view`` (3), ``cart`` (5),
485
488
  ``purchase`` (10), ``reject`` (-10: never recommend the item to this
486
489
  user again until a positive event on it). ``recommendation_id``
487
- overrides the automatic attribution. Raises ``ValueError`` on a bad level
490
+ overrides the automatic attribution. ``value`` is what the buyer paid for
491
+ a purchase's line (0 for a free one), ``currency`` its ISO 4217 code; a
492
+ currency needs a value. Raises ``ValueError`` on a bad level, amount
488
493
  or a bad user, visitor or recommendation id. An ``item_id`` the API would
489
494
  refuse isn't one: a page often takes it from a visitor's URL, so the
490
495
  event is dropped and logged instead.
491
496
  """
492
497
  level = _level(level)
493
498
  _check_ids(user_id=user_id, anon_id=anon_id, recommendation_id=recommendation_id)
499
+ _check_amount(value, currency)
494
500
  # A crafted link must not fail the page. Nothing is kept: in the history
495
501
  # it would make the API refuse every later list. The line never quotes
496
502
  # the visitor's id.
@@ -521,6 +527,8 @@ class Client:
521
527
  "user_id": user_id,
522
528
  "anon_id": anon_id,
523
529
  "recommendation_id": attributed,
530
+ "value": value,
531
+ "currency": currency,
524
532
  "timestamp": _iso(t),
525
533
  "event_id": str(uuid.uuid4()),
526
534
  }
@@ -1328,6 +1336,25 @@ def _check_ids(**ids: str | None) -> None:
1328
1336
  raise ValueError(f"{name} must be 1-256 bytes of UTF-8 without control characters")
1329
1337
 
1330
1338
 
1339
+ def _check_amount(value: object, currency: object) -> None:
1340
+ """Refuse what the API would refuse in the event (spec/client_vectors.json "amounts")."""
1341
+ if value is not None and (
1342
+ isinstance(value, bool) or not isinstance(value, int | float) or not (0 <= value < math.inf)
1343
+ ):
1344
+ raise ValueError("value must be a number of at least 0")
1345
+ if currency is None:
1346
+ return
1347
+ if value is None:
1348
+ raise ValueError("currency needs a value")
1349
+ if not (
1350
+ isinstance(currency, str)
1351
+ and len(currency) == 3
1352
+ and currency.isascii()
1353
+ and currency.isalpha()
1354
+ ):
1355
+ raise ValueError("currency must be three letters (ISO 4217)")
1356
+
1357
+
1331
1358
  def _usable_context(value: object) -> bool:
1332
1359
  # An id, or nothing: an empty string reads as no context item.
1333
1360
  return value is None or is_id(value) or (isinstance(value, str) and not value)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: recapi
3
- Version: 0.4.12
3
+ Version: 0.4.13
4
4
  Summary: Python client for the recapi recommendation API: per-user history, event batching, retries, popular fallback.
5
5
  License: MIT
6
6
  Project-URL: Homepage, https://recapi.io
@@ -49,7 +49,7 @@ Your recapi API serves the same library, for servers that can't reach PyPI
49
49
  (the dashboard's quick start shows the line with your API's address):
50
50
 
51
51
  ```sh
52
- pip install https://api.<your-domain>/sdk/python/recapi-0.4.12-py3-none-any.whl
52
+ pip install https://api.<your-domain>/sdk/python/recapi-0.4.13-py3-none-any.whl
53
53
  ```
54
54
 
55
55
  To work on the library itself, install it from a checkout of recapi's repository
@@ -237,7 +237,7 @@ one recommendation id collects the events of many users ("Page caches").
237
237
 
238
238
  | Method | What it does |
239
239
  |---|---|
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 |
240
+ | `track(item_id, level, *, user_id=None, anon_id=None, recommendation_id=None, value=None, currency=None)` | Updates the user's history at once and queues the event. `recommendation_id` overrides the automatic attribution. A purchase may carry `value` (what the buyer paid for the line) and `currency` (ISO 4217, such as `"EUR"`), kept for the sales figure of a lift test. Raises `ValueError` for an invalid level or user, visitor or recommendation id, and for a negative or non-finite value or a currency without a value or not of three letters. 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 |
241
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 |
242
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 |
243
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` |
@@ -115,6 +115,19 @@ class AsyncClient(APITest):
115
115
  self.assertIn("invalid_request", logs.output[0])
116
116
  self.assertNotIn("evil", logs.output[0])
117
117
 
118
+ def test_async_track_sends_an_amount(self) -> None:
119
+ client = self.async_client()
120
+
121
+ async def run() -> None:
122
+ await client.track("p1", "purchase", user_id="u", value=49.9, currency="EUR")
123
+ with self.assertRaises(ValueError):
124
+ await client.track("p1", "purchase", user_id="u", currency="EUR")
125
+ await client.flush()
126
+
127
+ asyncio.run(run())
128
+ sent = [e for batch in self.api.events() for e in batch]
129
+ self.assertEqual([(e["value"], e["currency"]) for e in sent], [(49.9, "EUR")])
130
+
118
131
  def test_async_track_drops_an_unusable_item_id(self) -> None:
119
132
  client = self.async_client()
120
133
 
@@ -480,3 +480,37 @@ class ClientVectors(APITest):
480
480
  self.assertEqual([it for b in bodies for it in b["items"]], items)
481
481
  self.assertEqual(got, case["upserted"])
482
482
  self.assertEqual(rejected, case["rejected"] or None)
483
+
484
+ def test_vector_amounts(self) -> None:
485
+ vectors = VECTORS["amounts"]
486
+ event = vectors["event"]
487
+ client = self.client()
488
+ bad = [*vectors["invalid"], {"value": float("nan")}, {"value": float("inf")}]
489
+ bad += [
490
+ {"value": float("-inf"), "currency": "EUR"},
491
+ {"value": True},
492
+ {"value": 1, "currency": ""},
493
+ {"value": 1, "currency": "ÉUR"}, # a letter, but not ASCII
494
+ {"value": 1, "currency": 978}, # the numeric code
495
+ ]
496
+ for case in bad:
497
+ with self.subTest(case=case), self.assertRaises(ValueError):
498
+ client.track(event["item_id"], event["level"], user_id=event["user_id"], **case)
499
+ for case in vectors["valid"]:
500
+ client.track(event["item_id"], event["level"], user_id=event["user_id"], **case)
501
+ client.flush()
502
+ sent = [e for batch in self.api.events() for e in batch] # nothing of the invalid ones
503
+ self.assertEqual(len(sent), len(vectors["valid"]))
504
+ for want, got in zip(vectors["valid"], sent, strict=True):
505
+ for key in ("value", "currency"): # as given, absent when unset
506
+ self.assertEqual(got.get(key, "absent"), want.get(key, "absent"), want)
507
+ self.assertIs(type(got.get("value")), type(want.get("value")))
508
+
509
+ def test_every_vector_section_runs(self) -> None:
510
+ run = {"description", "max_events_per_request", "max_exclude", "recommend_timeout_ms",
511
+ "levels", "ids", "errors", "retry", "batches", "exclude", "context_ids", "fallback",
512
+ "restore", "identify", "stored_state", "metadata", "why", "lists", "upsert_items",
513
+ "amounts"} # fmt: skip
514
+ self.assertEqual(
515
+ set(VECTORS) - run, set(), "sections of spec/client_vectors.json not tested"
516
+ )
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes