interlude-sdk 0.2.0__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.
interlude/storage.py ADDED
@@ -0,0 +1,155 @@
1
+ """The data plane: a project's files."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ import mimetypes
7
+ import os
8
+ from typing import IO, Any, Callable, Optional, Union
9
+
10
+ import httpx
11
+
12
+ from . import _parse
13
+ from ._http import Credentials, Transport, segment
14
+ from .errors import InterludeError
15
+ from .models import StorageObject
16
+
17
+ #: What upload() accepts: the bytes themselves, a path, or a binary file
18
+ #: object opened for reading.
19
+ Uploadable = Union[bytes, bytearray, memoryview, str, "os.PathLike[str]", IO[bytes]]
20
+
21
+
22
+ class StorageClient:
23
+ """Uploads, lists, fetches and deletes a project's files.
24
+
25
+ Needs the project's API key, or an account. End users cannot reach
26
+ storage directly; serve their files through your own server.
27
+ """
28
+
29
+ def __init__(
30
+ self,
31
+ transport: Transport,
32
+ credentials: Callable[[], Credentials],
33
+ project_id: str,
34
+ ) -> None:
35
+ self._transport = transport
36
+ self._credentials = credentials
37
+ self._path = f"/projects/{segment(project_id)}/storage/objects"
38
+
39
+ def upload(
40
+ self,
41
+ file: Uploadable,
42
+ *,
43
+ file_name: Optional[str] = None,
44
+ content_type: Optional[str] = None,
45
+ ) -> StorageObject:
46
+ """Uploads a file in one call, and returns its metadata.
47
+
48
+ ``file`` is the bytes, a path, or a binary file object. Paths and
49
+ named files supply ``file_name`` themselves; raw bytes need it.
50
+ ``content_type`` defaults to a guess from the file name.
51
+
52
+ Behind this are three HTTP requests: ask the API for a presigned URL,
53
+ PUT the bytes to it, then confirm. Cloudflare R2, where the bytes
54
+ live, has no presigned POST, so the API cannot collapse them.
55
+ """
56
+ if isinstance(file, (str, os.PathLike)):
57
+ with open(file, "rb") as handle:
58
+ return self.upload(
59
+ handle,
60
+ file_name=file_name or os.path.basename(os.fspath(file)),
61
+ content_type=content_type,
62
+ )
63
+
64
+ if isinstance(file, (bytes, bytearray, memoryview)):
65
+ content: Union[bytes, IO[bytes]] = bytes(file)
66
+ size = len(content)
67
+ else:
68
+ file_name = file_name or _name_of(file)
69
+ content, size = _sized(file)
70
+
71
+ if not file_name:
72
+ raise InterludeError(
73
+ "file_name_required",
74
+ "file_name is required when uploading bytes or an unnamed file",
75
+ 0,
76
+ )
77
+ content_type = (
78
+ content_type
79
+ or mimetypes.guess_type(file_name)[0]
80
+ or "application/octet-stream"
81
+ )
82
+
83
+ presigned, _ = self._send(
84
+ "POST",
85
+ "",
86
+ body={"file_name": file_name, "content_type": content_type, "size_bytes": size},
87
+ )
88
+
89
+ # Straight to object storage. No Interlude credential goes on this
90
+ # request: the URL itself is the authorisation.
91
+ try:
92
+ put = self._transport.http.put(
93
+ presigned["put_url"],
94
+ content=content,
95
+ headers={"Content-Type": content_type, "Content-Length": str(size)},
96
+ )
97
+ except httpx.TransportError as exc:
98
+ raise InterludeError(
99
+ "network_error", "could not reach storage to upload the file", 0
100
+ ) from exc
101
+ if put.status_code >= 400:
102
+ raise InterludeError(
103
+ "upload_failed",
104
+ f"upload failed with status {put.status_code}",
105
+ put.status_code,
106
+ )
107
+
108
+ confirmed, _ = self._send(
109
+ "POST",
110
+ f"/{segment(presigned['object_id'])}/confirm",
111
+ body={"file_name": file_name, "content_type": content_type},
112
+ )
113
+ return _parse.storage_object(confirmed)
114
+
115
+ def list(self) -> list[StorageObject]:
116
+ """Every file in the project."""
117
+ data, _ = self._send("GET", "")
118
+ return [_parse.storage_object(o) for o in data.get("objects") or []]
119
+
120
+ def get(self, id: str) -> StorageObject:
121
+ """A file's metadata, with a presigned ``download_url`` that expires."""
122
+ data, _ = self._send("GET", f"/{segment(id)}")
123
+ return _parse.storage_object(data["object"], data.get("download_url"))
124
+
125
+ def delete(self, id: str) -> None:
126
+ self._send("DELETE", f"/{segment(id)}")
127
+
128
+ def _send(
129
+ self, method: str, path: str, *, body: Optional[Any] = None
130
+ ) -> tuple[Any, dict[str, Any]]:
131
+ return self._transport.send_as(
132
+ self._credentials(), method, self._path + path, body=body
133
+ )
134
+
135
+
136
+ def _name_of(file: IO[bytes]) -> Optional[str]:
137
+ name = getattr(file, "name", None)
138
+ return os.path.basename(name) if isinstance(name, str) else None
139
+
140
+
141
+ def _sized(file: IO[bytes]) -> tuple[Union[bytes, IO[bytes]], int]:
142
+ """The file and how many bytes remain from its current position.
143
+
144
+ The API needs the size before the upload starts, and object storage needs
145
+ a Content-Length. A seekable file is measured and streamed; anything else
146
+ is read into memory, because there is no other way to learn its size.
147
+ """
148
+ try:
149
+ start = file.tell()
150
+ end = file.seek(0, io.SEEK_END)
151
+ file.seek(start)
152
+ return file, end - start
153
+ except (AttributeError, OSError, ValueError):
154
+ content = file.read()
155
+ return content, len(content)
interlude/table.py ADDED
@@ -0,0 +1,174 @@
1
+ """The data plane: a table's rows."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Callable, Iterable, Literal, Optional
6
+
7
+ from ._http import Credentials, Transport, segment
8
+ from .models import Filter, FilterLike, Measure, Page, Row, Summary, SummaryGroup
9
+
10
+
11
+ class TableClient:
12
+ """Reads and writes one table's rows.
13
+
14
+ Get one from ``client.table(name)`` (as your server, with the API key) or
15
+ ``client.as_user(token).table(name)`` (as one of your app's users, within
16
+ the table's access rules).
17
+ """
18
+
19
+ def __init__(
20
+ self,
21
+ transport: Transport,
22
+ credentials: Callable[[], Credentials],
23
+ project_id: str,
24
+ name: str,
25
+ ) -> None:
26
+ self._transport = transport
27
+ self._credentials = credentials
28
+ self._path = f"/projects/{segment(project_id)}/tables/{segment(name)}/rows"
29
+
30
+ def list(
31
+ self,
32
+ *,
33
+ limit: Optional[int] = None,
34
+ offset: Optional[int] = None,
35
+ order_by: Optional[str] = None,
36
+ order: Optional[Literal["ASC", "DESC"]] = None,
37
+ filters: Optional[Iterable[FilterLike]] = None,
38
+ ) -> list[Row]:
39
+ """The matching rows. For paging use :meth:`page`, which also says
40
+ whether there are more."""
41
+ return self.page(
42
+ limit=limit, offset=offset, order_by=order_by, order=order, filters=filters
43
+ ).rows
44
+
45
+ def page(
46
+ self,
47
+ *,
48
+ limit: Optional[int] = None,
49
+ offset: Optional[int] = None,
50
+ order_by: Optional[str] = None,
51
+ order: Optional[Literal["ASC", "DESC"]] = None,
52
+ filters: Optional[Iterable[FilterLike]] = None,
53
+ ) -> Page:
54
+ """One page of rows, and whether another page follows::
55
+
56
+ offset = 0
57
+ while True:
58
+ page = table.page(limit=100, offset=offset)
59
+ handle(page.rows)
60
+ if not page.has_more:
61
+ break
62
+ offset += 100
63
+ """
64
+ params: list[tuple[str, str]] = []
65
+ if limit is not None:
66
+ params.append(("limit", str(limit)))
67
+ if offset is not None:
68
+ params.append(("offset", str(offset)))
69
+ if order_by:
70
+ params.append(("order_by", order_by))
71
+ if order:
72
+ params.append(("order", order))
73
+ params += _filter_params(filters)
74
+ data, meta = self._send("GET", "", params=params)
75
+ return Page(rows=data or [], has_more=bool(meta.get("has_more")))
76
+
77
+ def summarize(
78
+ self,
79
+ *,
80
+ measure: Optional[Measure] = None,
81
+ column: Optional[str] = None,
82
+ group_by: Optional[str] = None,
83
+ filters: Optional[Iterable[FilterLike]] = None,
84
+ ) -> Summary:
85
+ """Count, total, average, lowest or highest of the matching rows.
86
+
87
+ ``measure`` defaults to ``"count"``. ``sum`` and ``avg`` need a number
88
+ column; ``min`` and ``max`` a number, text or date column. With
89
+ ``group_by``, one result per value of that column, largest first (at
90
+ most 50).
91
+ """
92
+ params: list[tuple[str, str]] = []
93
+ if measure:
94
+ params.append(("measure", measure))
95
+ if column:
96
+ params.append(("column", column))
97
+ if group_by:
98
+ params.append(("group_by", group_by))
99
+ params += _filter_params(filters)
100
+ data, _ = self._send("GET", "/summary", params=params)
101
+ return Summary(
102
+ groups=[SummaryGroup(key=g.get("key"), value=g.get("value"))
103
+ for g in data.get("groups") or []],
104
+ truncated=bool(data.get("truncated")),
105
+ )
106
+
107
+ def get(self, id: str) -> Row:
108
+ data, _ = self._send("GET", f"/{segment(id)}")
109
+ return data
110
+
111
+ def insert(self, row: Row) -> Row:
112
+ data, _ = self._send("POST", "", body=row)
113
+ return data
114
+
115
+ def update(self, id: str, row: Row) -> Row:
116
+ data, _ = self._send("PATCH", f"/{segment(id)}", body=row)
117
+ return data
118
+
119
+ def delete(self, id: str) -> None:
120
+ self._send("DELETE", f"/{segment(id)}")
121
+
122
+ def update_matching(
123
+ self, row: Row, *, filters: Iterable[FilterLike], expected: int
124
+ ) -> int:
125
+ """Sets ``row``'s fields on every matching row. Returns how many rows
126
+ changed.
127
+
128
+ ``expected`` is how many rows you expect the filters to match. If they
129
+ match a different number when the request runs, nothing changes and
130
+ :class:`InterludeError` ``row_count_mismatch`` is raised, its
131
+ ``details`` ``{"expected": n, "actual": m}``. At least one filter; at
132
+ most 10,000 rows. Needs the API key or an account; an end user cannot.
133
+ """
134
+ data, _ = self._send(
135
+ "PATCH", "", body=row, params=_matching_params(filters, expected)
136
+ )
137
+ return int(data["affected"])
138
+
139
+ def delete_matching(self, *, filters: Iterable[FilterLike], expected: int) -> int:
140
+ """Deletes every matching row. Returns how many were deleted. The
141
+ same ``expected`` rule as :meth:`update_matching`."""
142
+ data, _ = self._send("DELETE", "", params=_matching_params(filters, expected))
143
+ return int(data["affected"])
144
+
145
+ def _send(
146
+ self,
147
+ method: str,
148
+ path: str,
149
+ *,
150
+ body: Optional[Any] = None,
151
+ params: Optional[list[tuple[str, str]]] = None,
152
+ ) -> tuple[Any, dict[str, Any]]:
153
+ return self._transport.send_as(
154
+ self._credentials(), method, self._path + path, body=body, params=params
155
+ )
156
+
157
+
158
+ def _filter_params(filters: Optional[Iterable[FilterLike]]) -> list[tuple[str, str]]:
159
+ params = []
160
+ for f in filters or ():
161
+ column, op, value = (f.column, f.op, f.value) if isinstance(f, Filter) else f
162
+ params.append(("filter", f"{column}.{op}.{_format_value(value)}"))
163
+ return params
164
+
165
+
166
+ def _format_value(value: Any) -> str:
167
+ # str(True) is "True"; the API, like every other client, sends "true".
168
+ if isinstance(value, bool):
169
+ return "true" if value else "false"
170
+ return str(value)
171
+
172
+
173
+ def _matching_params(filters: Iterable[FilterLike], expected: int) -> list[tuple[str, str]]:
174
+ return _filter_params(filters) + [("expected", str(expected))]
@@ -0,0 +1,128 @@
1
+ Metadata-Version: 2.4
2
+ Name: interlude-sdk
3
+ Version: 0.2.0
4
+ Summary: Official Python SDK for Interlude: tables, storage, end users and projects
5
+ License: MIT
6
+ Project-URL: Homepage, https://useinterlude.com
7
+ Project-URL: Documentation, https://useinterlude.com/docs
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ Requires-Dist: httpx<1,>=0.27
18
+ Provides-Extra: test
19
+ Requires-Dist: pytest>=8; extra == "test"
20
+
21
+ # interlude-sdk
22
+
23
+ The Python client for [Interlude](https://useinterlude.com), for servers, scripts and CLIs: table rows, file storage, your app's users, and managing projects and API keys.
24
+
25
+ ```bash
26
+ pip install interlude-sdk
27
+ ```
28
+
29
+ Package name `interlude-sdk`; import name `interlude`. Python 3.10+.
30
+
31
+ ## Rows, as your server
32
+
33
+ ```python
34
+ import os
35
+ from interlude import Client
36
+
37
+ client = Client(project_id="proj_123", api_key=os.environ["INTERLUDE_API_KEY"])
38
+ todos = client.table("todos")
39
+
40
+ todo = todos.insert({"title": "Ship it", "done": False})
41
+ todos.update(todo["id"], {"done": True})
42
+ open_todos = todos.list(filters=[("done", "eq", False)], order_by="created_at", order="DESC")
43
+
44
+ # Paging: no total count, just whether there is more.
45
+ offset = 0
46
+ while True:
47
+ page = todos.page(limit=100, offset=offset)
48
+ ...
49
+ if not page.has_more:
50
+ break
51
+ offset += 100
52
+
53
+ # Count, sum, avg, min, max; optionally grouped.
54
+ summary = todos.summarize(measure="count", group_by="list")
55
+
56
+ # Change or delete many rows, only if the filters match as many as you expect.
57
+ todos.update_matching({"done": True}, filters=[("list", "eq", "inbox")], expected=12)
58
+ ```
59
+
60
+ Filters are `(column, op, value)` tuples or `Filter(column, op, value)`. Ops: `eq`, `neq`, `gt`, `gte`, `lt`, `lte`, `contains` (text, case-insensitive), `is` (`"null"` or `"not_null"`). Every filter must hold.
61
+
62
+ ## Files
63
+
64
+ ```python
65
+ obj = client.storage.upload("report.pdf") # a path
66
+ obj = client.storage.upload(b"...", file_name="notes.txt") # bytes
67
+ with open("photo.jpg", "rb") as f:
68
+ obj = client.storage.upload(f) # a file object
69
+
70
+ link = client.storage.get(obj.id).download_url # presigned, expires
71
+ client.storage.delete(obj.id)
72
+ ```
73
+
74
+ ## Your app's users
75
+
76
+ Your app signs its users in with the JavaScript SDK and sends their access token to your server. Pass the project's publishable key to work with it:
77
+
78
+ ```python
79
+ client = Client(
80
+ project_id="proj_123",
81
+ api_key=os.environ["INTERLUDE_API_KEY"],
82
+ publishable_key="il_pk_v1_...",
83
+ )
84
+
85
+ user = client.auth.get_user(token) # who sent this request? 401 if the token is bad
86
+
87
+ # Read and write rows *as that user*: the table's access rules apply, and the
88
+ # API key is not sent.
89
+ mine = client.as_user(token).table("todos").list()
90
+ ```
91
+
92
+ Prefer `as_user()` over the API key whenever you act on a user's behalf. The API key bypasses the access rules that keep one user out of another's rows.
93
+
94
+ ## Projects and API keys
95
+
96
+ These act for an Interlude account, so they take an account credential rather than a project key:
97
+
98
+ ```python
99
+ from interlude.models import CreateProjectRequest, CreateAPIKeyRequest
100
+
101
+ client = Client()
102
+ client.account.sign_in(email="you@example.com", password="...") # renews its token itself
103
+ # or: Client(os.environ["INTERLUDE_ACCESS_TOKEN"]) # used as is
104
+
105
+ project = client.projects.create(CreateProjectRequest(name="My App", slug="my-app"))
106
+ key = client.api_keys.create(project.id, CreateAPIKeyRequest(name="server", role="DEVELOPER"))
107
+ print(key.key) # shown once; store it as a secret
108
+ ```
109
+
110
+ ## Errors
111
+
112
+ Everything raises `interlude.InterludeError` with `code`, `message`, `status_code` and `details`. `status_code` is `0` when the SDK refused to send a request (`project_id_required`, `publishable_key_required`, `file_name_required`, ...) or could not reach the API (`network_error`). The codes are the API's own, shared with the JavaScript and Go SDKs.
113
+
114
+ ```python
115
+ from interlude import InterludeError
116
+
117
+ try:
118
+ todos.delete_matching(filters=[("done", "eq", True)], expected=10)
119
+ except InterludeError as err:
120
+ if err.code == "row_count_mismatch":
121
+ print(err.details) # {"expected": 10, "actual": 14}
122
+ ```
123
+
124
+ A key passed in the wrong place (a secret key as `publishable_key`, say) raises `ValueError` from `Client()` immediately.
125
+
126
+ `Client` is safe to share between threads. Use it as a context manager, or call `close()`, to release its connections.
127
+
128
+ See [CHANGELOG.md](CHANGELOG.md) for what changed between releases.
@@ -0,0 +1,13 @@
1
+ interlude/__init__.py,sha256=1GikVFmsSRSfQHeLWncHdwCE7mjT8yDxXUCJ5P78FtQ,776
2
+ interlude/_http.py,sha256=b80-yI_UDBbB-QUFSq-7rghAER3JbTWHRMY_pLjts84,6172
3
+ interlude/_parse.py,sha256=0rAXmuKJj41oUycyGiPeSTlNKiXExHDuH5_bDVDoZM0,2674
4
+ interlude/account.py,sha256=kj4Nv956guXsy6W_JHnojVQPfUvtarWqwqhwcDnURmI,6191
5
+ interlude/client.py,sha256=toGgewppTvuvH3n_wOjmnLziaOhp4k5ungfGddAOW5o,13778
6
+ interlude/errors.py,sha256=CP1MhzTpaU7V1hbS41fBbLTGU0ZdDrhg3zjgoxalTe4,1403
7
+ interlude/models.py,sha256=5IIFLJ4eJbl1yumf51URbZU2GLV58VUT52uHqs3PlCc,5090
8
+ interlude/storage.py,sha256=e0-nqoKvgRrLfuch04Lc0v-vOLr_Y2sA0gk6UIPeaw4,5413
9
+ interlude/table.py,sha256=cC-6p44dHNy2XbEzPAUVcEMctmaug730fSc6jH_MeSg,6212
10
+ interlude_sdk-0.2.0.dist-info/METADATA,sha256=oTmPJN4SpFvlG4iT-AdNA1WcdBEBeZ9NWUWRh8__3HU,4811
11
+ interlude_sdk-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
12
+ interlude_sdk-0.2.0.dist-info/top_level.txt,sha256=-5TMepyWUKJk0V-YHq6Cczdw3oKnpXSSnSpLSorg5aY,10
13
+ interlude_sdk-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ interlude