<p align="center"><img width="150" height="150" src="https://data-star.dev/static/images/rocket-512x512.png"></p>
# Datastar Python SDK
The `datastar-py` package provides a Python SDK for working with [Datastar](https://data-star.dev).
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:
* [Django](https://www.djangoproject.com/)
* [FastAPI](https://fastapi.tiangolo.com/)
* [FastHTML](https://fastht.ml/)
* [Litestar](https://litestar.dev/)
* [Quart](https://quart.palletsprojects.com/en/stable/)
* [Sanic](https://sanic.dev/en/)
* [Starlette](https://www.starlette.io/)
## Event Generation Helpers
To use `datastar-py`, import the SSE generator in your app and then use
it in your route handler:
```python
import asyncio
from datastar_py import ServerSentEventGenerator as SSE
from datastar_py.sse import SSE_HEADERS
from quart import Quart, make_response
from datetime import datetime
app = Quart(__name__)
# Import frontend library via Content Distribution Network, create targets for Server Sent Events
@app.route("/")
def index():
return '''
<script type="module" src="https://cdn.jsdelivr.net/gh/starfederation/datastar@main/bundles/datastar.js"></script>
<span data-on-load="@get('/updates')" id="currentTime"></span><br><span data-text="$currentTime"></div>
'''
@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
app.run()
```
The example above is for the Quart framework, and is only using the event generation helpers.
## 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.
```python
# per framework Response import, eg:
# from datastar_py.fastapi import DatastarResponse
from datastar_py import ServerSentEventGenerator as SSE
# 0 events, a 204
@app.get("zero")
def zero_event():
return DatastarResponse()
# 1 event
@app.get("one")
def one_event():
return DatastarResponse(SSE.patch_elements("<div id='mydiv'></div>"))
# 2 events
@app.get("two")
def two_event():
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)
@app.get("/updates")
async def updates():
async def _():
while True:
yield SSE.patch_elements("<div id='mydiv'></div>")
await asyncio.sleep(1)
return DatastarResponse(_())
# A long lived stream for sanic
@app.get("/updates")
async def updates(request):
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.
```python
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`
```python
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.
```python
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)
Button(data.on("click", "console.log('clicked')").debounce(1000).stop)("My Button")
# 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.
```python
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)
```
Raw data
{
"_id": null,
"home_page": null,
"name": "datastar-py",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.9",
"maintainer_email": null,
"keywords": "datastar, django, fastapi, fasthtml, flask, html, litestar, quart, sanic, starlette",
"author": null,
"author_email": "Felix Ingram <f.ingram@gmail.com>, Lucian Knock <git@lucianknock.com>, Chase Sterling <chase.sterling@gmail.com>",
"download_url": "https://files.pythonhosted.org/packages/bf/8d/3b5f8c703dc8456141c4d2841192e630ed7557dcd13de4adc3c7f3325d88/datastar_py-0.6.3.tar.gz",
"platform": null,
"description": "<p align=\"center\"><img width=\"150\" height=\"150\" src=\"https://data-star.dev/static/images/rocket-512x512.png\"></p>\n\n# Datastar Python SDK\n\nThe `datastar-py` package provides a Python SDK for working with [Datastar](https://data-star.dev).\n\nDatastar sends responses back to the browser using SSE. This allows the backend to\nsend any number of events, from zero to infinity in response to a single request.\n\n`datastar-py` has helpers for creating those responses, formatting the events,\nreading signals from the frontend, and generating the data-* HTML attributes.\n\nThe event generator can be used with any framework. There are also custom\nhelpers included for the following frameworks:\n\n* [Django](https://www.djangoproject.com/)\n* [FastAPI](https://fastapi.tiangolo.com/)\n* [FastHTML](https://fastht.ml/)\n* [Litestar](https://litestar.dev/)\n* [Quart](https://quart.palletsprojects.com/en/stable/)\n* [Sanic](https://sanic.dev/en/)\n* [Starlette](https://www.starlette.io/)\n\n## Event Generation Helpers\n\nTo use `datastar-py`, import the SSE generator in your app and then use\nit in your route handler:\n\n```python\nimport asyncio\n\nfrom datastar_py import ServerSentEventGenerator as SSE\nfrom datastar_py.sse import SSE_HEADERS\nfrom quart import Quart, make_response\nfrom datetime import datetime\n\napp = Quart(__name__)\n\n# Import frontend library via Content Distribution Network, create targets for Server Sent Events\n@app.route(\"/\")\ndef index():\n return '''\n <script type=\"module\" src=\"https://cdn.jsdelivr.net/gh/starfederation/datastar@main/bundles/datastar.js\"></script>\n <span data-on-load=\"@get('/updates')\" id=\"currentTime\"></span><br><span data-text=\"$currentTime\"></div>\n '''\n\n\n@app.route(\"/updates\")\nasync def updates():\n async def time_updates():\n while True:\n yield SSE.patch_elements(\n f\"\"\"<span id=\"currentTime\">{datetime.now().isoformat()}\"\"\"\n )\n await asyncio.sleep(1)\n yield SSE.patch_signals({\"currentTime\": f\"{datetime.now().isoformat()}\"})\n await asyncio.sleep(1)\n\n response = await make_response(time_updates(), SSE_HEADERS)\n response.timeout = None\n return response\n\n\napp.run()\n```\n\nThe example above is for the Quart framework, and is only using the event generation helpers.\n\n## Response Helpers\n\nA datastar response consists of 0..N datastar events. There are response\nclasses included to make this easy in all of the supported frameworks.\n\nThe following examples will work across all supported frameworks when the\nresponse class is imported from the appropriate framework package.\ne.g. `from datastar_py.quart import DatastarResponse` The containing functions\nare not shown here, as they will differ per framework.\n\n```python\n# per framework Response import, eg:\n# from datastar_py.fastapi import DatastarResponse\nfrom datastar_py import ServerSentEventGenerator as SSE\n\n# 0 events, a 204\n@app.get(\"zero\")\ndef zero_event():\n return DatastarResponse()\n# 1 event\n@app.get(\"one\")\ndef one_event():\n return DatastarResponse(SSE.patch_elements(\"<div id='mydiv'></div>\"))\n# 2 events\n@app.get(\"two\")\ndef two_event():\n return DatastarResponse([\n SSE.patch_elements(\"<div id='mydiv'></div>\"),\n SSE.patch_signals({\"mysignal\": \"myval\"}),\n ])\n\n# N events, a long lived stream (for all frameworks but sanic)\n\n@app.get(\"/updates\")\nasync def updates():\n async def _():\n while True:\n yield SSE.patch_elements(\"<div id='mydiv'></div>\")\n await asyncio.sleep(1)\n return DatastarResponse(_())\n\n# A long lived stream for sanic\n@app.get(\"/updates\")\nasync def updates(request):\n response = await datastar_respond(request)\n # which is just a helper for the following\n # response = await request.respond(DatastarResponse())\n while True:\n await response.send(SSE.patch_elements(\"<div id='mydiv'></div>\"))\n await asyncio.sleep(1)\n```\n\n### Response Decorator\nTo make returning a `DatastarResponse` simpler, there is a decorator\n`datastar_response` available that automatically wraps a function result in\n`DatastarResponse`. It works on async and regular functions and generator\nfunctions. The main use case is when using a generator function, as you can\navoid a second generator function inside your response function. The decorator\nworks the same for any of the supported frameworks, and should be used under\nany routing decorator from the framework.\n\n```python\nfrom datastar_py.sanic import datastar_response, ServerSentEventGenerator as SSE\n\n@app.get('/my_route')\n@datastar_response\ndef my_route(request):\n while True:\n yield SSE.patch_elements(\"<div id='mydiv'></div>\")\n await asyncio.sleep(1)\n```\n\n## Signal Helpers\nThe current state of the datastar signals is included by default in every\ndatastar request. A helper is included to load those signals for each\nframework. `read_signals`\n\n```python\nfrom datastar_py.quart import read_signals\n\n@app.route(\"/updates\")\nasync def updates():\n signals = await read_signals()\n```\n\n## Attribute Generation Helper\nDatastar allows HTML generation to be done on the backend. datastar-py includes\na helper to generate data-* attributes in your HTML with IDE completion and\ntype checking. It can be used with many different HTML generation libraries.\n\n```python\nfrom datastar_py import attribute_generator as data\n\n# htpy\nbutton(data.on(\"click\", \"console.log('clicked')\").debounce(1000).stop)[\"My Button\"]\n# FastHTML\nButton(\"My Button\", data.on(\"click\", \"console.log('clicked')\").debounce(1000).stop)\nButton(data.on(\"click\", \"console.log('clicked')\").debounce(1000).stop)(\"My Button\")\n# f-strings\nf\"<button {data.on(\"click\", \"console.log('clicked')\").debounce(1000).stop}>My Button</button>\"\n# Jinja, but no editor completion :(\n<button {{data.on(\"click\", \"console.log('clicked')\").debounce(1000).stop}}>My Button</button>\n```\n\nWhen using datastar with a different alias, you can instantiate the class yourself.\n\n```python\nfrom datastar_py.attributes import AttributeGenerator\n\ndata = AttributeGenerator(alias=\"data-star-\")\n\n# htmy (htmy will transform _ into - unless the attribute starts with _, which will be stripped)\ndata = AttributeGenerator(alias=\"_data-\")\nhtml.button(\"My Button\", **data.on(\"click\", \"console.log('clicked')\").debounce(\"1s\").stop)\n```\n",
"bugtrack_url": null,
"license": null,
"summary": "Helper functions and classes for the Datastar library (https://data-star.dev/)",
"version": "0.6.3",
"project_urls": {
"Documentation": "https://github.com/starfederation/datastar-python/blob/develop/README.md",
"GitHub": "https://github.com/starfederation/datastar-python"
},
"split_keywords": [
"datastar",
" django",
" fastapi",
" fasthtml",
" flask",
" html",
" litestar",
" quart",
" sanic",
" starlette"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "5db6efd73a95bd8103b9a1ace31eb93a3ee6be960a4389d7300ab0c429147508",
"md5": "b29ba3fc3e7b0dca91d4236846fa6c92",
"sha256": "6c42ced5229fe7e9fb54fd405e8fbd5174a9c99294d96e60dccd377829ea30a3"
},
"downloads": -1,
"filename": "datastar_py-0.6.3-py3-none-any.whl",
"has_sig": false,
"md5_digest": "b29ba3fc3e7b0dca91d4236846fa6c92",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.9",
"size": 18620,
"upload_time": "2025-07-18T19:34:54",
"upload_time_iso_8601": "2025-07-18T19:34:54.837272Z",
"url": "https://files.pythonhosted.org/packages/5d/b6/efd73a95bd8103b9a1ace31eb93a3ee6be960a4389d7300ab0c429147508/datastar_py-0.6.3-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "bf8d3b5f8c703dc8456141c4d2841192e630ed7557dcd13de4adc3c7f3325d88",
"md5": "4d03cddfefd26108c6bf1848ef6ca69a",
"sha256": "a8818d325081d8b362149a0c341952aaa97b68da30df28936f4e690962870529"
},
"downloads": -1,
"filename": "datastar_py-0.6.3.tar.gz",
"has_sig": false,
"md5_digest": "4d03cddfefd26108c6bf1848ef6ca69a",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.9",
"size": 145895,
"upload_time": "2025-07-18T19:34:55",
"upload_time_iso_8601": "2025-07-18T19:34:55.749517Z",
"url": "https://files.pythonhosted.org/packages/bf/8d/3b5f8c703dc8456141c4d2841192e630ed7557dcd13de4adc3c7f3325d88/datastar_py-0.6.3.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-07-18 19:34:55",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "starfederation",
"github_project": "datastar-python",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "datastar-py"
}