Skip to main content

Helper functions and classes for the Datastar library (https://data-star.dev/)

Project description

Datastar Python SDK

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:

Event Generation Helpers

To use datastar-py, import the SSE generator in your app and then use it in your route handler:

from datastar_py import ServerSentEventGenerator as SSE


# ... various app setup.
# The example below is for the Quart framework, and is only using the event generation helpers.

@app.route("/updates")
async def updates():
    async def time_updates():
        while True:
            yield SSE.patch_elements(
                [f"""<span id="currentTime">{datetime.now().isoformat()}"""]
            )
            await asyncio.sleep(1)
            yield SSE.patch_signals({"currentTime": f"{datetime.now().isoformat()}"})
            await asyncio.sleep(1)

    response = await make_response(time_updates(), SSE_HEADERS)
    response.timeout = None
    return response

Response Helpers

A datastar response consists of 0..N datastar events. There are response classes included to make this easy in all of the supported frameworks.

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.

from datastar_py import ServerSentEventGenerator as SSE

# 0 events, a 204
return DatastarResponse()
# 1 event
return DatastarResponse(SSE.patch_elements("<div id='mydiv'></div>"))
# 2 events
return DatastarResponse([
    SSE.patch_elements("<div id='mydiv'></div>"),
    SSE.patch_signals({"mysignal": "myval"}),
])

# N events, a long lived stream (for all frameworks but sanic)
async def updates():
    while True:
        yield SSE.patch_elements("<div id='mydiv'></div>")
        await asyncio.sleep(1)
return DatastarResponse(updates())

# A long lived stream for sanic
response = await datastar_respond(request)
# which is just a helper for the following
# response = await request.respond(DatastarResponse())
while True:
    await response.send(SSE.patch_elements("<div id='mydiv'></div>"))
    await asyncio.sleep(1)

Response Decorator

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.

from datastar_py.sanic import datastar_response, ServerSentEventGenerator as SSE

@app.get('/my_route')
@datastar_response
def my_route(request):
    while True:
        yield SSE.patch_elements("<div id='mydiv'></div>")
        await asyncio.sleep(1)

Signal Helpers

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

from datastar_py.quart import read_signals

@app.route("/updates")
async def updates():
    signals = await read_signals()

Attribute Generation Helper

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.

from datastar_py import attribute_generator as data

# htpy
button(data.on("click", "console.log('clicked')").debounce(1000).stop)["My Button"]
# FastHTML
Button("My Button", **data.on("click", "console.log('clicked')").debounce(1000).stop)
# After next release of FastHTML you don't have to unpack the datastar helpers e.g.
Button("My Button", data.on("click", "console.log('clicked')").debounce(1000).stop)
# f-strings
f"<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}}>My Button</button>

When using datastar with a different alias, you can instantiate the class yourself.

from datastar_py.attributes import AttributeGenerator

data = 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)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

datastar_py-0.6.1.tar.gz (144.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

datastar_py-0.6.1-py3-none-any.whl (18.3 kB view details)

Uploaded Python 3

File details

Details for the file datastar_py-0.6.1.tar.gz.

File metadata

  • Download URL: datastar_py-0.6.1.tar.gz
  • Upload date:
  • Size: 144.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.7.21

File hashes

Hashes for datastar_py-0.6.1.tar.gz
Algorithm Hash digest
SHA256 90adf6fc4185cfd09816dd2669feb6a668fb15b3a069b80b666579761a6cef78
MD5 c6f1b2f5e0dfccb3132a3fd9b0ea8f96
BLAKE2b-256 b79805dab949c73ade4a60e87ef422826f23d72a2021d02c69340d66dba720ff

See more details on using hashes here.

File details

Details for the file datastar_py-0.6.1-py3-none-any.whl.

File metadata

File hashes

Hashes for datastar_py-0.6.1-py3-none-any.whl
Algorithm Hash digest
SHA256 1a498d7b7930851ab9ef4ed4a69ceb25b2837bce64fc5d3c949e8cb55d969774
MD5 51ecb7cdfc21887854ec1a608f294e32
BLAKE2b-256 efd5c317c4be22b9d66bdc47973c2f4aa26ee0f0cc592454e1d86d0472c7e3de

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page