Skip to content

Commit

Permalink
Minimal SSE clock example
Browse files Browse the repository at this point in the history
Rate limit · GitHub

Access has been restricted

You have triggered a rate limit.

Please wait a few minutes before you try again;
in some cases this may take up to an hour.

audreyfeldroy committed Aug 15, 2024
1 parent 95a711a commit c28c3f1
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions 04_sse/sse_clock.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@

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()

0 comments on commit c28c3f1

Please sign in to comment.