1
1
import asyncio
2
2
from datetime import datetime
3
3
4
+ import uvicorn
4
5
from fastapi import FastAPI
5
6
from fastapi .responses import HTMLResponse
6
7
7
- from datastar_py .fastapi import DatastarStreamingResponse
8
+ from datastar_py .fastapi import DatastarStreamingResponse , ServerSentEventGenerator
9
+ from datastar_py .starlette import sse_generator
8
10
9
11
app = FastAPI ()
10
12
15
17
<head>
16
18
<title>DATASTAR on FastAPI</title>
17
19
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
18
- <script type="module" src="https://cdn.jsdelivr.net/gh/starfederation/datastar/bundles/datastar.js"></script>
20
+ <script type="module" src="https://cdn.jsdelivr.net/gh/starfederation/datastar@v1.0.0-beta.11 /bundles/datastar.js"></script>
19
21
<style>
20
22
html, body { height: 100%; width: 100%; }
21
23
body { background-image: linear-gradient(to right bottom, oklch(0.424958 0.052808 253.972015), oklch(0.189627 0.038744 264.832977)); }
29
31
<div class="container">
30
32
<div
31
33
class="time"
32
- data-on-load="@get('/updates ')"
34
+ data-on-load="@get('/updates3 ')"
33
35
>
34
36
Current time from fragment: <span id="currentTime">CURRENT_TIME</span>
35
37
</div>
@@ -53,14 +55,43 @@ async def read_root():
53
55
54
56
async def time_updates ():
55
57
while True :
56
- yield DatastarStreamingResponse .merge_fragments (
58
+ yield ServerSentEventGenerator .merge_fragments (
57
59
[f"""<span id="currentTime">{ datetime .now ().isoformat ()} """ ]
58
60
)
59
61
await asyncio .sleep (1 )
60
- yield DatastarStreamingResponse .merge_signals ({"currentTime" : f"{ datetime .now ().isoformat ()} " })
62
+ yield ServerSentEventGenerator .merge_signals ({"currentTime" : f"{ datetime .now ().isoformat ()} " })
61
63
await asyncio .sleep (1 )
62
64
63
65
64
66
@app .get ("/updates" )
65
67
async def updates ():
66
68
return DatastarStreamingResponse (time_updates ())
69
+
70
+
71
+ # This is identical to the /updates endpoint, but uses a convenience decorator
72
+ @app .get ("/updates2" )
73
+ @sse_generator
74
+ async def updates2 ():
75
+ while True :
76
+ yield ServerSentEventGenerator .merge_fragments (
77
+ [f"""<span id="currentTime">{ datetime .now ().isoformat ()} """ ]
78
+ )
79
+ await asyncio .sleep (1 )
80
+ yield ServerSentEventGenerator .merge_signals ({"currentTime" : f"{ datetime .now ().isoformat ()} " })
81
+ await asyncio .sleep (1 )
82
+
83
+
84
+ # This is also identical, but yielding lists automaticall calls merge_fragments
85
+ # and dicts automaticall calls merge_signals
86
+ @app .get ("/updates3" )
87
+ @sse_generator
88
+ async def updates3 ():
89
+ while True :
90
+ yield [f"""<span id="currentTime">{ datetime .now ().isoformat ()} """ ]
91
+ await asyncio .sleep (1 )
92
+ yield {"currentTime" : f"{ datetime .now ().isoformat ()} " }
93
+ await asyncio .sleep (1 )
94
+
95
+
96
+ if __name__ == '__main__' :
97
+ uvicorn .run (app )
0 commit comments