kedai 0.2.2__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.
- kedai-0.2.2/PKG-INFO +33 -0
- kedai-0.2.2/README.md +18 -0
- kedai-0.2.2/pyproject.toml +26 -0
- kedai-0.2.2/setup.cfg +4 -0
- kedai-0.2.2/src/kedai/__init__.py +7 -0
- kedai-0.2.2/src/kedai/dashboard.py +336 -0
- kedai-0.2.2/src/kedai/endpoint.py +101 -0
- kedai-0.2.2/src/kedai.egg-info/PKG-INFO +33 -0
- kedai-0.2.2/src/kedai.egg-info/SOURCES.txt +9 -0
- kedai-0.2.2/src/kedai.egg-info/dependency_links.txt +1 -0
- kedai-0.2.2/src/kedai.egg-info/top_level.txt +1 -0
kedai-0.2.2/PKG-INFO
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: kedai
|
|
3
|
+
Version: 0.2.2
|
|
4
|
+
Summary: Python client for Kedai.
|
|
5
|
+
Author: Kedai
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://kedai.io
|
|
8
|
+
Project-URL: Documentation, https://kedai.io
|
|
9
|
+
Keywords: kedai,dashboard,workflow,api
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Requires-Python: >=3.9
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# kedai
|
|
17
|
+
|
|
18
|
+
Python client for Kedai. Standard library only; `pandas` is optional.
|
|
19
|
+
|
|
20
|
+
```python
|
|
21
|
+
import kedai
|
|
22
|
+
|
|
23
|
+
board = kedai.dashboard.get("https://app.kedai.io/v/<view>", api_key="kedai_ak_...")
|
|
24
|
+
board.widgets["filings"].to_df() # a table card as a DataFrame
|
|
25
|
+
board.widgets["new_per_day"].points() # [{"label": "2026-11-20", "value": 3}, ...]
|
|
26
|
+
board.widgets["total"].value(range=7) # a metric over the last seven days
|
|
27
|
+
|
|
28
|
+
answer = kedai.invoke("https://app.kedai.io/api/v1/endpoints/<token>", api_key="kedai_ek_...", cik="0000320193")
|
|
29
|
+
answer["result"]
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Pass your Kedai account key as `api_key=` or set `KEDAI_API_KEY`. `range` is `"all"`, a number
|
|
33
|
+
of days, or a `(start, end)` pair of dates.
|
kedai-0.2.2/README.md
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# kedai
|
|
2
|
+
|
|
3
|
+
Python client for Kedai. Standard library only; `pandas` is optional.
|
|
4
|
+
|
|
5
|
+
```python
|
|
6
|
+
import kedai
|
|
7
|
+
|
|
8
|
+
board = kedai.dashboard.get("https://app.kedai.io/v/<view>", api_key="kedai_ak_...")
|
|
9
|
+
board.widgets["filings"].to_df() # a table card as a DataFrame
|
|
10
|
+
board.widgets["new_per_day"].points() # [{"label": "2026-11-20", "value": 3}, ...]
|
|
11
|
+
board.widgets["total"].value(range=7) # a metric over the last seven days
|
|
12
|
+
|
|
13
|
+
answer = kedai.invoke("https://app.kedai.io/api/v1/endpoints/<token>", api_key="kedai_ek_...", cik="0000320193")
|
|
14
|
+
answer["result"]
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Pass your Kedai account key as `api_key=` or set `KEDAI_API_KEY`. `range` is `"all"`, a number
|
|
18
|
+
of days, or a `(start, end)` pair of dates.
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "kedai"
|
|
7
|
+
version = "0.2.2"
|
|
8
|
+
description = "Python client for Kedai."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
authors = [{ name = "Kedai" }]
|
|
13
|
+
keywords = ["kedai", "dashboard", "workflow", "api"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"License :: OSI Approved :: MIT License",
|
|
17
|
+
"Operating System :: OS Independent",
|
|
18
|
+
]
|
|
19
|
+
dependencies = []
|
|
20
|
+
|
|
21
|
+
[project.urls]
|
|
22
|
+
Homepage = "https://kedai.io"
|
|
23
|
+
Documentation = "https://kedai.io"
|
|
24
|
+
|
|
25
|
+
[tool.setuptools.packages.find]
|
|
26
|
+
where = ["src"]
|
kedai-0.2.2/setup.cfg
ADDED
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
"""Read a Kedai dashboard: the same numbers the page shows, as Python values.
|
|
2
|
+
|
|
3
|
+
board = kedai.dashboard.get("https://app.kedai.io/v/<view>", api_key="kedai_ak_...")
|
|
4
|
+
board.widgets["filings"].table() # the rows, newest first
|
|
5
|
+
board.widgets["new_per_day"].points() # the chart's points: [{"label": ..., "value": ...}]
|
|
6
|
+
board.widgets["total"].value() # the number on the metric card
|
|
7
|
+
board.widgets["filings"].to_df() # any of the above as a pandas DataFrame (requires pandas)
|
|
8
|
+
board.widgets["total"].recipe() # which of those calls read this card, as data
|
|
9
|
+
|
|
10
|
+
A dashboard's data document is one consistent snapshot: the layout (its cards) and the
|
|
11
|
+
dataset the cards read. Every card's aggregation happens here, by the rules the page uses:
|
|
12
|
+
the date window over the cards' date fields, sums per label, trend points sorted by label,
|
|
13
|
+
breakdowns sorted by value with a donut's long tail folded into "Other", tables newest
|
|
14
|
+
first. Pass an account key as `api_key=` or KEDAI_API_KEY.
|
|
15
|
+
|
|
16
|
+
Each Widget method that reads a card declares itself with @reads: the card kinds it serves
|
|
17
|
+
and the card keys whose values name the fields it reads. recipes() is that table and
|
|
18
|
+
to_df() dispatches through it.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
import json
|
|
22
|
+
import os
|
|
23
|
+
import re
|
|
24
|
+
import urllib.error
|
|
25
|
+
import urllib.request
|
|
26
|
+
from datetime import date, timedelta
|
|
27
|
+
|
|
28
|
+
__all__ = ["get", "Dashboard", "Widget", "DashboardError", "format_value", "money", "recipes"]
|
|
29
|
+
|
|
30
|
+
DATE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
|
|
31
|
+
MAX_RESPONSE_BYTES = 16 * 1024 * 1024
|
|
32
|
+
# The release in __init__.py and pyproject.toml; tests/clients keeps the three in step.
|
|
33
|
+
USER_AGENT = "kedai-python/0.2.2 (+https://kedai.io)"
|
|
34
|
+
MAX_SAFE_INTEGER = 2**53 - 1
|
|
35
|
+
MAX_CATEGORIES = 366
|
|
36
|
+
DONUT_SLICES = 7
|
|
37
|
+
BAR_ROWS = 12
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class DashboardError(RuntimeError):
|
|
41
|
+
"""The dashboard could not be read or a card could not be computed; .status, .detail."""
|
|
42
|
+
|
|
43
|
+
def __init__(self, status, detail):
|
|
44
|
+
super().__init__(f"HTTP {status}: {detail}" if status else detail)
|
|
45
|
+
self.status, self.detail = status, detail
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def get(url, api_key=None, timeout=30):
|
|
49
|
+
"""Fetch a published dashboard's data document and wrap it. `url` is the page's address
|
|
50
|
+
(https://host/v/<view>) or its data address; a private view needs an account key."""
|
|
51
|
+
data_url = url.rstrip("/")
|
|
52
|
+
if not data_url.endswith("/data"):
|
|
53
|
+
data_url += "/data"
|
|
54
|
+
document, etag = _fetch(data_url, api_key, timeout)
|
|
55
|
+
return Dashboard(document, url=data_url, api_key=api_key, timeout=timeout, etag=etag)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _fetch(url, api_key, timeout, etag=None):
|
|
59
|
+
headers = {"accept": "application/json", "user-agent": USER_AGENT}
|
|
60
|
+
key = api_key or os.environ.get("KEDAI_API_KEY")
|
|
61
|
+
if key:
|
|
62
|
+
headers["authorization"] = "Bearer " + key
|
|
63
|
+
if etag:
|
|
64
|
+
headers["if-none-match"] = etag
|
|
65
|
+
request = urllib.request.Request(url, headers=headers, method="GET")
|
|
66
|
+
try:
|
|
67
|
+
with urllib.request.urlopen(request, timeout=timeout) as response:
|
|
68
|
+
if response.status == 304:
|
|
69
|
+
return None, etag
|
|
70
|
+
raw = response.read(MAX_RESPONSE_BYTES + 1)
|
|
71
|
+
answer = response.headers.get("etag")
|
|
72
|
+
except urllib.error.HTTPError as refused:
|
|
73
|
+
if refused.code == 304:
|
|
74
|
+
return None, etag
|
|
75
|
+
body = refused.read(65536).decode("utf-8", "replace")
|
|
76
|
+
try:
|
|
77
|
+
detail = json.loads(body).get("detail") or body
|
|
78
|
+
except ValueError:
|
|
79
|
+
detail = body or "the view sent no sentence"
|
|
80
|
+
raise DashboardError(refused.code, detail) from None
|
|
81
|
+
if len(raw) > MAX_RESPONSE_BYTES:
|
|
82
|
+
raise DashboardError(None, f"the data document exceeded {MAX_RESPONSE_BYTES} bytes")
|
|
83
|
+
try:
|
|
84
|
+
document = json.loads(raw.decode("utf-8"))
|
|
85
|
+
except ValueError as error:
|
|
86
|
+
raise DashboardError(None, f"the data document is not JSON: {error}") from None
|
|
87
|
+
if not isinstance(document, dict) or not isinstance(document.get("layout"), dict):
|
|
88
|
+
raise DashboardError(None, "the answer is not a dashboard data document")
|
|
89
|
+
return document, answer
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class Dashboard:
|
|
93
|
+
"""One snapshot of a published dashboard: its layout, its dataset and its widgets by card id."""
|
|
94
|
+
|
|
95
|
+
def __init__(self, document, *, url=None, api_key=None, timeout=30, etag=None):
|
|
96
|
+
self.document, self.url, self.api_key, self.timeout, self.etag = document, url, api_key, timeout, etag
|
|
97
|
+
self.version = document.get("version")
|
|
98
|
+
self.revision = document.get("revision")
|
|
99
|
+
self.data_version = document.get("data_version")
|
|
100
|
+
self.layout = document["layout"]
|
|
101
|
+
self.type = document.get("type")
|
|
102
|
+
self.value = document.get("value")
|
|
103
|
+
self.freshness = document.get("freshness")
|
|
104
|
+
self.widgets = {card["id"]: Widget(self, card) for card in self.layout.get("cards", [])}
|
|
105
|
+
|
|
106
|
+
@property
|
|
107
|
+
def title(self):
|
|
108
|
+
return self.layout.get("title")
|
|
109
|
+
|
|
110
|
+
@property
|
|
111
|
+
def cards(self):
|
|
112
|
+
return list(self.layout.get("cards", []))
|
|
113
|
+
|
|
114
|
+
def refresh(self):
|
|
115
|
+
"""The current snapshot: this one when the server says nothing changed, else a new one."""
|
|
116
|
+
if not self.url:
|
|
117
|
+
return self
|
|
118
|
+
document, etag = _fetch(self.url, self.api_key, self.timeout, self.etag)
|
|
119
|
+
if document is None:
|
|
120
|
+
return self
|
|
121
|
+
return Dashboard(document, url=self.url, api_key=self.api_key, timeout=self.timeout, etag=etag)
|
|
122
|
+
|
|
123
|
+
def dates(self):
|
|
124
|
+
"""The first and last date any dated card sees, as the page computes its windows."""
|
|
125
|
+
found = []
|
|
126
|
+
for card in self.cards:
|
|
127
|
+
rows = self.value.get(card["source"]) if card.get("source") else self.value
|
|
128
|
+
if card.get("date") and isinstance(rows, list):
|
|
129
|
+
found.extend(str(row.get(card["date"])) for row in rows
|
|
130
|
+
if isinstance(row, dict) and isinstance(row.get(card["date"]), str) and DATE.match(row[card["date"]]))
|
|
131
|
+
found.sort()
|
|
132
|
+
return (found[0], found[-1]) if found else (None, None)
|
|
133
|
+
|
|
134
|
+
def window(self, range="all"):
|
|
135
|
+
"""(from, to) for a range: "all", 7 or 30 days back from the latest date, or (from, to)."""
|
|
136
|
+
first, last = self.dates()
|
|
137
|
+
if isinstance(range, (tuple, list)) and len(range) == 2:
|
|
138
|
+
return (range[0] or first, range[1] or last)
|
|
139
|
+
if isinstance(range, dict):
|
|
140
|
+
return (range.get("from") or first, range.get("to") or last)
|
|
141
|
+
if range in ("all", None) or not last:
|
|
142
|
+
return (first, last)
|
|
143
|
+
days = int(range)
|
|
144
|
+
start = date.fromisoformat(last) - timedelta(days=days - 1)
|
|
145
|
+
return (start.isoformat(), last)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
# The kinds a recipe names when it serves every card kind another recipe names.
|
|
149
|
+
EVERY_KIND = "*"
|
|
150
|
+
# How a script that reads a dashboard begins, for the snippets a page
|
|
151
|
+
# may compose from this module; recipes() gives each card kind's calls. URL and ID stand for
|
|
152
|
+
# the page's address and a card's id, which the page writes in as quoted strings.
|
|
153
|
+
SCRIPT = {
|
|
154
|
+
"get": {"call": "kedai.dashboard.get(URL)",
|
|
155
|
+
"keyed_call": 'kedai.dashboard.get(URL, api_key=os.environ["KEDAI_API_KEY"])',
|
|
156
|
+
"keyed_import": "import os",
|
|
157
|
+
"comment": "",
|
|
158
|
+
"keyed_comment": "a private dashboard needs your account key"},
|
|
159
|
+
"widgets": "board.widgets[ID]",
|
|
160
|
+
"range": 'Add range=7, range=30 or range=("2026-01-01", "2026-01-31") to any call to limit the dates.',
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def reads(*kinds, fields=(), aggregate=None, requires=None):
|
|
165
|
+
"""Declare a Widget method one of the calls that read a card.
|
|
166
|
+
|
|
167
|
+
`kinds` are the card kinds it serves, or EVERY_KIND; `fields` the card keys whose
|
|
168
|
+
values name the fields it reads (label, value, date, columns); `aggregate` how it
|
|
169
|
+
combines the first of those over the rows ("sum"), when it does; `requires` the extra
|
|
170
|
+
it needs ("pandas"), when it needs one. The first line of the method's docstring is
|
|
171
|
+
the one-line comment shown beside the call."""
|
|
172
|
+
def declare(method):
|
|
173
|
+
method.reads = {"kinds": tuple(kinds), "fields": tuple(fields), "aggregate": aggregate, "requires": requires}
|
|
174
|
+
return method
|
|
175
|
+
return declare
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
class Widget:
|
|
179
|
+
"""One card of a dashboard, computed as the page computes it."""
|
|
180
|
+
|
|
181
|
+
def __init__(self, dashboard, card):
|
|
182
|
+
self.dashboard, self.card = dashboard, card
|
|
183
|
+
self.id, self.kind, self.title = card["id"], card.get("kind"), card.get("title")
|
|
184
|
+
|
|
185
|
+
def __repr__(self):
|
|
186
|
+
return f"Widget({self.id!r}, kind={self.kind!r})"
|
|
187
|
+
|
|
188
|
+
def rows(self, range="all"):
|
|
189
|
+
"""The card's source within the date window: a list of rows, or a scalar for a
|
|
190
|
+
metric card over a scalar source."""
|
|
191
|
+
card = self.card
|
|
192
|
+
source = self.dashboard.value.get(card["source"]) if card.get("source") else self.dashboard.value
|
|
193
|
+
if not isinstance(source, list):
|
|
194
|
+
return source
|
|
195
|
+
if not card.get("date"):
|
|
196
|
+
return list(source)
|
|
197
|
+
start, end = self.dashboard.window(range)
|
|
198
|
+
if start and end and start > end:
|
|
199
|
+
return []
|
|
200
|
+
key = card["date"]
|
|
201
|
+
return [row for row in source
|
|
202
|
+
if (not start or str(row.get(key)) >= start) and (not end or str(row.get(key)) <= end)]
|
|
203
|
+
|
|
204
|
+
@reads("metric", fields=("value", "date"), aggregate="sum")
|
|
205
|
+
def value(self, range="all"):
|
|
206
|
+
"""The number on the card.
|
|
207
|
+
|
|
208
|
+
Its value field summed over the date window, or the stored number when the card
|
|
209
|
+
reads a single number, which no date window narrows."""
|
|
210
|
+
rows = self.rows(range)
|
|
211
|
+
if isinstance(rows, list):
|
|
212
|
+
return sum_values(row.get(self.card.get("value")) for row in rows)
|
|
213
|
+
return rows
|
|
214
|
+
|
|
215
|
+
@reads("metric", fields=("value", "date"))
|
|
216
|
+
def formatted(self, range="all"):
|
|
217
|
+
"""The same number, formatted as the card shows it."""
|
|
218
|
+
return format_value(self.value(range), self.card.get("format", "integer"))
|
|
219
|
+
|
|
220
|
+
@reads("line", "area", "bar", "donut", fields=("label", "value", "date"))
|
|
221
|
+
def points(self, range="all"):
|
|
222
|
+
"""The chart's points, as a list of {"label": ..., "value": ...}.
|
|
223
|
+
|
|
224
|
+
Grouped by label and summed over the date window, as the page draws them: a line or
|
|
225
|
+
area by label; bars and donuts by value, largest first, a donut's tail past seven
|
|
226
|
+
slices folded into Other."""
|
|
227
|
+
rows = self.rows(range)
|
|
228
|
+
if not isinstance(rows, list):
|
|
229
|
+
raise DashboardError(None, "Select a table source for this chart.")
|
|
230
|
+
groups = {}
|
|
231
|
+
label_key, value_key = self.card.get("label"), self.card.get("value")
|
|
232
|
+
for row in rows:
|
|
233
|
+
label = row.get(label_key)
|
|
234
|
+
label = "Unlabelled" if label is None else str(label)
|
|
235
|
+
groups[label] = sum_values([groups.get(label, 0), row.get(value_key)])
|
|
236
|
+
points = [{"label": label, "value": value} for label, value in groups.items()]
|
|
237
|
+
if len(points) > MAX_CATEGORIES:
|
|
238
|
+
raise DashboardError(None, f"This chart exceeds {MAX_CATEGORIES} categories. Narrow or aggregate its source.")
|
|
239
|
+
if self.kind in ("line", "area"):
|
|
240
|
+
points.sort(key=lambda p: p["label"])
|
|
241
|
+
else:
|
|
242
|
+
points.sort(key=lambda p: (-p["value"], p["label"]))
|
|
243
|
+
if self.kind == "donut" and len(points) > DONUT_SLICES + 1:
|
|
244
|
+
rest = points[DONUT_SLICES:]
|
|
245
|
+
points = points[:DONUT_SLICES] + [{"label": f"Other ({len(rest)})", "value": sum_values(p["value"] for p in rest)}]
|
|
246
|
+
return points
|
|
247
|
+
|
|
248
|
+
@reads("table", fields=("columns", "date"))
|
|
249
|
+
def table(self, range="all"):
|
|
250
|
+
"""The rows, newest first.
|
|
251
|
+
|
|
252
|
+
In the page's order: newest first by the date field, then latest first; whole rows
|
|
253
|
+
when the card names no columns."""
|
|
254
|
+
rows = self.rows(range)
|
|
255
|
+
if not isinstance(rows, list):
|
|
256
|
+
raise DashboardError(None, "Select a table source for this card.")
|
|
257
|
+
key = self.card.get("date")
|
|
258
|
+
indexed = list(enumerate(rows))
|
|
259
|
+
indexed.sort(key=lambda pair: ((str(pair[1].get(key)) if key else ""), pair[0]), reverse=True)
|
|
260
|
+
columns = self.card.get("columns")
|
|
261
|
+
return [{k: row.get(k) for k in columns} if columns else dict(row) for _, row in indexed]
|
|
262
|
+
|
|
263
|
+
@reads(EVERY_KIND, requires="pandas")
|
|
264
|
+
def to_df(self, range="all"):
|
|
265
|
+
"""The same data as a pandas DataFrame.
|
|
266
|
+
|
|
267
|
+
It frames the card's first recipe other than formatted(), so recipes() is the one
|
|
268
|
+
table of which call reads which kind: a table's rows, a chart's points, a metric's
|
|
269
|
+
number as one row named after its method."""
|
|
270
|
+
framed = next((entry["method"] for entry in self.recipe() if entry["method"] not in {"formatted", "to_df"}), None)
|
|
271
|
+
if framed is None:
|
|
272
|
+
raise DashboardError(None, (
|
|
273
|
+
f"Card {self.id!r} is a {self.kind!r} card, a kind this kedai package declares no call for; "
|
|
274
|
+
f"it reads {', '.join(recipes())} cards. A newer kedai may read it."))
|
|
275
|
+
try:
|
|
276
|
+
import pandas
|
|
277
|
+
except ImportError: # pragma: no cover
|
|
278
|
+
raise DashboardError(None, "to_df needs pandas installed.") from None
|
|
279
|
+
result = getattr(self, framed)(range)
|
|
280
|
+
return pandas.DataFrame(result if isinstance(result, list) else [{framed: result}])
|
|
281
|
+
|
|
282
|
+
def recipe(self):
|
|
283
|
+
"""The calls a published page's snippet shows for this card, in method order: one
|
|
284
|
+
{"method", "call", "comment", "fields", "aggregate", "requires"} each (recipes())."""
|
|
285
|
+
return recipes().get(self.kind, [])
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def recipes():
|
|
289
|
+
"""{kind: [recipe]} for every card kind a Widget method declares with @reads, each list
|
|
290
|
+
in method definition order. A recipe is {"method", "call", "comment", "fields",
|
|
291
|
+
"aggregate", "requires"}: the call a snippet writes, its docstring's first line, and the
|
|
292
|
+
declaration. A new list each time, so a caller may keep or change it."""
|
|
293
|
+
declared = [(name, member) for name, member in vars(Widget).items() if hasattr(member, "reads")]
|
|
294
|
+
kinds = dict.fromkeys(kind for _, member in declared for kind in member.reads["kinds"] if kind != EVERY_KIND)
|
|
295
|
+
return {kind: [_recipe(name, member) for name, member in declared
|
|
296
|
+
if kind in member.reads["kinds"] or EVERY_KIND in member.reads["kinds"]]
|
|
297
|
+
for kind in kinds}
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def _recipe(name, method):
|
|
301
|
+
said = method.reads
|
|
302
|
+
lines = (method.__doc__ or "").strip().splitlines()
|
|
303
|
+
return {"method": name, "call": name + "()", "comment": lines[0].strip() if lines else "",
|
|
304
|
+
"fields": list(said["fields"]), "aggregate": said["aggregate"], "requires": said["requires"]}
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def sum_values(values):
|
|
308
|
+
total = 0
|
|
309
|
+
for value in values:
|
|
310
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)) or value != value or value in (float("inf"), float("-inf")):
|
|
311
|
+
raise DashboardError(None, "This card received a non-numeric value.")
|
|
312
|
+
total += value
|
|
313
|
+
if abs(total) > MAX_SAFE_INTEGER:
|
|
314
|
+
raise DashboardError(None, "This chart exceeds its numeric bounds; aggregate or narrow the source upstream.")
|
|
315
|
+
return total
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def money(n, places=2):
|
|
319
|
+
"""Whole USD micro-units as the page prints them: half-up, grouped, `places` decimals."""
|
|
320
|
+
if not isinstance(n, int) or isinstance(n, bool) or abs(n) > MAX_SAFE_INTEGER:
|
|
321
|
+
raise DashboardError(None, "Currency requires safe integer USD micro-units.")
|
|
322
|
+
sign, n = ("−", -n) if n < 0 else ("", n)
|
|
323
|
+
div = 10 ** (6 - places)
|
|
324
|
+
n = (n + div // 2) // div
|
|
325
|
+
scale = 10 ** places
|
|
326
|
+
whole, fraction = divmod(n, scale)
|
|
327
|
+
return sign + "$" + f"{whole:,}" + (f".{fraction:0{places}d}" if places else "")
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def format_value(n, kind="integer", detail=False):
|
|
331
|
+
"""A card's number as the page prints it: currency from micro-units, else grouped."""
|
|
332
|
+
if kind == "usd_micro":
|
|
333
|
+
return money(n, 4 if detail or abs(n) < 10000 else 2)
|
|
334
|
+
if kind == "decimal":
|
|
335
|
+
return f"{round(n, 2):,.2f}".rstrip("0").rstrip(".") if isinstance(n, float) else f"{n:,}"
|
|
336
|
+
return f"{round(n):,}"
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""Call a published Kedai endpoint: one file, standard library only. Experimental.
|
|
2
|
+
|
|
3
|
+
import kedai
|
|
4
|
+
answer = kedai.invoke("https://host/api/v1/endpoints/<token>",
|
|
5
|
+
api_key="kedai_ek_...", query="widget", limit=5)
|
|
6
|
+
print(answer["result"]) # the result record, keyed by Output name
|
|
7
|
+
print(answer["revision"]) # the immutable revision that answered
|
|
8
|
+
print(kedai.schema("https://host/api/v1/endpoints/<token>", api_key="kedai_ek_..."))
|
|
9
|
+
|
|
10
|
+
The body is the request record: each keyword is one of the endpoint's Inputs, and a value
|
|
11
|
+
is whatever its type takes -- a string, a number, a boolean, a list, a table (a list of
|
|
12
|
+
row dicts), a record (a dict), or None for a nullable field; `schema()` reads the types.
|
|
13
|
+
The key is sent as a bearer header and never placed in the URL; leave it out (or set
|
|
14
|
+
KEDAI_API_KEY) on a draft that has minted none. Each call carries a fresh Idempotency-Key;
|
|
15
|
+
pass idempotency_key=answer["idempotency_key"] to re-send the same request and get the same
|
|
16
|
+
answer back. Refusals raise EndpointError with .status, .error, .detail, .retry_after and,
|
|
17
|
+
for a request the interface refused, .path/.expected/.arrived; a "delivery_unknown" error
|
|
18
|
+
means the work may have run and must not be retried blindly.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
import json
|
|
22
|
+
import os
|
|
23
|
+
import time
|
|
24
|
+
import urllib.error
|
|
25
|
+
import urllib.request
|
|
26
|
+
import uuid
|
|
27
|
+
|
|
28
|
+
__all__ = ["invoke", "schema", "EndpointError"]
|
|
29
|
+
MAX_RESPONSE_BYTES = 2 * 1024 * 1024
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class EndpointError(RuntimeError):
|
|
33
|
+
"""The endpoint refused or failed; .status, .error (a code or None), .detail, .retry_after,
|
|
34
|
+
and for a refused request record .path, .expected and .arrived (else None)."""
|
|
35
|
+
|
|
36
|
+
def __init__(self, status, error, detail, retry_after=None, path=None, expected=None, arrived=None):
|
|
37
|
+
super().__init__(f"HTTP {status} {error or 'refused'}: {detail}")
|
|
38
|
+
self.status, self.error, self.detail, self.retry_after = status, error, detail, retry_after
|
|
39
|
+
self.path, self.expected, self.arrived = path, expected, arrived
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def invoke(url, api_key=None, idempotency_key=None, timeout=180, **fields):
|
|
43
|
+
"""POST the request record to a published endpoint or channel URL; returns the envelope.
|
|
44
|
+
|
|
45
|
+
The envelope is the server's (revision, canonical_path, result, determinism, charge,
|
|
46
|
+
completeness, and channel/channel_path through a channel) plus idempotency_key and
|
|
47
|
+
cache (None, "miss" or "hit; age=<s>"). Each keyword is one Input of the record, sent
|
|
48
|
+
as JSON exactly as given.
|
|
49
|
+
"""
|
|
50
|
+
try:
|
|
51
|
+
body = json.dumps(fields, allow_nan=False).encode("utf-8")
|
|
52
|
+
except (TypeError, ValueError) as error:
|
|
53
|
+
raise TypeError(f"every input must be a JSON value: {error}") from None
|
|
54
|
+
key = idempotency_key or f"v1:{int(time.time() * 1000):013d}:{uuid.uuid4()}"
|
|
55
|
+
headers = {"content-type": "application/json", "accept": "application/json", "idempotency-key": key}
|
|
56
|
+
answer = _exchange(url, "POST", body, headers, api_key, timeout)
|
|
57
|
+
return {**answer["body"], "idempotency_key": key, "cache": answer["headers"].get("x-kedai-cache")}
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def schema(url, api_key=None, timeout=30):
|
|
61
|
+
"""GET <endpoint url>/schema: {revision, canonical_path, input_schema, output_schema, interface}."""
|
|
62
|
+
answer = _exchange(url.rstrip("/") + "/schema", "GET", None, {"accept": "application/json"}, api_key, timeout)
|
|
63
|
+
return answer["body"]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _exchange(url, method, data, headers, api_key, timeout):
|
|
67
|
+
headers.setdefault("user-agent", "kedai-python/0.1.0 (+https://kedai.io)")
|
|
68
|
+
api_key = api_key or os.environ.get("KEDAI_API_KEY")
|
|
69
|
+
if api_key:
|
|
70
|
+
headers["authorization"] = "Bearer " + api_key
|
|
71
|
+
request = urllib.request.Request(url, data=data, headers=headers, method=method)
|
|
72
|
+
try:
|
|
73
|
+
with urllib.request.urlopen(request, timeout=timeout) as response:
|
|
74
|
+
status, answer, body = response.status, response.headers, _read(response, response.status)
|
|
75
|
+
except urllib.error.HTTPError as refused:
|
|
76
|
+
status, answer, body = refused.code, refused.headers, _read(refused, refused.code)
|
|
77
|
+
if status != 200:
|
|
78
|
+
detail = body.get("detail") or body.get("message") or "the endpoint sent no sentence"
|
|
79
|
+
raise EndpointError(
|
|
80
|
+
status, body.get("error"), detail, _seconds(answer.get("retry-after")),
|
|
81
|
+
body.get("path"), body.get("expected"), body.get("arrived"),
|
|
82
|
+
)
|
|
83
|
+
return {"body": body, "headers": answer}
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _seconds(retry_after):
|
|
87
|
+
try:
|
|
88
|
+
return float(retry_after) if retry_after else None
|
|
89
|
+
except ValueError: # an HTTP-date; the contract sends whole seconds
|
|
90
|
+
return None
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _read(response, status):
|
|
94
|
+
raw = response.read(MAX_RESPONSE_BYTES + 1)
|
|
95
|
+
if len(raw) > MAX_RESPONSE_BYTES:
|
|
96
|
+
raise EndpointError(status, "response_too_large", f"the response exceeded {MAX_RESPONSE_BYTES} bytes")
|
|
97
|
+
try:
|
|
98
|
+
body = json.loads(raw.decode("utf-8") or "{}")
|
|
99
|
+
except ValueError:
|
|
100
|
+
body = {}
|
|
101
|
+
return body if isinstance(body, dict) else {}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: kedai
|
|
3
|
+
Version: 0.2.2
|
|
4
|
+
Summary: Python client for Kedai.
|
|
5
|
+
Author: Kedai
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://kedai.io
|
|
8
|
+
Project-URL: Documentation, https://kedai.io
|
|
9
|
+
Keywords: kedai,dashboard,workflow,api
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Requires-Python: >=3.9
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# kedai
|
|
17
|
+
|
|
18
|
+
Python client for Kedai. Standard library only; `pandas` is optional.
|
|
19
|
+
|
|
20
|
+
```python
|
|
21
|
+
import kedai
|
|
22
|
+
|
|
23
|
+
board = kedai.dashboard.get("https://app.kedai.io/v/<view>", api_key="kedai_ak_...")
|
|
24
|
+
board.widgets["filings"].to_df() # a table card as a DataFrame
|
|
25
|
+
board.widgets["new_per_day"].points() # [{"label": "2026-11-20", "value": 3}, ...]
|
|
26
|
+
board.widgets["total"].value(range=7) # a metric over the last seven days
|
|
27
|
+
|
|
28
|
+
answer = kedai.invoke("https://app.kedai.io/api/v1/endpoints/<token>", api_key="kedai_ek_...", cik="0000320193")
|
|
29
|
+
answer["result"]
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Pass your Kedai account key as `api_key=` or set `KEDAI_API_KEY`. `range` is `"all"`, a number
|
|
33
|
+
of days, or a `(start, end)` pair of dates.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
kedai
|