aicser-embed 0.3.1__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.
@@ -0,0 +1,107 @@
1
+ """Mint signed, single-use Aicser embed links from your server.
2
+
3
+ from aicser_embed import sign_embed_url
4
+
5
+ embed = sign_embed_url(
6
+ base_url="https://api.aicser.com",
7
+ api_key=os.environ["AICSER_API_KEY"],
8
+ dashboard_id="b4b3…",
9
+ locked_filters=[{"field": "tenant_id", "value": customer.id}],
10
+ )
11
+ # render embed.url in an <iframe>; it opens once, so mint one per page view
12
+
13
+ Every query made with the link is pinned to ``locked_filters`` by Aicser, whatever the browser
14
+ sends. Keep the API key on your server. Standard library only.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import urllib.error
21
+ import urllib.request
22
+ from dataclasses import dataclass
23
+ from typing import Any, Dict, List, Mapping, Optional, Sequence
24
+
25
+ __all__ = ["AicserSignError", "SignedEmbed", "sign_embed_url"]
26
+ __version__ = "0.3.1"
27
+
28
+
29
+ class AicserSignError(Exception):
30
+ """Aicser refused to sign the link (bad key, plan without embedding, unknown dashboard…)."""
31
+
32
+ def __init__(self, message: str, status: int) -> None:
33
+ super().__init__(message)
34
+ self.status = status
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class SignedEmbed:
39
+ url: str
40
+ token: str
41
+ expires_at: str
42
+
43
+
44
+ def _message(body: Mapping[str, Any], status: int) -> str:
45
+ detail = body.get("detail")
46
+ if isinstance(detail, str):
47
+ return detail
48
+ if isinstance(detail, Mapping) and isinstance(detail.get("message"), str):
49
+ return detail["message"]
50
+ return f"Aicser refused to sign the embed ({status})"
51
+
52
+
53
+ def sign_embed_url(
54
+ *,
55
+ base_url: str,
56
+ api_key: str,
57
+ dashboard_id: Optional[str] = None,
58
+ resource_id: Optional[str] = None,
59
+ scope: str = "dashboard",
60
+ locked_filters: Optional[Sequence[Mapping[str, Any]]] = None,
61
+ expires_in_minutes: int = 60,
62
+ allowed_domains: Optional[Sequence[str]] = None,
63
+ download: str = "none",
64
+ timeout: float = 15.0,
65
+ ) -> SignedEmbed:
66
+ """Return a signed embed link for a dashboard, chart, or report.
67
+
68
+ Pass ``dashboard_id`` (legacy) or ``resource_id``. For charts and reports set
69
+ ``scope`` to ``"chart"`` or ``"report"`` (report ids are ``conversationId:messageId``).
70
+
71
+ ``expires_in_minutes`` (5–1440) is how long the session may last once opened.
72
+ ``allowed_domains`` limits which sites may show it; ``download`` is what visitors may save:
73
+ ``"none"``, ``"image"`` or ``"data"``.
74
+ """
75
+ resolved = resource_id or dashboard_id
76
+ if not resolved:
77
+ raise AicserSignError("resource_id (or dashboard_id) is required", 400)
78
+ if scope not in ("dashboard", "chart", "report"):
79
+ raise AicserSignError(f"Unsupported embed scope: {scope}", 400)
80
+
81
+ payload: Dict[str, Any] = {
82
+ "resource_id": resolved,
83
+ "scope": scope,
84
+ "locked_filters": list(locked_filters or []),
85
+ "expires_in_minutes": expires_in_minutes,
86
+ "allowed_domains": list(allowed_domains or []),
87
+ "download": download,
88
+ }
89
+ request = urllib.request.Request(
90
+ f"{base_url.rstrip('/')}/api/embed/sign",
91
+ data=json.dumps(payload).encode(),
92
+ headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"},
93
+ method="POST",
94
+ )
95
+ try:
96
+ with urllib.request.urlopen(request, timeout=timeout) as response: # noqa: S310 (caller's URL)
97
+ status = response.status
98
+ body = json.loads(response.read() or b"{}")
99
+ except urllib.error.HTTPError as exc:
100
+ try:
101
+ body = json.loads(exc.read() or b"{}")
102
+ except ValueError:
103
+ body = {}
104
+ raise AicserSignError(_message(body, exc.code), exc.code) from exc
105
+ if not body.get("url") or not body.get("token"):
106
+ raise AicserSignError(_message(body, status), status)
107
+ return SignedEmbed(url=body["url"], token=body["token"], expires_at=body.get("expires_at") or "")
@@ -0,0 +1,39 @@
1
+ Metadata-Version: 2.4
2
+ Name: aicser-embed
3
+ Version: 0.3.1
4
+ Summary: Mint signed, single-use Aicser embed links from your server
5
+ License: AGPL-3.0
6
+ Project-URL: Source, https://github.com/Aicser-Platform/aicser/tree/main/packages/embed-python
7
+ Requires-Python: >=3.8
8
+ Description-Content-Type: text/markdown
9
+
10
+ # aicser-embed
11
+
12
+ Mint signed, single-use Aicser embed links from your Python server, for embedding a dashboard, chart, or executive report for one of your customers.
13
+
14
+ ```bash
15
+ pip install aicser-embed
16
+ ```
17
+
18
+ ```python
19
+ import os
20
+ from aicser_embed import sign_embed_url
21
+
22
+ embed = sign_embed_url(
23
+ base_url="https://api.aicser.com", # your Aicser API
24
+ api_key=os.environ["AICSER_API_KEY"], # Settings → API keys; keep it on the server
25
+ dashboard_id="b4b3…", # or resource_id=… with scope="chart"|"report"
26
+ locked_filters=[{"field": "tenant_id", "value": customer.id}],
27
+ expires_in_minutes=60,
28
+ allowed_domains=["app.example.com"],
29
+ download="none", # "none" | "image" | "data"
30
+ )
31
+ # Put embed.url in an <iframe>, or hand it to @aicser/embed's getToken.
32
+ # Reports: sign_embed_url(..., resource_id="conversationId:messageId", scope="report")
33
+ ```
34
+
35
+ - **Locked filters.** Aicser applies them to every query made with the link, so a visitor can't see another customer's rows.
36
+ - **Single use.** A link opens once, so mint one per page view. With `@aicser/embed`, return a fresh link's `token` from `getToken` and sessions renew without reloading the page.
37
+ - **Errors.** Failures raise `AicserSignError`, which carries `.status`: 401 for a bad key, 402 for a plan without embedding, 404 for an unknown resource.
38
+
39
+ The package uses only the standard library and supports Python 3.8+.
@@ -0,0 +1,5 @@
1
+ aicser_embed/__init__.py,sha256=J1FvtvROJFDTQJ5raYgGIykYn_YPVF2mCVWw3e00XWg,3860
2
+ aicser_embed-0.3.1.dist-info/METADATA,sha256=BCgTp1QouqBVfwv0oZffa1JxizMjgGU4quE8JxIAZew,1760
3
+ aicser_embed-0.3.1.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
4
+ aicser_embed-0.3.1.dist-info/top_level.txt,sha256=9BjzfGRMvW-5H8y9WFZC6oIOVTCJVSjDDsSacExmOe8,13
5
+ aicser_embed-0.3.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ aicser_embed