interlude-sdk 0.2.0__tar.gz → 0.4.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.
Files changed (24) hide show
  1. {interlude_sdk-0.2.0 → interlude_sdk-0.4.0}/PKG-INFO +23 -2
  2. {interlude_sdk-0.2.0 → interlude_sdk-0.4.0}/README.md +22 -1
  3. {interlude_sdk-0.2.0 → interlude_sdk-0.4.0}/pyproject.toml +1 -1
  4. {interlude_sdk-0.2.0 → interlude_sdk-0.4.0}/src/interlude/__init__.py +6 -3
  5. {interlude_sdk-0.2.0 → interlude_sdk-0.4.0}/src/interlude/client.py +18 -7
  6. {interlude_sdk-0.2.0 → interlude_sdk-0.4.0}/src/interlude/table.py +78 -2
  7. {interlude_sdk-0.2.0 → interlude_sdk-0.4.0}/src/interlude_sdk.egg-info/PKG-INFO +23 -2
  8. {interlude_sdk-0.2.0 → interlude_sdk-0.4.0}/tests/test_end_user.py +20 -0
  9. {interlude_sdk-0.2.0 → interlude_sdk-0.4.0}/tests/test_table.py +58 -0
  10. {interlude_sdk-0.2.0 → interlude_sdk-0.4.0}/setup.cfg +0 -0
  11. {interlude_sdk-0.2.0 → interlude_sdk-0.4.0}/src/interlude/_http.py +0 -0
  12. {interlude_sdk-0.2.0 → interlude_sdk-0.4.0}/src/interlude/_parse.py +0 -0
  13. {interlude_sdk-0.2.0 → interlude_sdk-0.4.0}/src/interlude/account.py +0 -0
  14. {interlude_sdk-0.2.0 → interlude_sdk-0.4.0}/src/interlude/errors.py +0 -0
  15. {interlude_sdk-0.2.0 → interlude_sdk-0.4.0}/src/interlude/models.py +0 -0
  16. {interlude_sdk-0.2.0 → interlude_sdk-0.4.0}/src/interlude/storage.py +0 -0
  17. {interlude_sdk-0.2.0 → interlude_sdk-0.4.0}/src/interlude_sdk.egg-info/SOURCES.txt +0 -0
  18. {interlude_sdk-0.2.0 → interlude_sdk-0.4.0}/src/interlude_sdk.egg-info/dependency_links.txt +0 -0
  19. {interlude_sdk-0.2.0 → interlude_sdk-0.4.0}/src/interlude_sdk.egg-info/requires.txt +0 -0
  20. {interlude_sdk-0.2.0 → interlude_sdk-0.4.0}/src/interlude_sdk.egg-info/top_level.txt +0 -0
  21. {interlude_sdk-0.2.0 → interlude_sdk-0.4.0}/tests/test_account_session.py +0 -0
  22. {interlude_sdk-0.2.0 → interlude_sdk-0.4.0}/tests/test_client_auth.py +0 -0
  23. {interlude_sdk-0.2.0 → interlude_sdk-0.4.0}/tests/test_integration.py +0 -0
  24. {interlude_sdk-0.2.0 → interlude_sdk-0.4.0}/tests/test_storage.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: interlude-sdk
3
- Version: 0.2.0
3
+ Version: 0.4.0
4
4
  Summary: Official Python SDK for Interlude: tables, storage, end users and projects
5
5
  License: MIT
6
6
  Project-URL: Homepage, https://useinterlude.com
@@ -28,6 +28,27 @@ pip install interlude-sdk
28
28
 
29
29
  Package name `interlude-sdk`; import name `interlude`. Python 3.10+.
30
30
 
31
+ ## Tables
32
+
33
+ Once, from a setup script. Safe to run again: it adds what is missing and
34
+ leaves the rest alone.
35
+
36
+ ```python
37
+ client.table("todos").create({
38
+ "owner_id": {"type": "uuid", "nullable": False},
39
+ "title": {"type": "text", "nullable": False},
40
+ "done": {"type": "boolean", "nullable": False, "default": False},
41
+ "note": "text",
42
+ })
43
+
44
+ # Which rows your app's users may touch. Needs the owner's account session.
45
+ owner = Client(project_id="proj_123")
46
+ owner.account.sign_in(email, password)
47
+ owner.table("todos").set_access(
48
+ owner_column="owner_id", select="owner", insert="owner", update="owner", delete="owner"
49
+ )
50
+ ```
51
+
31
52
  ## Rows, as your server
32
53
 
33
54
  ```python
@@ -82,7 +103,7 @@ client = Client(
82
103
  publishable_key="il_pk_v1_...",
83
104
  )
84
105
 
85
- user = client.auth.get_user(token) # who sent this request? 401 if the token is bad
106
+ user = client.auth.get_user(request.headers.get("authorization")) # who sent this request? 401 if the token is bad
86
107
 
87
108
  # Read and write rows *as that user*: the table's access rules apply, and the
88
109
  # API key is not sent.
@@ -8,6 +8,27 @@ pip install interlude-sdk
8
8
 
9
9
  Package name `interlude-sdk`; import name `interlude`. Python 3.10+.
10
10
 
11
+ ## Tables
12
+
13
+ Once, from a setup script. Safe to run again: it adds what is missing and
14
+ leaves the rest alone.
15
+
16
+ ```python
17
+ client.table("todos").create({
18
+ "owner_id": {"type": "uuid", "nullable": False},
19
+ "title": {"type": "text", "nullable": False},
20
+ "done": {"type": "boolean", "nullable": False, "default": False},
21
+ "note": "text",
22
+ })
23
+
24
+ # Which rows your app's users may touch. Needs the owner's account session.
25
+ owner = Client(project_id="proj_123")
26
+ owner.account.sign_in(email, password)
27
+ owner.table("todos").set_access(
28
+ owner_column="owner_id", select="owner", insert="owner", update="owner", delete="owner"
29
+ )
30
+ ```
31
+
11
32
  ## Rows, as your server
12
33
 
13
34
  ```python
@@ -62,7 +83,7 @@ client = Client(
62
83
  publishable_key="il_pk_v1_...",
63
84
  )
64
85
 
65
- user = client.auth.get_user(token) # who sent this request? 401 if the token is bad
86
+ user = client.auth.get_user(request.headers.get("authorization")) # who sent this request? 401 if the token is bad
66
87
 
67
88
  # Read and write rows *as that user*: the table's access rules apply, and the
68
89
  # API key is not sent.
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "interlude-sdk"
7
- version = "0.2.0"
7
+ version = "0.4.0"
8
8
  description = "Official Python SDK for Interlude: tables, storage, end users and projects"
9
9
  readme = "README.md"
10
10
  license = {text = "MIT"}
@@ -7,7 +7,7 @@ Official Python client library for the Interlude BaaS platform.
7
7
  from __future__ import annotations
8
8
 
9
9
  from .account import AccountClient
10
- from .client import Client, EndUserAuth, UserScope
10
+ from .client import DEFAULT_BASE_URL, Client, EndUserAuth, UserScope
11
11
  from .errors import ClientError, InterludeError
12
12
  from .models import (
13
13
  Account,
@@ -20,15 +20,18 @@ from .models import (
20
20
  SummaryGroup,
21
21
  )
22
22
  from .storage import StorageClient
23
- from .table import TableClient
23
+ from .table import Access, ColumnSpec, TableClient
24
24
 
25
- __version__ = "0.2.0"
25
+ __version__ = "0.4.0"
26
26
 
27
27
  __all__ = [
28
+ "Access",
28
29
  "Account",
29
30
  "AccountClient",
30
31
  "Client",
31
32
  "ClientError",
33
+ "ColumnSpec",
34
+ "DEFAULT_BASE_URL",
32
35
  "EndUser",
33
36
  "EndUserAuth",
34
37
  "Filter",
@@ -2,6 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import re
5
6
  from typing import Any, Optional
6
7
 
7
8
  import httpx
@@ -118,16 +119,16 @@ class Client:
118
119
  """Your app's users: check who an access token belongs to."""
119
120
  return EndUserAuth(self)
120
121
 
121
- def as_user(self, access_token: str) -> "UserScope":
122
+ def as_user(self, access_token: Optional[str]) -> "UserScope":
122
123
  """Acts as one of your app's users, with the access token they sent
123
- your server.
124
+ your server (or the request's whole ``Authorization`` header).
124
125
 
125
126
  Requests carry their token and the publishable key, never the API
126
127
  key, so the table's access rules apply exactly as they would to that
127
128
  user's own app. Use this rather than the API key whenever a request is
128
129
  made on a user's behalf.
129
130
  """
130
- if not access_token:
131
+ if not _bare_token(access_token):
131
132
  raise InterludeError("access_token_required", "an end-user access token is required", 0)
132
133
  return UserScope(self, access_token)
133
134
 
@@ -186,23 +187,33 @@ class Client:
186
187
  return self._publishable_key
187
188
 
188
189
 
190
+ _BEARER = re.compile(r"^\s*bearer(\s+|$)", re.IGNORECASE)
191
+
192
+
193
+ def _bare_token(credential: Optional[str]) -> str:
194
+ """A token from either the token itself or an ``Authorization`` header."""
195
+ return _BEARER.sub("", credential or "").strip()
196
+
197
+
189
198
  class EndUserAuth:
190
199
  """Your app's users, as seen from your server."""
191
200
 
192
201
  def __init__(self, client: Client) -> None:
193
202
  self._client = client
194
203
 
195
- def get_user(self, access_token: str) -> EndUser:
204
+ def get_user(self, access_token: Optional[str]) -> EndUser:
196
205
  """The user an access token belongs to.
197
206
 
198
207
  This is how your server learns who sent a request: the app sends its
199
208
  user's token, and this asks Interlude whether the token is valid and
200
- whose it is. An invalid or expired token raises
209
+ whose it is. Pass the token, or the request's whole ``Authorization``
210
+ header; ``Bearer`` is stripped. An invalid or expired token raises
201
211
  :class:`InterludeError` with ``status_code`` 401.
202
212
  """
203
213
  client = self._client
204
214
  project_id = client._require_project_id("auth")
205
215
  publishable_key = client._require_publishable_key("auth")
216
+ access_token = _bare_token(access_token)
206
217
  if not access_token:
207
218
  raise InterludeError("access_token_required", "an end-user access token is required", 0)
208
219
  data, _ = client._transport.send(
@@ -217,9 +228,9 @@ class EndUserAuth:
217
228
  class UserScope:
218
229
  """The data plane as one of your app's users. From :meth:`Client.as_user`."""
219
230
 
220
- def __init__(self, client: Client, access_token: str) -> None:
231
+ def __init__(self, client: Client, access_token: Optional[str]) -> None:
221
232
  self._client = client
222
- self._access_token = access_token
233
+ self._access_token = _bare_token(access_token)
223
234
 
224
235
  def table(self, name: str) -> TableClient:
225
236
  """A table's rows, as this user, within the table's access rules."""
@@ -2,12 +2,21 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from typing import Any, Callable, Iterable, Literal, Optional
5
+ from typing import Any, Callable, Iterable, Literal, Mapping, Optional, Union
6
6
 
7
7
  from ._http import Credentials, Transport, segment
8
+ from .errors import InterludeError
8
9
  from .models import Filter, FilterLike, Measure, Page, Row, Summary, SummaryGroup
9
10
 
10
11
 
12
+ Access = Literal["owner", "public", "none"]
13
+ """Who an access rule lets through. See :meth:`TableClient.set_access`."""
14
+
15
+ ColumnSpec = Union[str, Mapping[str, Any]]
16
+ """A column for :meth:`TableClient.create`: its type (``"text"``), or a dict
17
+ with ``type`` and any of ``nullable``, ``unique`` and ``default``."""
18
+
19
+
11
20
  class TableClient:
12
21
  """Reads and writes one table's rows.
13
22
 
@@ -25,7 +34,74 @@ class TableClient:
25
34
  ) -> None:
26
35
  self._transport = transport
27
36
  self._credentials = credentials
28
- self._path = f"/projects/{segment(project_id)}/tables/{segment(name)}/rows"
37
+ self._name = name
38
+ self._tables = f"/projects/{segment(project_id)}/tables"
39
+ self._path = f"{self._tables}/{segment(name)}/rows"
40
+
41
+ def create(self, columns: Optional[Mapping[str, ColumnSpec]] = None) -> list[str]:
42
+ """Creates this table and any of ``columns`` it lacks. What already
43
+ exists is left as it is, so a setup script can run any number of
44
+ times. Needs the API key. Returns the columns added this time.
45
+
46
+ .. code-block:: python
47
+
48
+ client.table("events").create({
49
+ "title": {"type": "text", "nullable": False},
50
+ "slug": {"type": "text", "nullable": False, "unique": True},
51
+ "venue": "text",
52
+ })
53
+
54
+ A column is its type, or a dict with ``type`` and any of
55
+ ``nullable`` (default True), ``unique`` and ``default``.
56
+ """
57
+ self._ignoring("table_already_exists", self._tables, {"name": self._name})
58
+ added = []
59
+ for name, spec in (columns or {}).items():
60
+ column = {"type": spec} if isinstance(spec, str) else dict(spec)
61
+ if "default" in column and column["default"] is not None:
62
+ column["default"] = _format_value(column["default"])
63
+ body = {"name": name, **{k: v for k, v in column.items() if v is not None}}
64
+ if self._ignoring("column_already_exists", f"{self._tables}/{segment(self._name)}/columns", body):
65
+ added.append(name)
66
+ return added
67
+
68
+ def set_access(
69
+ self,
70
+ *,
71
+ select: Access,
72
+ insert: Access,
73
+ update: Access,
74
+ delete: Access,
75
+ owner_column: Optional[str] = None,
76
+ ) -> None:
77
+ """Sets which rows your app's users may read and write. A new table
78
+ lets them do nothing until this is set. Needs the project owner's
79
+ account session (``client.account.sign_in``), not the API key.
80
+
81
+ Each rule is ``"owner"`` (rows whose ``owner_column`` is the user's
82
+ id), ``"public"`` (``select`` only: anyone) or ``"none"``.
83
+ """
84
+ self._transport.send_as(
85
+ self._credentials(),
86
+ "PUT",
87
+ f"{self._tables}/{segment(self._name)}/access",
88
+ body={
89
+ "owner_column": owner_column or "",
90
+ "select": select,
91
+ "insert": insert,
92
+ "update": update,
93
+ "delete": delete,
94
+ },
95
+ )
96
+
97
+ def _ignoring(self, code: str, path: str, body: Any) -> bool:
98
+ try:
99
+ self._transport.send_as(self._credentials(), "POST", path, body=body)
100
+ return True
101
+ except InterludeError as err:
102
+ if err.code == code:
103
+ return False
104
+ raise
29
105
 
30
106
  def list(
31
107
  self,
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: interlude-sdk
3
- Version: 0.2.0
3
+ Version: 0.4.0
4
4
  Summary: Official Python SDK for Interlude: tables, storage, end users and projects
5
5
  License: MIT
6
6
  Project-URL: Homepage, https://useinterlude.com
@@ -28,6 +28,27 @@ pip install interlude-sdk
28
28
 
29
29
  Package name `interlude-sdk`; import name `interlude`. Python 3.10+.
30
30
 
31
+ ## Tables
32
+
33
+ Once, from a setup script. Safe to run again: it adds what is missing and
34
+ leaves the rest alone.
35
+
36
+ ```python
37
+ client.table("todos").create({
38
+ "owner_id": {"type": "uuid", "nullable": False},
39
+ "title": {"type": "text", "nullable": False},
40
+ "done": {"type": "boolean", "nullable": False, "default": False},
41
+ "note": "text",
42
+ })
43
+
44
+ # Which rows your app's users may touch. Needs the owner's account session.
45
+ owner = Client(project_id="proj_123")
46
+ owner.account.sign_in(email, password)
47
+ owner.table("todos").set_access(
48
+ owner_column="owner_id", select="owner", insert="owner", update="owner", delete="owner"
49
+ )
50
+ ```
51
+
31
52
  ## Rows, as your server
32
53
 
33
54
  ```python
@@ -82,7 +103,7 @@ client = Client(
82
103
  publishable_key="il_pk_v1_...",
83
104
  )
84
105
 
85
- user = client.auth.get_user(token) # who sent this request? 401 if the token is bad
106
+ user = client.auth.get_user(request.headers.get("authorization")) # who sent this request? 401 if the token is bad
86
107
 
87
108
  # Read and write rows *as that user*: the table's access rules apply, and the
88
109
  # API key is not sent.
@@ -70,3 +70,23 @@ def test_keys_in_the_wrong_place_are_refused(options, mistake):
70
70
  with pytest.raises(ValueError) as excinfo:
71
71
  build_client(Recorder(ok(None)), **options)
72
72
  assert mistake in str(excinfo.value)
73
+
74
+
75
+ @pytest.mark.parametrize("header", ["Bearer user.jwt.token", "bearer user.jwt.token ", "user.jwt.token"])
76
+ def test_get_user_takes_the_authorization_header_as_it_arrives(header):
77
+ rec = Recorder(ok(USER))
78
+
79
+ client(rec).auth.get_user(header)
80
+
81
+ assert rec.last.headers["Authorization"] == "Bearer user.jwt.token"
82
+
83
+
84
+ @pytest.mark.parametrize("missing", [None, "", "Bearer ", " "])
85
+ def test_get_user_without_a_token_is_refused_before_sending(missing):
86
+ rec = Recorder(ok(USER))
87
+
88
+ with pytest.raises(InterludeError) as err:
89
+ client(rec).auth.get_user(missing)
90
+
91
+ assert err.value.code == "access_token_required"
92
+ assert rec.requests == []
@@ -192,3 +192,61 @@ def httpx_no_content():
192
192
  import httpx
193
193
 
194
194
  return httpx.Response(204)
195
+
196
+
197
+ TABLES = "/projects/proj_1/tables"
198
+ COLUMNS = "/projects/proj_1/tables/events/columns"
199
+
200
+
201
+ def test_create_makes_the_table_then_each_column():
202
+ rec = Recorder(ok({}, status=201))
203
+
204
+ added = server(rec).table("events").create({
205
+ "title": {"type": "text", "nullable": False},
206
+ "capacity": {"type": "integer", "default": 0},
207
+ "open": {"type": "boolean", "default": True},
208
+ "venue": "text",
209
+ })
210
+
211
+ assert added == ["title", "capacity", "open", "venue"]
212
+ assert [r.url.path for r in rec.requests] == [TABLES] + [COLUMNS] * 4
213
+ assert all(r.headers["X-API-Key"] == API_KEY for r in rec.requests)
214
+ bodies = [json.loads(r.content) for r in rec.requests]
215
+ assert bodies[0] == {"name": "events"}
216
+ assert bodies[1] == {"name": "title", "type": "text", "nullable": False}
217
+ assert bodies[2] == {"name": "capacity", "type": "integer", "default": "0"}
218
+ assert bodies[3] == {"name": "open", "type": "boolean", "default": "true"}
219
+ assert bodies[4] == {"name": "venue", "type": "text"}
220
+
221
+
222
+ def test_create_leaves_what_exists_alone():
223
+ rec = Recorder(
224
+ fail(409, "table_already_exists"),
225
+ fail(409, "column_already_exists"),
226
+ ok({}, status=201),
227
+ )
228
+
229
+ assert server(rec).table("events").create({"title": "text", "venue": "text"}) == ["venue"]
230
+
231
+
232
+ def test_create_surfaces_any_other_failure():
233
+ rec = Recorder(ok({}, status=201), fail(400, "column_type_unsupported"))
234
+
235
+ with pytest.raises(InterludeError) as err:
236
+ server(rec).table("events").create({"bad": "nope"})
237
+
238
+ assert err.value.code == "column_type_unsupported"
239
+
240
+
241
+ def test_set_access_puts_all_four_rules():
242
+ rec = Recorder(ok({}))
243
+
244
+ server(rec).table("todos").set_access(
245
+ owner_column="owner_id", select="owner", insert="owner", update="owner", delete="none"
246
+ )
247
+
248
+ assert rec.last.method == "PUT"
249
+ assert rec.last.url.path == "/projects/proj_1/tables/todos/access"
250
+ assert json.loads(rec.last.content) == {
251
+ "owner_column": "owner_id", "select": "owner", "insert": "owner", "update": "owner", "delete": "none",
252
+ }
File without changes