Hot Reload Development ¶
Live Page Updates with Datastar SSE ¶
This is an efficient development pattern: establish an SSE connection from the browser to stream page updates.
When the server reloads (eg detected changes in the code), Browser automatically reconnects and receives the updated page from /stream.
This is recommended mostly for development purposes, as it comes additional considerations that you might not want to deal with in production.
Basic Setup ¶
import asyncio
from stario import Stario
from stario.datastar import Attributes, Actions
from stario.html import div, button, span, h1, html, head, body, meta, title
from stario.toys import toy_page, load_datastar
import time
app = Stario()
@app.query("/")
async def page(attr: Attributes, act: Actions):
"""Main page with Datastar SSE connection."""
return html(
head(
meta({"charset": "UTF-8"}),
title("Hot Reload Demo"),
load_datastar,
),
body(
attr.init(act.get("updates")), # Establish main SSE updates stream
),
div(
"Initial page content - change it and save to see the updates",
),
)
@app.query("/updates")
async def updates(attr: Attributes, act: Actions):
"""
Stream the page as SSE.
Yields entire page on connect and when server reloads,
client reconnects automatically and receives updated content.
"""
# Upon connection, yield the initial page
yield await page(attr, act)
while True:
# keep the connection alive
await asyncio.sleep(1)
Run with Reload ¶
By default uvicorn will try to gracefully wait for open connections to close before shutting down.
This is not what we want here, so we set --timeout-graceful-shutdown 0 to disable it.
Additionally note that in browser there will be error messages about the connection being closed - this is expected as we are not waiting for the connection to close gracefully.
# Terminal 1: Run with hot reload
uv run uvicorn app:app --reload --port 8000 --timeout-graceful-shutdown 0
# Terminal 2: Edit app.py and save - page updates instantly!
How It Works ¶
- Page Load: Browser requests
/→ server returns page with Datastar initialized - SSE Connection: On page intersection, Datastar connects to
/updates. - Stream Content: Server yields updated signals and HTML patches
- Server Reload: When you save
app.py, uvicorn reloads and SSE connection drops - Auto Reconnect: Datastar automatically reconnects to
/updates - New Content: Client receives latest page HTML with updated code
