Skip to content

Commit 5c8dfdc

Browse files
vdicedicej
andcommitted
feat(sdk): add util module with collect helper func; update spin-kv example to suit
Signed-off-by: Vaughn Dice <vdice@akamai.com> Co-authored-by: Joel Dice <joel.dice@akamai.com>
1 parent b5a54d5 commit 5c8dfdc

3 files changed

Lines changed: 132 additions & 15 deletions

File tree

docs/v4/util.html

Lines changed: 103 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

examples/spin-kv/app.py

Lines changed: 3 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,19 @@
1-
from typing import TypeVar, Tuple, List
2-
from componentize_py_types import Result, Err
3-
from componentize_py_async_support.streams import StreamReader
4-
from componentize_py_async_support.futures import FutureReader
5-
from spin_sdk import http, key_value
1+
from spin_sdk import http, key_value, util
62
from spin_sdk.http import Request, Response
73
from spin_sdk.key_value import Store
84

95
class WasiHttpHandler030Rc20260315(http.Handler):
106
async def handle_request(self, request: Request) -> Response:
117
with await key_value.open_default() as a:
128
await a.set("test", bytes("hello world!", "utf-8"))
13-
print(await get_keys(a))
9+
print(await util.collect(await a.get_keys()))
1410
print(await a.exists("test"))
1511
print(await a.get("test"))
1612
await a.delete("test")
17-
print(await get_keys(a))
13+
print(await util.collect(await a.get_keys()))
1814

1915
return Response(
2016
200,
2117
{"content-type": "text/plain"},
2218
bytes("Hello from Python!", "utf-8")
2319
)
24-
25-
async def get_keys(store: Store) -> list[str]:
26-
stream, future = await store.get_keys()
27-
with stream, future:
28-
keys = []
29-
while not stream.writer_dropped:
30-
keys += await stream.read(max_count=100)
31-
return keys

src/spin_sdk/util.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
"""Module for general-purpose utility functions"""
2+
3+
from typing import TypeVar, Tuple, List
4+
from componentize_py_types import Result, Err
5+
from componentize_py_async_support.streams import StreamReader
6+
from componentize_py_async_support.futures import FutureReader
7+
8+
T = TypeVar('T')
9+
E = TypeVar('E')
10+
11+
async def collect(tuple: Tuple[StreamReader[T], FutureReader[Result[None, E]]]) -> List[T]:
12+
"""
13+
Collect all items from the StreamReader portion of the provided Tuple and return them in a List,
14+
verifying the FutureReader result upon stream completion.
15+
"""
16+
stream = tuple[0]
17+
future = tuple[1]
18+
collected = []
19+
with stream, future:
20+
while not stream.writer_dropped:
21+
collected += await stream.read(128)
22+
result = await future.read()
23+
if isinstance(result, Err):
24+
raise result
25+
else:
26+
return collected

0 commit comments

Comments
 (0)