The datastar-py package provides a Python SDK for working with Datastar.
Datastar sends responses back to the browser using SSE. This allows the backend to send any number of events, from zero to infinity in response to a single request.
datastar-py has helpers for creating those responses, formatting the events,
reading signals from the frontend, and generating the data-* HTML attributes.
The event generator can be used with any framework. There are also custom helpers included for the following frameworks:
Framework-specific helpers are kept in their own packages. e.g. datastar_py.quart
Make sure to use the helpers from the package of the framework you are using.
Here is a full example using the quart framework showing many of the features available in this package.
importasynciofromdatetimeimportdatetimefromdatastar_pyimportServerSentEventGeneratorasSSE, attribute_generatorasdatafromdatastar_py.quartimportdatastar_response, read_signalsfromquartimportQuartapp=Quart(__name__)
# Import frontend library via Content Distribution Network, create targets for Server Sent Events@app.route("/")defindex():
returnf""" <html> <head> <script type="module" src="https://cdn.jsdelivr.net/gh/starfederation/datastar@v1.0.0-RC.7/bundles/datastar.js"></script> </head> <body {data.init("@get('/updates')")}> <span id="currentTime"></span><br> <span data-text="$currentTime"></span> </body> </html> """@app.route("/updates")@datastar_responseasyncdefupdates():
# Retrieve a dictionary with the current state of the signals from the frontendsignals=awaitread_signals()
# Alternate updating an element from the backend, and updating a signal from the backendwhileTrue:
yieldSSE.patch_elements(
f"""<span id="currentTime">{datetime.now().isoformat()}"""
)
awaitasyncio.sleep(1)
yieldSSE.patch_signals({"currentTime": f"{datetime.now().isoformat()}"})
awaitasyncio.sleep(1)
app.run()Starting examples for each framework can be found in the examples directory.
This helper is used to generate the actual events that are sent over SSE. They are just text blobs that can be sent using any framework. These can even be used by frameworks not directly supported in this library if you set up the headers of the SSE response yourself.
A datastar response consists of 0..N datastar events. There are response
classes included to make this easy in all of the supported frameworks.
Each framework also exposes a @datastar_response decorator that will wrap
return values (including generators) into the right response class while
preserving sync handlers as sync so frameworks can keep them in their
threadpools.
The following examples will work across all supported frameworks when the
response class is imported from the appropriate framework package.
e.g. from datastar_py.quart import DatastarResponse The containing functions
are not shown here, as they will differ per framework.
# per framework Response import. (Replace 'fastapi' with your framework.) e.g.:# from datastar_py.fastapi import DatastarResponsefromdatastar_pyimportServerSentEventGeneratorasSSE# 0 events, a 204@app.get("zero")defzero_event():
returnDatastarResponse()
# 1 event@app.get("one")defone_event():
returnDatastarResponse(SSE.patch_elements("<div id='mydiv'></div>"))
# 2 events@app.get("two")deftwo_event():
returnDatastarResponse([
SSE.patch_elements("<div id='mydiv'></div>"),
SSE.patch_signals({"mysignal": "myval"}),
])
# N events, a long lived stream (for all frameworks but sanic)@app.get("/updates")asyncdefupdates():
asyncdef_():
whileTrue:
yieldSSE.patch_elements("<div id='mydiv'></div>")
awaitasyncio.sleep(1)
returnDatastarResponse(_())
# A long lived stream for sanic@app.get("/updates")asyncdefupdates(request):
response=awaitdatastar_respond(request)
# which is just a helper for the following# response = await request.respond(DatastarResponse())whileTrue:
awaitresponse.send(SSE.patch_elements("<div id='mydiv'></div>"))
awaitasyncio.sleep(1)To make returning a DatastarResponse simpler, there is a decorator
datastar_response available that automatically wraps a function result in
DatastarResponse. It works on async and regular functions and generator
functions. The main use case is when using a generator function, as you can
avoid a second generator function inside your response function. The decorator
works the same for any of the supported frameworks, and should be used under
any routing decorator from the framework.
# Import the decorator from the package specific to your frameworkfromdatastar_py.sanicimportdatastar_response, ServerSentEventGeneratorasSSE@app.get('/my_route')@datastar_responseasyncdefmy_route(request):
whileTrue:
yieldSSE.patch_elements("<div id='mydiv'></div>")
awaitasyncio.sleep(1)The current state of the datastar signals is included by default in every
datastar request. A helper is included to load those signals for each
framework. read_signals. The usage varies per framework so check the
signature for your framework. You usually need to pass the request in.
fromdatastar_py.quartimportread_signals@app.route("/updates")asyncdefupdates():
signals=awaitread_signals()Datastar allows HTML generation to be done on the backend. datastar-py includes a helper to generate data-* attributes in your HTML with IDE completion and type checking. It can be used with many different HTML generation libraries.
fromdatastar_pyimportattribute_generatorasdata# htpybutton(data.on("click", "console.log('clicked')").debounce(1000).stop)["My Button"]
# FastHTMLButton("My Button", data.on("click", "console.log('clicked')").debounce(1000).stop)
Button(data.on("click", "console.log('clicked')").debounce(1000).stop)("My Button")
# f-stringsf"<button {data.on("click", "console.log('clicked')").debounce(1000).stop}>My Button</button>"# Jinja, but no editor completion :(<button {{data.on("click", "console.log('clicked')").debounce(1000).stop}}>MyButton</button>When using datastar with a different alias, you can instantiate the class yourself.
fromdatastar_py.attributesimportAttributeGeneratordata=AttributeGenerator(alias="data-star-")
# htmy (htmy will transform _ into - unless the attribute starts with _, which will be stripped)data=AttributeGenerator(alias="_data-")
html.button("My Button", **data.on("click", "console.log('clicked')").debounce("1s").stop)