interlude-sdk 0.2.0__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.
- interlude_sdk-0.2.0/PKG-INFO +128 -0
- interlude_sdk-0.2.0/README.md +108 -0
- interlude_sdk-0.2.0/pyproject.toml +33 -0
- interlude_sdk-0.2.0/setup.cfg +4 -0
- interlude_sdk-0.2.0/src/interlude/__init__.py +44 -0
- interlude_sdk-0.2.0/src/interlude/_http.py +191 -0
- interlude_sdk-0.2.0/src/interlude/_parse.py +85 -0
- interlude_sdk-0.2.0/src/interlude/account.py +162 -0
- interlude_sdk-0.2.0/src/interlude/client.py +353 -0
- interlude_sdk-0.2.0/src/interlude/errors.py +41 -0
- interlude_sdk-0.2.0/src/interlude/models.py +218 -0
- interlude_sdk-0.2.0/src/interlude/storage.py +155 -0
- interlude_sdk-0.2.0/src/interlude/table.py +174 -0
- interlude_sdk-0.2.0/src/interlude_sdk.egg-info/PKG-INFO +128 -0
- interlude_sdk-0.2.0/src/interlude_sdk.egg-info/SOURCES.txt +22 -0
- interlude_sdk-0.2.0/src/interlude_sdk.egg-info/dependency_links.txt +1 -0
- interlude_sdk-0.2.0/src/interlude_sdk.egg-info/requires.txt +4 -0
- interlude_sdk-0.2.0/src/interlude_sdk.egg-info/top_level.txt +1 -0
- interlude_sdk-0.2.0/tests/test_account_session.py +179 -0
- interlude_sdk-0.2.0/tests/test_client_auth.py +138 -0
- interlude_sdk-0.2.0/tests/test_end_user.py +72 -0
- interlude_sdk-0.2.0/tests/test_integration.py +234 -0
- interlude_sdk-0.2.0/tests/test_storage.py +135 -0
- interlude_sdk-0.2.0/tests/test_table.py +194 -0
|
@@ -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,108 @@
|
|
|
1
|
+
# interlude-sdk
|
|
2
|
+
|
|
3
|
+
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.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pip install interlude-sdk
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
Package name `interlude-sdk`; import name `interlude`. Python 3.10+.
|
|
10
|
+
|
|
11
|
+
## Rows, as your server
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
import os
|
|
15
|
+
from interlude import Client
|
|
16
|
+
|
|
17
|
+
client = Client(project_id="proj_123", api_key=os.environ["INTERLUDE_API_KEY"])
|
|
18
|
+
todos = client.table("todos")
|
|
19
|
+
|
|
20
|
+
todo = todos.insert({"title": "Ship it", "done": False})
|
|
21
|
+
todos.update(todo["id"], {"done": True})
|
|
22
|
+
open_todos = todos.list(filters=[("done", "eq", False)], order_by="created_at", order="DESC")
|
|
23
|
+
|
|
24
|
+
# Paging: no total count, just whether there is more.
|
|
25
|
+
offset = 0
|
|
26
|
+
while True:
|
|
27
|
+
page = todos.page(limit=100, offset=offset)
|
|
28
|
+
...
|
|
29
|
+
if not page.has_more:
|
|
30
|
+
break
|
|
31
|
+
offset += 100
|
|
32
|
+
|
|
33
|
+
# Count, sum, avg, min, max; optionally grouped.
|
|
34
|
+
summary = todos.summarize(measure="count", group_by="list")
|
|
35
|
+
|
|
36
|
+
# Change or delete many rows, only if the filters match as many as you expect.
|
|
37
|
+
todos.update_matching({"done": True}, filters=[("list", "eq", "inbox")], expected=12)
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
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.
|
|
41
|
+
|
|
42
|
+
## Files
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
obj = client.storage.upload("report.pdf") # a path
|
|
46
|
+
obj = client.storage.upload(b"...", file_name="notes.txt") # bytes
|
|
47
|
+
with open("photo.jpg", "rb") as f:
|
|
48
|
+
obj = client.storage.upload(f) # a file object
|
|
49
|
+
|
|
50
|
+
link = client.storage.get(obj.id).download_url # presigned, expires
|
|
51
|
+
client.storage.delete(obj.id)
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## Your app's users
|
|
55
|
+
|
|
56
|
+
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:
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
client = Client(
|
|
60
|
+
project_id="proj_123",
|
|
61
|
+
api_key=os.environ["INTERLUDE_API_KEY"],
|
|
62
|
+
publishable_key="il_pk_v1_...",
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
user = client.auth.get_user(token) # who sent this request? 401 if the token is bad
|
|
66
|
+
|
|
67
|
+
# Read and write rows *as that user*: the table's access rules apply, and the
|
|
68
|
+
# API key is not sent.
|
|
69
|
+
mine = client.as_user(token).table("todos").list()
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
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.
|
|
73
|
+
|
|
74
|
+
## Projects and API keys
|
|
75
|
+
|
|
76
|
+
These act for an Interlude account, so they take an account credential rather than a project key:
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
from interlude.models import CreateProjectRequest, CreateAPIKeyRequest
|
|
80
|
+
|
|
81
|
+
client = Client()
|
|
82
|
+
client.account.sign_in(email="you@example.com", password="...") # renews its token itself
|
|
83
|
+
# or: Client(os.environ["INTERLUDE_ACCESS_TOKEN"]) # used as is
|
|
84
|
+
|
|
85
|
+
project = client.projects.create(CreateProjectRequest(name="My App", slug="my-app"))
|
|
86
|
+
key = client.api_keys.create(project.id, CreateAPIKeyRequest(name="server", role="DEVELOPER"))
|
|
87
|
+
print(key.key) # shown once; store it as a secret
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
## Errors
|
|
91
|
+
|
|
92
|
+
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.
|
|
93
|
+
|
|
94
|
+
```python
|
|
95
|
+
from interlude import InterludeError
|
|
96
|
+
|
|
97
|
+
try:
|
|
98
|
+
todos.delete_matching(filters=[("done", "eq", True)], expected=10)
|
|
99
|
+
except InterludeError as err:
|
|
100
|
+
if err.code == "row_count_mismatch":
|
|
101
|
+
print(err.details) # {"expected": 10, "actual": 14}
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
A key passed in the wrong place (a secret key as `publishable_key`, say) raises `ValueError` from `Client()` immediately.
|
|
105
|
+
|
|
106
|
+
`Client` is safe to share between threads. Use it as a context manager, or call `close()`, to release its connections.
|
|
107
|
+
|
|
108
|
+
See [CHANGELOG.md](CHANGELOG.md) for what changed between releases.
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=64", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "interlude-sdk"
|
|
7
|
+
version = "0.2.0"
|
|
8
|
+
description = "Official Python SDK for Interlude: tables, storage, end users and projects"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = {text = "MIT"}
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
dependencies = [
|
|
13
|
+
"httpx>=0.27,<1",
|
|
14
|
+
]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 3 - Alpha",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"License :: OSI Approved :: MIT License",
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Programming Language :: Python :: 3.10",
|
|
21
|
+
"Programming Language :: Python :: 3.11",
|
|
22
|
+
"Programming Language :: Python :: 3.12",
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
[project.optional-dependencies]
|
|
26
|
+
test = ["pytest>=8"]
|
|
27
|
+
|
|
28
|
+
[project.urls]
|
|
29
|
+
Homepage = "https://useinterlude.com"
|
|
30
|
+
Documentation = "https://useinterlude.com/docs"
|
|
31
|
+
|
|
32
|
+
[tool.setuptools.packages.find]
|
|
33
|
+
where = ["src"]
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Interlude Python SDK.
|
|
3
|
+
|
|
4
|
+
Official Python client library for the Interlude BaaS platform.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from .account import AccountClient
|
|
10
|
+
from .client import Client, EndUserAuth, UserScope
|
|
11
|
+
from .errors import ClientError, InterludeError
|
|
12
|
+
from .models import (
|
|
13
|
+
Account,
|
|
14
|
+
EndUser,
|
|
15
|
+
Filter,
|
|
16
|
+
Page,
|
|
17
|
+
Row,
|
|
18
|
+
StorageObject,
|
|
19
|
+
Summary,
|
|
20
|
+
SummaryGroup,
|
|
21
|
+
)
|
|
22
|
+
from .storage import StorageClient
|
|
23
|
+
from .table import TableClient
|
|
24
|
+
|
|
25
|
+
__version__ = "0.2.0"
|
|
26
|
+
|
|
27
|
+
__all__ = [
|
|
28
|
+
"Account",
|
|
29
|
+
"AccountClient",
|
|
30
|
+
"Client",
|
|
31
|
+
"ClientError",
|
|
32
|
+
"EndUser",
|
|
33
|
+
"EndUserAuth",
|
|
34
|
+
"Filter",
|
|
35
|
+
"InterludeError",
|
|
36
|
+
"Page",
|
|
37
|
+
"Row",
|
|
38
|
+
"StorageClient",
|
|
39
|
+
"StorageObject",
|
|
40
|
+
"Summary",
|
|
41
|
+
"SummaryGroup",
|
|
42
|
+
"TableClient",
|
|
43
|
+
"UserScope",
|
|
44
|
+
]
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"""The one place the API's response envelope is unwrapped.
|
|
2
|
+
|
|
3
|
+
Every Interlude response is ``{"data": ..., "meta": ...}`` on success or
|
|
4
|
+
``{"error": {"code", "message", "details"}}`` on failure. Nothing outside
|
|
5
|
+
this module needs to know that.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from typing import Any, Optional, Protocol
|
|
12
|
+
from urllib.parse import quote
|
|
13
|
+
|
|
14
|
+
import httpx
|
|
15
|
+
|
|
16
|
+
from .errors import InterludeError
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def segment(value: str) -> str:
|
|
20
|
+
"""One path segment, encoded.
|
|
21
|
+
|
|
22
|
+
Table names, row IDs and object IDs come from the caller. An unencoded
|
|
23
|
+
``/``, ``?``, ``#`` or ``../`` in one would send the request, credentials
|
|
24
|
+
and all, to a different endpoint than the method names.
|
|
25
|
+
"""
|
|
26
|
+
return quote(value, safe="")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class TokenSource(Protocol):
|
|
30
|
+
"""Where a request's bearer token comes from, and how to renew it."""
|
|
31
|
+
|
|
32
|
+
def get(self) -> Optional[str]:
|
|
33
|
+
"""The token to send, renewed first if it is about to expire."""
|
|
34
|
+
...
|
|
35
|
+
|
|
36
|
+
def renew(self, rejected: str) -> Optional[str]:
|
|
37
|
+
"""Called after the API refused ``rejected``. Returns the token to
|
|
38
|
+
retry with, or ``None`` when there is nothing better to offer."""
|
|
39
|
+
...
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class StaticToken:
|
|
43
|
+
"""A token the caller supplied and the SDK cannot renew."""
|
|
44
|
+
|
|
45
|
+
def __init__(self, token: str) -> None:
|
|
46
|
+
self._token = token
|
|
47
|
+
|
|
48
|
+
def get(self) -> Optional[str]:
|
|
49
|
+
return self._token
|
|
50
|
+
|
|
51
|
+
def renew(self, rejected: str) -> Optional[str]:
|
|
52
|
+
return None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass(frozen=True)
|
|
56
|
+
class Credentials:
|
|
57
|
+
"""What one request authenticates with. Each field is its own header:
|
|
58
|
+
|
|
59
|
+
* ``api_key``: ``X-API-Key``, the secret project key.
|
|
60
|
+
* ``publishable_key``: ``X-Publishable-Key``, which names the project and
|
|
61
|
+
authorises nothing on its own.
|
|
62
|
+
* ``tokens``: ``Authorization: Bearer``, an account or end-user JWT.
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
api_key: Optional[str] = None
|
|
66
|
+
publishable_key: Optional[str] = None
|
|
67
|
+
tokens: Optional[TokenSource] = None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class Transport:
|
|
71
|
+
"""Sends requests to the API and unwraps the envelope."""
|
|
72
|
+
|
|
73
|
+
def __init__(self, base_url: str, http_client: httpx.Client) -> None:
|
|
74
|
+
# Without trailing slashes, so base + "/auth" cannot become "//auth",
|
|
75
|
+
# which the API does not route.
|
|
76
|
+
self.base_url = base_url.rstrip("/")
|
|
77
|
+
self.http = http_client
|
|
78
|
+
|
|
79
|
+
def send(
|
|
80
|
+
self,
|
|
81
|
+
method: str,
|
|
82
|
+
path: str,
|
|
83
|
+
*,
|
|
84
|
+
token: Optional[str] = None,
|
|
85
|
+
api_key: Optional[str] = None,
|
|
86
|
+
publishable_key: Optional[str] = None,
|
|
87
|
+
body: Optional[Any] = None,
|
|
88
|
+
params: Optional[list[tuple[str, str]]] = None,
|
|
89
|
+
) -> tuple[Any, dict[str, Any]]:
|
|
90
|
+
"""Sends one request. Returns ``(data, meta)``."""
|
|
91
|
+
headers = {"Content-Type": "application/json"}
|
|
92
|
+
if token:
|
|
93
|
+
headers["Authorization"] = f"Bearer {token}"
|
|
94
|
+
if api_key:
|
|
95
|
+
headers["X-API-Key"] = api_key
|
|
96
|
+
if publishable_key:
|
|
97
|
+
headers["X-Publishable-Key"] = publishable_key
|
|
98
|
+
|
|
99
|
+
try:
|
|
100
|
+
response = self.http.request(
|
|
101
|
+
method,
|
|
102
|
+
f"{self.base_url}{path}",
|
|
103
|
+
headers=headers,
|
|
104
|
+
json=body,
|
|
105
|
+
params=params or None,
|
|
106
|
+
)
|
|
107
|
+
except httpx.TransportError as exc:
|
|
108
|
+
raise InterludeError(
|
|
109
|
+
"network_error",
|
|
110
|
+
"could not reach the Interlude API; check your network "
|
|
111
|
+
"connection and base_url",
|
|
112
|
+
0,
|
|
113
|
+
) from exc
|
|
114
|
+
|
|
115
|
+
if response.status_code >= 400:
|
|
116
|
+
# A proxy in front of the API can answer with HTML or nothing at
|
|
117
|
+
# all, so the error body is read defensively.
|
|
118
|
+
error = _error_body(response)
|
|
119
|
+
raise InterludeError(
|
|
120
|
+
error.get("code") or "unknown_error",
|
|
121
|
+
error.get("message")
|
|
122
|
+
or f"request failed with status {response.status_code}",
|
|
123
|
+
response.status_code,
|
|
124
|
+
error.get("details"),
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
if response.status_code == 204:
|
|
128
|
+
return None, {}
|
|
129
|
+
|
|
130
|
+
try:
|
|
131
|
+
payload = response.json()
|
|
132
|
+
except ValueError as exc:
|
|
133
|
+
raise InterludeError(
|
|
134
|
+
"invalid_response",
|
|
135
|
+
"the API answered with a body that is not JSON",
|
|
136
|
+
response.status_code,
|
|
137
|
+
) from exc
|
|
138
|
+
if not isinstance(payload, dict):
|
|
139
|
+
return None, {}
|
|
140
|
+
return payload.get("data"), payload.get("meta") or {}
|
|
141
|
+
|
|
142
|
+
def send_as(
|
|
143
|
+
self,
|
|
144
|
+
credentials: Credentials,
|
|
145
|
+
method: str,
|
|
146
|
+
path: str,
|
|
147
|
+
*,
|
|
148
|
+
body: Optional[Any] = None,
|
|
149
|
+
params: Optional[list[tuple[str, str]]] = None,
|
|
150
|
+
) -> tuple[Any, dict[str, Any]]:
|
|
151
|
+
"""Sends a request, and if the API refuses the bearer token, renews
|
|
152
|
+
it and sends the request once more.
|
|
153
|
+
|
|
154
|
+
A token can be revoked before its expiry, and the expiry is judged on
|
|
155
|
+
this machine. The retry is safe for writes: a 401 comes from the API's
|
|
156
|
+
middleware, before any handler ran. Exactly one retry, no loop.
|
|
157
|
+
"""
|
|
158
|
+
tokens = credentials.tokens
|
|
159
|
+
token = tokens.get() if tokens else None
|
|
160
|
+
|
|
161
|
+
def attempt(bearer: Optional[str]) -> tuple[Any, dict[str, Any]]:
|
|
162
|
+
return self.send(
|
|
163
|
+
method,
|
|
164
|
+
path,
|
|
165
|
+
token=bearer,
|
|
166
|
+
api_key=credentials.api_key,
|
|
167
|
+
publishable_key=credentials.publishable_key,
|
|
168
|
+
body=body,
|
|
169
|
+
params=params,
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
try:
|
|
173
|
+
return attempt(token)
|
|
174
|
+
except InterludeError as exc:
|
|
175
|
+
if exc.status_code != 401 or not token or tokens is None:
|
|
176
|
+
raise
|
|
177
|
+
renewed = tokens.renew(token)
|
|
178
|
+
if not renewed or renewed == token:
|
|
179
|
+
raise
|
|
180
|
+
return attempt(renewed)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _error_body(response: httpx.Response) -> dict[str, Any]:
|
|
184
|
+
try:
|
|
185
|
+
payload = response.json()
|
|
186
|
+
except ValueError:
|
|
187
|
+
return {}
|
|
188
|
+
if not isinstance(payload, dict):
|
|
189
|
+
return {}
|
|
190
|
+
error = payload.get("error")
|
|
191
|
+
return error if isinstance(error, dict) else {}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Turning API JSON into models."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
from typing import Any, Optional
|
|
8
|
+
|
|
9
|
+
from .models import Account, APIKeyMetadata, EndUser, Project, StorageObject
|
|
10
|
+
|
|
11
|
+
# The API is written in Go, which emits RFC 3339 with up to nine fractional
|
|
12
|
+
# digits ("...T10:00:00.123456789Z"). datetime.fromisoformat accepts at most
|
|
13
|
+
# six before Python 3.11, and no "Z" before 3.11 either.
|
|
14
|
+
_FRACTION = re.compile(r"\.(\d{6})\d+")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def parse_datetime(value: str) -> datetime:
|
|
18
|
+
"""Parses an RFC 3339 timestamp from the API."""
|
|
19
|
+
normalized = _FRACTION.sub(r".\1", value.replace("Z", "+00:00"))
|
|
20
|
+
return datetime.fromisoformat(normalized)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def optional_datetime(value: Optional[str]) -> Optional[datetime]:
|
|
24
|
+
return parse_datetime(value) if value else None
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def project(data: dict[str, Any]) -> Project:
|
|
28
|
+
return Project(
|
|
29
|
+
id=data["id"],
|
|
30
|
+
name=data["name"],
|
|
31
|
+
slug=data["slug"],
|
|
32
|
+
region=data["region"],
|
|
33
|
+
created_at=parse_datetime(data["created_at"]),
|
|
34
|
+
updated_at=parse_datetime(data["updated_at"]),
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def api_key_metadata(data: dict[str, Any]) -> APIKeyMetadata:
|
|
39
|
+
return APIKeyMetadata(
|
|
40
|
+
id=data["id"],
|
|
41
|
+
display_id=data["display_id"],
|
|
42
|
+
name=data["name"],
|
|
43
|
+
role=data["role"],
|
|
44
|
+
created_at=parse_datetime(data["created_at"]),
|
|
45
|
+
updated_at=parse_datetime(data["updated_at"]),
|
|
46
|
+
last_used_at=optional_datetime(data.get("last_used_at")),
|
|
47
|
+
revoked_at=optional_datetime(data.get("revoked_at")),
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def account(data: dict[str, Any]) -> Account:
|
|
52
|
+
return Account(
|
|
53
|
+
account_id=data["account_id"],
|
|
54
|
+
email=data.get("email"),
|
|
55
|
+
display_name=data.get("display_name"),
|
|
56
|
+
avatar_url=data.get("avatar_url"),
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def end_user(data: dict[str, Any]) -> EndUser:
|
|
61
|
+
return EndUser(
|
|
62
|
+
id=data["id"],
|
|
63
|
+
project_id=data["project_id"],
|
|
64
|
+
email=data.get("email"),
|
|
65
|
+
display_name=data.get("display_name"),
|
|
66
|
+
avatar_url=data.get("avatar_url"),
|
|
67
|
+
email_verified=bool(data.get("email_verified")),
|
|
68
|
+
last_sign_in_at=optional_datetime(data.get("last_sign_in_at")),
|
|
69
|
+
created_at=parse_datetime(data["created_at"]),
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def storage_object(
|
|
74
|
+
data: dict[str, Any], download_url: Optional[str] = None
|
|
75
|
+
) -> StorageObject:
|
|
76
|
+
return StorageObject(
|
|
77
|
+
id=data["id"],
|
|
78
|
+
project_id=data["project_id"],
|
|
79
|
+
provider=data["provider"],
|
|
80
|
+
file_name=data["file_name"],
|
|
81
|
+
content_type=data["content_type"],
|
|
82
|
+
size_bytes=data["size_bytes"],
|
|
83
|
+
created_at=parse_datetime(data["created_at"]),
|
|
84
|
+
download_url=download_url,
|
|
85
|
+
)
|