Skip to content

Commit 0a666dd

Browse files
authored
Use runnable code in README snippets (#3)
Co-authored-by: Lucian Knock <git@lucianknock.com>
1 parent d89ee1f commit 0a666dd

1 file changed

Lines changed: 52 additions & 23 deletions

File tree

README.md

Lines changed: 52 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -27,18 +27,30 @@ To use `datastar-py`, import the SSE generator in your app and then use
2727
it in your route handler:
2828

2929
```python
30+
import asyncio
31+
3032
from datastar_py import ServerSentEventGenerator as SSE
33+
from datastar_py.sse import SSE_HEADERS
34+
from quart import Quart, make_response
35+
from datetime import datetime
36+
37+
app = Quart(__name__)
3138

39+
# Import frontend library via Content Distribution Network, create targets for Server Sent Events
40+
@app.route("/")
41+
def index():
42+
return '''
43+
<script type="module" src="https://cdn.jsdelivr.net/gh/starfederation/datastar@main/bundles/datastar.js"></script>
44+
<span data-on-load="@get('/updates')" id="currentTime"></span><br><span data-text="$currentTime"></div>
45+
'''
3246

33-
# ... various app setup.
34-
# The example below is for the Quart framework, and is only using the event generation helpers.
3547

3648
@app.route("/updates")
3749
async def updates():
3850
async def time_updates():
3951
while True:
4052
yield SSE.patch_elements(
41-
[f"""<span id="currentTime">{datetime.now().isoformat()}"""]
53+
f"""<span id="currentTime">{datetime.now().isoformat()}"""
4254
)
4355
await asyncio.sleep(1)
4456
yield SSE.patch_signals({"currentTime": f"{datetime.now().isoformat()}"})
@@ -47,8 +59,13 @@ async def updates():
4759
response = await make_response(time_updates(), SSE_HEADERS)
4860
response.timeout = None
4961
return response
62+
63+
64+
app.run()
5065
```
5166

67+
The example above is for the Quart framework, and is only using the event generation helpers.
68+
5269
## Response Helpers
5370

5471
A datastar response consists of 0..N datastar events. There are response
@@ -60,32 +77,45 @@ e.g. `from datastar_py.quart import DatastarResponse` The containing functions
6077
are not shown here, as they will differ per framework.
6178

6279
```python
80+
# per framework Response import, eg:
81+
# from datastar_py.fastapi import DatastarResponse
6382
from datastar_py import ServerSentEventGenerator as SSE
6483

6584
# 0 events, a 204
66-
return DatastarResponse()
85+
@app.get("zero")
86+
def zero_event():
87+
return DatastarResponse()
6788
# 1 event
68-
return DatastarResponse(SSE.patch_elements("<div id='mydiv'></div>"))
89+
@app.get("one")
90+
def one_event():
91+
return DatastarResponse(SSE.patch_elements("<div id='mydiv'></div>"))
6992
# 2 events
70-
return DatastarResponse([
71-
SSE.patch_elements("<div id='mydiv'></div>"),
72-
SSE.patch_signals({"mysignal": "myval"}),
73-
])
93+
@app.get("two")
94+
def two_event():
95+
return DatastarResponse([
96+
SSE.patch_elements("<div id='mydiv'></div>"),
97+
SSE.patch_signals({"mysignal": "myval"}),
98+
])
7499

75100
# N events, a long lived stream (for all frameworks but sanic)
101+
102+
@app.get("/updates")
76103
async def updates():
77-
while True:
78-
yield SSE.patch_elements("<div id='mydiv'></div>")
79-
await asyncio.sleep(1)
80-
return DatastarResponse(updates())
104+
async def _():
105+
while True:
106+
yield SSE.patch_elements("<div id='mydiv'></div>")
107+
await asyncio.sleep(1)
108+
return DatastarResponse(_())
81109

82110
# A long lived stream for sanic
83-
response = await datastar_respond(request)
84-
# which is just a helper for the following
85-
# response = await request.respond(DatastarResponse())
86-
while True:
87-
await response.send(SSE.patch_elements("<div id='mydiv'></div>"))
88-
await asyncio.sleep(1)
111+
@app.get("/updates")
112+
async def updates(request):
113+
response = await datastar_respond(request)
114+
# which is just a helper for the following
115+
# response = await request.respond(DatastarResponse())
116+
while True:
117+
await response.send(SSE.patch_elements("<div id='mydiv'></div>"))
118+
await asyncio.sleep(1)
89119
```
90120

91121
### Response Decorator
@@ -109,7 +139,7 @@ def my_route(request):
109139
```
110140

111141
## Signal Helpers
112-
The current state of the datastar signals is included by default in every
142+
The current state of the datastar signals is included by default in every
113143
datastar request. A helper is included to load those signals for each
114144
framework. `read_signals`
115145

@@ -132,9 +162,8 @@ from datastar_py import attribute_generator as data
132162
# htpy
133163
button(data.on("click", "console.log('clicked')").debounce(1000).stop)["My Button"]
134164
# FastHTML
135-
Button("My Button", **data.on("click", "console.log('clicked')").debounce(1000).stop)
136-
# After next release of FastHTML you don't have to unpack the datastar helpers e.g.
137165
Button("My Button", data.on("click", "console.log('clicked')").debounce(1000).stop)
166+
Button(data.on("click", "console.log('clicked')").debounce(1000).stop)("My Button")
138167
# f-strings
139168
f"<button {data.on("click", "console.log('clicked')").debounce(1000).stop}>My Button</button>"
140169
# Jinja, but no editor completion :(
@@ -151,4 +180,4 @@ data = AttributeGenerator(alias="data-star-")
151180
# htmy (htmy will transform _ into - unless the attribute starts with _, which will be stripped)
152181
data = AttributeGenerator(alias="_data-")
153182
html.button("My Button", **data.on("click", "console.log('clicked')").debounce("1s").stop)
154-
```
183+
```

0 commit comments

Comments
 (0)