Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add simple sse example #293

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions examples/sse_clock.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import asyncio
from datetime import datetime
from fasthtml.common import *
from starlette.responses import StreamingResponse

sselink = Script(src="https://unpkg.com/htmx-ext-sse@2.2.1/sse.js")
app, rt = fast_app(hdrs=(sselink,))

@rt("/")
def get():
return Titled("SSE Clock",
P("XX:XX", sse_swap="TimeUpdateEvent",
hx_ext="sse", sse_connect="/time-sender"))

async def time_generator():
while True:
yield f"""event: TimeUpdateEvent\ndata: {to_xml(P(datetime.now().strftime('%H:%M:%S'), sse_swap="TimeUpdateEvent"))}\n\n"""
await asyncio.sleep(1)

@rt("/time-sender")
async def get():
"Send time to all connected clients every second"
return StreamingResponse(time_generator(), media_type="text/event-stream")

serve()
Loading