### Install Dependencies and Run Example with pip Source: https://github.com/starfederation/datastar-python/blob/develop/examples/README.md Alternative method to run examples using pip. Create a virtual environment, activate it, install dependencies, and then run the script. ```sh python -m venv .venv source .venv/bin/activate # On Windows: .venv\Scripts\activate pip install datastar-py python ``` -------------------------------- ### Run FastAPI Example with uv Source: https://github.com/starfederation/datastar-python/blob/develop/examples/README.md Use uv to run the FastAPI example. Ensure you are in the 'examples/fastapi' directory. ```sh uv run app.py ``` -------------------------------- ### Install Datastar-Python Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/README.md Use pip to install the datastar-python package. ```bash pip install datastar-py ``` -------------------------------- ### Run FastHTML Example with uv Source: https://github.com/starfederation/datastar-python/blob/develop/examples/README.md Use uv to run the FastHTML example. Ensure you are in the 'examples/fasthtml' directory. ```sh uv run simple.py ``` -------------------------------- ### Full Example with Quart Framework Source: https://github.com/starfederation/datastar-python/blob/develop/README.md This snippet demonstrates a complete example using the Quart framework to serve Datastar SSE. It includes setting up the web server, defining the HTML structure with Datastar initialization, and creating an endpoint that continuously sends SSE updates for patching elements and signals. ```python import asyncio from datetime import datetime from datastar_py import ServerSentEventGenerator as SSE, attribute_generator as data from datastar_py.quart import datastar_response, read_signals from quart import Quart app = Quart(__name__) # Import frontend library via Content Distribution Network, create targets for Server Sent Events @app.route("/") def index(): return f"""
" @app.route("/updates") @datastar_response async def updates(): # Retrieve a dictionary with the current state of the signals from the frontend signals = await read_signals() # Alternate updating an element from the backend, and updating a signal from the backend while True: yield SSE.patch_elements( f"{datetime.now().isoformat()}" ) await asyncio.sleep(1) yield SSE.patch_signals({"currentTime": f"{datetime.now().isoformat()}"}) await asyncio.sleep(1) app.run() ``` -------------------------------- ### FastAPI Example with datastar_response Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/api-reference/framework-responses.md Demonstrates how to use the datastar_response decorator with FastAPI to stream Server-Sent Events. Ensure asyncio and time are imported for this example. ```python from fastapi import FastAPI from datastar_py.fastapi import datastar_response, ServerSentEventGenerator as SSE app = FastAPI() @app.get("/updates") @datastar_response async def updates(): while True: yield SSE.patch_signals({"timestamp": time.time()}) await asyncio.sleep(1) ``` -------------------------------- ### DatastarEvent Usage Example Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/types.md Demonstrates how to create and print a DatastarEvent using the ServerSentEventGenerator.patch_signals method. ```python from datastar_py import ServerSentEventGenerator as SSE event: DatastarEvent = SSE.patch_signals({"count": 1}) print(event) # prints: "event: datastar-patch-signals\ndata: signals {\"count\": 1}\n\n" ``` -------------------------------- ### Quart Example with datastar_response Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/api-reference/framework-responses.md Illustrates using the datastar_response decorator within a Quart application to stream Server-Sent Events. This example defines an inner generator function to produce events. ```python from quart import Quart from datastar_py.quart import datastar_response, ServerSentEventGenerator as SSE app = Quart(__name__) @app.route("/stream") @datastar_response async def stream(): async def generator(): for i in range(10): yield SSE.patch_elements(f"
Item {i}
") await asyncio.sleep(1) return generator() ``` -------------------------------- ### FastHTML DatastarResponse Example Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/api-reference/framework-responses.md Provides an example of returning a DatastarResponse from a FastHTML route, sending a Server-Sent Event with a 'count' of 1. ```python from fasthtml.common import * from datastar_py.fasthtml import DatastarResponse, ServerSentEventGenerator as SSE app, rt = fast_app() @rt("/stream") async def stream(): return DatastarResponse(SSE.patch_signals({"count": 1})) ``` -------------------------------- ### Quart SSE Streaming Example Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/api-reference/framework-responses.md Demonstrates how to use `DatastarResponse` to stream events from a generator in a Quart application, suitable for infinite streams. ```python from quart import Quart from datastar_py.quart import DatastarResponse, ServerSentEventGenerator as SSE app = Quart(__name__) @app.route("/stream") async def stream(): async def event_stream(): while True: yield SSE.patch_signals({"time": now()}) await asyncio.sleep(1) return DatastarResponse(event_stream()) ``` -------------------------------- ### FastAPI with Dependencies Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/examples.md Example of using Datastar Python with FastAPI, leveraging dependencies for signal reading and response generation. ```python from typing import Annotated from fastapi import FastAPI, Depends from datastar_py.fastapi import ReadSignals, DatastarResponse app = FastAPI() @app.post("/action") async def action(signals: ReadSignals): if signals: return DatastarResponse(SSE.patch_signals({"result": signals.get("count", 0) * 2})) return DatastarResponse() ``` -------------------------------- ### Django SSE Streaming Example Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/api-reference/framework-responses.md Demonstrates how to use `DatastarResponse` to stream events from a generator in a Django view. ```python from django.http import StreamingHttpResponse from datastar_py.django import DatastarResponse, ServerSentEventGenerator as SSE def stream_view(request): def event_generator(): for i in range(10): yield SSE.patch_signals({"count": i}) return DatastarResponse(event_generator()) ``` -------------------------------- ### Litestar DatastarResponse Example Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/api-reference/framework-responses.md Demonstrates how to return a DatastarResponse from a Litestar route handler, sending a Server-Sent Event with a 'hello' message. ```python from litestar import Litestar, get from datastar_py.litestar import DatastarResponse, ServerSentEventGenerator as SSE @get("/stream") async def stream() -> DatastarResponse: return DatastarResponse(SSE.patch_signals({"msg": "hello"})) ``` -------------------------------- ### Run Django Development Server with Daphne (ASGI) Source: https://github.com/starfederation/datastar-python/blob/develop/examples/django/README.md This command starts the Django development server using Daphne, the recommended ASGI server for Datastar. Access the demo at http://127.0.0.1:8000/. ```bash uv run manage.py runserver ``` -------------------------------- ### Sanic Example with datastar_response Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/api-reference/framework-responses.md Provides an example of integrating the datastar_response decorator into a Sanic application for streaming Server-Sent Events. It uses an inner async generator to yield events. ```python from sanic import Sanic from datastar_py.sanic import datastar_response, ServerSentEventGenerator as SSE app = Sanic("app") @app.route("/stream") @datastar_response def stream(request): async def generator(): for i in range(5): yield SSE.patch_signals({"progress": i * 20}) await asyncio.sleep(1) return generator() ``` -------------------------------- ### FastAPI SSE Streaming Examples Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/api-reference/framework-responses.md Demonstrates how to use `DatastarResponse` to stream single events, multiple events, or generated events in a FastAPI application. ```python from fastapi import FastAPI from datastar_py.fastapi import DatastarResponse, ServerSentEventGenerator as SSE app = FastAPI() @app.get("/stream") async def stream(): return DatastarResponse(SSE.patch_signals({"count": 42})) @app.get("/stream-multiple") async def stream_multiple(): return DatastarResponse([ SSE.patch_signals({"status": "loading"}), SSE.patch_elements("
Content
"), ]) @app.get("/stream-generated") async def stream_generated(): async def event_generator(): for i in range(10): yield SSE.patch_signals({"count": i}) await asyncio.sleep(1) return DatastarResponse(event_generator()) ``` -------------------------------- ### SignalValue Usage Example Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/types.md Demonstrates the creation of a dictionary containing various valid SignalValue types, including primitives, lists, and nested dictionaries, and formatting it into a Datastar event. ```python from datastar_py import ServerSentEventGenerator as SSE # All valid SignalValue types signals = { "string": "hello", "number": 42, "float": 3.14, "bool": True, "null": None, "list": [1, "two", 3.0, True], "dict": { "nested": "value", "count": 5, "items": [1, 2, 3], } } event = SSE.patch_signals(signals) ``` -------------------------------- ### Sanic DatastarResponse Streaming Example Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/api-reference/framework-responses.md Shows how to use datastar_respond in a Sanic route to stream Server-Sent Events, updating a 'count' value every second for 10 seconds. ```python from sanic import Sanic, request from datastar_py.sanic import datastar_respond, ServerSentEventGenerator as SSE app = Sanic("my_app") @app.route("/stream") async def stream(request): response = await datastar_respond(request) for i in range(10): await response.send(SSE.patch_signals({"count": i})) await asyncio.sleep(1) ``` -------------------------------- ### Django Example with datastar_response Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/api-reference/framework-responses.md Shows how to apply the datastar_response decorator to a Django view for streaming Server-Sent Events. The require_http_methods decorator is used to specify allowed HTTP methods. ```python from django.views.decorators.http import require_http_methods from datastar_py.django import datastar_response, ServerSentEventGenerator as SSE @require_http_methods(["GET"]) @datastar_response async def stream_view(request): for i in range(5): yield SSE.patch_signals({"count": i}) ``` -------------------------------- ### DatastarEvents Usage Examples Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/types.md Illustrates how to use the DatastarEvents type alias with DatastarResponse for different event streaming scenarios: single event, multiple events, and an async generator. ```python from datastar_py import ServerSentEventGenerator as SSE from datastar_py.fastapi import DatastarResponse @app.get("/stream") async def stream() -> DatastarResponse: # Single event return DatastarResponse(SSE.patch_signals({"count": 1})) @app.get("/stream-multiple") async def stream_multiple() -> DatastarResponse: # Multiple events events = [ SSE.patch_signals({"status": "loading"}), SSE.patch_elements("
Content
"), ] return DatastarResponse(events) @app.get("/stream-generator") async def stream_generator() -> DatastarResponse: async def event_gen(): for i in range(10): yield SSE.patch_signals({"count": i}) return DatastarResponse(event_gen()) ``` -------------------------------- ### Sanic Streaming Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/examples.md Example of streaming server-sent events with Datastar Python in a Sanic application, sending updates periodically. ```python from sanic import Sanic from datastar_py.sanic import datastar_respond, ServerSentEventGenerator as SSE app = Sanic("myapp") @app.route("/stream") async def stream(request): response = await datastar_respond(request) for i in range(100): await response.send(SSE.patch_signals({"count": i})) await asyncio.sleep(0.5) ``` -------------------------------- ### Generate HTML Attributes with AttributeGenerator Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/00-START-HERE.md Utilize `AttributeGenerator` to create HTML attributes dynamically. This example generates an 'onclick' attribute for a button. ```python from datastar_py import attribute_generator as data button_html = f"" ``` -------------------------------- ### Quart with Global Context Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/examples.md Shows how to use Datastar Python with Quart, accessing signals from the global context in a route handler. ```python from quart import Quart from datastar_py.quart import read_signals, datastar_response app = Quart(__name__) @app.route("/update", methods=["POST"]) @datastar_response async def update(): signals = await read_signals() # Uses global context return SSE.patch_signals({"updated": True}) ``` -------------------------------- ### Read Signals in Starlette/FastAPI Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/api-reference/framework-responses.md Use `read_signals` to get signal state from a Starlette/FastAPI request. It returns a dictionary of signals or None if the request is not from Datastar. ```python from datastar_py.fastapi import read_signals from starlette.requests import Request async def read_signals(request: Request) -> dict[str, Any] | None ``` ```python from fastapi import FastAPI, Request from datastar_py.fastapi import read_signals @app.post("/action") async def action(request: Request): signals = await read_signals(request) if signals: print(f"Current signals: {signals}") ``` -------------------------------- ### Django with Async Views Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/examples.md Demonstrates using Datastar Python with Django's asynchronous views for handling POST requests and yielding server-sent events. ```python from django.views.decorators.http import require_http_methods from datastar_py.django import datastar_response, read_signals @require_http_methods(["POST"]) @datastar_response async def process(request): signals = read_signals(request) if signals: result = await expensive_operation(signals) yield SSE.patch_signals({"result": result}) ``` -------------------------------- ### Distinguishing None vs. Empty Server-Sent Events Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/errors.md Understand the difference between returning `None` and an empty list (`[]`) from `DatastarResponse`. `None` results in a 204 No Content, while `[]` results in a 200 OK with an empty body. ```python from datastar_py.fastapi import DatastarResponse # Returns 204 No Content return DatastarResponse() # Same as DatastarResponse(None) # Returns 200 OK with no event data return DatastarResponse([]) # Empty list, not None # Returns 200 OK with one event return DatastarResponse(SSE.patch_signals({"x": 1})) ``` -------------------------------- ### Generate SSE Patch Event with ServerSentEventGenerator Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/00-START-HERE.md Use `ServerSentEventGenerator` to create SSE events. This example shows how to generate a patch event for a 'count' signal. ```python from datastar_py import ServerSentEventGenerator as SSE event = SSE.patch_signals({"count": 1}) ``` -------------------------------- ### Create Computed Signals Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/api-reference/attribute-generator.md Illustrates the creation of computed signals using either a dictionary of signal names and their expressions or keyword arguments. ```python data.computed(fullName="$firstName + ' ' + $lastName") data.computed({"isValid": "$email.includes('@')"}) ``` -------------------------------- ### Root Package Exports Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/api-reference/modules.md Imports key components from the root datastar_py package. Ensure Python 3.10 or higher is used. ```python from datastar_py import ( ServerSentEventGenerator, SSE_HEADERS, attribute_generator, ) ``` -------------------------------- ### View Transitions with DataStar Python Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/examples.md Use SSE.patch_elements with use_view_transition and view_transition_selector for animated DOM updates. ```python event = SSE.patch_elements( "
New content
", selector="#content", use_view_transition=True, view_transition_selector="#card" ) ``` -------------------------------- ### Quart DatastarResponse Import Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/api-reference/framework-responses.md Import the `DatastarResponse` class for Quart applications. ```python from datastar_py.quart import DatastarResponse ``` -------------------------------- ### AttributeGenerator with Underscore Prefix for htmy Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/configuration.md Use AttributeGenerator with an underscore prefix for compatibility with libraries like htmy, which convert underscores to hyphens unless the prefix starts with an underscore. ```python from datastar_py.attributes import AttributeGenerator # For libraries that convert underscore prefixes # htmy converts _ to - unless it starts with _, which is then stripped data_star = AttributeGenerator(alias="_data-") html.button("Click", **data_star.on("click", "alert('hi')").stop) ``` -------------------------------- ### Streaming SSE Events Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/README.md Demonstrates how to create a streaming response of Server-Sent Events using an async generator. ```python # Streaming events async def event_stream(): for i in range(100): yield SSE.patch_signals({"progress": i}) return DatastarResponse(event_stream()) ``` -------------------------------- ### InitAttr Class Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/api-reference/modules.md InitAttr is a specialized builder for `data-init` with timing and transition modifiers. ```APIDOC ## InitAttr ### Description Specialized builder for `data-init`. ### Modifiers: `once`, `delay()`, `viewtransition` ``` -------------------------------- ### Creating Multiple SSE Events Response Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/README.md Illustrates how to bundle multiple Server-Sent Events into a single DatastarResponse. ```python # Multiple events return DatastarResponse([ SSE.patch_signals({"status": "loading"}), SSE.patch_elements("
Content
"), SSE.patch_signals({"status": "done"}), ]) ``` -------------------------------- ### Execute Effects with Expressions Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/api-reference/attribute-generator.md Demonstrates how to use the `effect` method to execute a JavaScript expression whenever any referenced signals change. ```python data.effect("console.log('User changed:', $userId)") ``` -------------------------------- ### Initialize AttributeGenerator with Default and Custom Aliases Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/api-reference/attribute-generator.md Demonstrates how to use the global attribute_generator instance with its default alias and how to create a custom instance with a different alias. ```python from datastar_py import attribute_generator as data from datastar_py.attributes import AttributeGenerator # Use default alias data.on("click", "console.log('clicked')") # Use custom alias custom = AttributeGenerator(alias="_data-") custom.on("click", "console.log('clicked')") ``` -------------------------------- ### Setting SSE Headers Manually or with DatastarResponse Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/errors.md When manually creating Server-Sent Events responses, ensure SSE headers are correctly set. Use `DatastarResponse` for convenience or manually include `SSE_HEADERS`. ```python from fastapi import FastAPI from datastar_py import SSE_HEADERS, ServerSentEventGenerator as SSE app = FastAPI() # ❌ WRONG: Not using DatastarResponse, headers not set @app.get("/stream") async def stream(): async def gen(): yield SSE.patch_signals({"count": 1}) # Missing SSE_HEADERS! return StreamingResponse(gen()) ``` ```python # ✓ CORRECT: Use framework helper from datastar_py.fastapi import DatastarResponse @app.get("/stream") async def stream(): async def gen(): yield SSE.patch_signals({"count": 1}) return DatastarResponse(gen()) ``` ```python # ✓ OR: Manually set headers from datastar_py import SSE_HEADERS from starlette.responses import StreamingResponse @app.get("/stream") async def stream(): async def gen(): yield SSE.patch_signals({"count": 1}) return StreamingResponse(gen(), headers=SSE_HEADERS) ``` ```json { "Cache-Control": "no-cache", "Content-Type": "text/event-stream", "X-Accel-Buffering": "no", } ``` -------------------------------- ### Create Datastar Responses with SSE Events Source: https://github.com/starfederation/datastar-python/blob/develop/README.md Use DatastarResponse to wrap events for SSE. Import the Response class from your specific framework package (e.g., datastar_py.fastapi). Handles zero, one, two, or N events. ```python # per framework Response import. (Replace 'fastapi' with your framework.) e.g.: # 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("
")) # 2 events @app.get("two") def two_event(): return DatastarResponse([ SSE.patch_elements("
"), 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("
") 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("
")) await asyncio.sleep(1) ``` -------------------------------- ### Quart Integration Imports Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/api-reference/modules.md Imports core components for Quart integration, including DatastarResponse, datastar_response, read_signals, ServerSentEventGenerator, and SSE_HEADERS. DatastarResponse extends quart.Response. ```python from datastar_py.quart import ( DatastarResponse, datastar_response, read_signals, ServerSentEventGenerator, SSE_HEADERS, ) ``` -------------------------------- ### Perform a Redirect Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/examples.md Initiates a browser redirect to a specified URL. This is a common way to navigate users after an action. ```python event = SSE.redirect("/success") ``` -------------------------------- ### Generate and Use HTML Attributes Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/types.md Demonstrates how to generate HTML attribute strings and use them with HTML elements. Supports direct string conversion and unpacking as keyword arguments. ```python from datastar_py import attribute_generator as data from fasthtml.common import Div, Button # Convert to string attr_str = str(data.on("click", "alert('hi')")) # Returns: data-on:click="alert('hi')" # Use in element creation Div(data.on("click", "toggle()")) # Unpack as kwargs (works with some HTML libraries) kwargs = dict(data.on("click", "toggle()")) ``` -------------------------------- ### Creating a Single SSE Event Response Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/README.md Shows how to return a single Server-Sent Event from a DatastarResponse. ```python # Single event return DatastarResponse(SSE.patch_signals({"count": 1})) ``` -------------------------------- ### Quart DatastarResponse Constructor Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/api-reference/framework-responses.md Defines the constructor for `DatastarResponse` in Quart, specifying parameters for content, status, and headers. It auto-sets the timeout to None for streaming generators. ```python class DatastarResponse(Response): def __init__( self, content: DatastarEvents = None, status: int | None = None, headers: Mapping[str, str] | None = None, ) -> None ``` -------------------------------- ### Patching Signals with Datastar Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/README.md Demonstrates how to send updates to reactive state variables (signals) from the server using `patch_signals()`. ```python # Send signal updates SSE.patch_signals({"count": 42, "user": {"name": "Alice"}}) ``` -------------------------------- ### Initialize Element Attributes Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/types.md Use InitAttr to build attributes for element initialization on DOM insertion. Modifiers like .once, .delay(wait), and .viewtransition are available. ```python from datastar_py import attribute_generator as data # Auto-focus input data.init("this.focus()") # Initialize with delay data.init("showToast()").delay(500) ``` -------------------------------- ### init Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/api-reference/attribute-generator.md Executes an expression when the element is loaded into the DOM. Supports modifiers like .once, .delay(), and .viewtransition. ```APIDOC ## init ### Description Executes an expression when the element is loaded into the DOM. ### Method Signature ```python def init(expression: str) -> InitAttr ``` ### Parameters #### Parameters - **expression** (`str`) - Required - Expression to execute. ### Returns - `InitAttr` ### Modifiers - `.once` - Execute once - `.delay(wait)` - Delay execution - `.viewtransition` - Wrap in view transition ### Example ```python Input(data.init("this.focus()")) Div(data.init("initChart()").delay(100)) ``` ``` -------------------------------- ### Handle Framework Errors with DatastarResponse Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/errors.md Demonstrates how to catch exceptions during request processing and return a DatastarResponse with an appropriate status code and error message. Logs the error on the server side. ```python from fastapi import FastAPI, HTTPException from datastar_py.fastapi import DatastarResponse @app.post("/action") async def action(request: Request): try: signals = await read_signals(request) # Process... return DatastarResponse(SSE.patch_signals({"status": "ok"})) except Exception as e: # Log error logger.error(f"Action failed: {e}") # Return error response return DatastarResponse( SSE.execute_script("console.error('Server error')"), status_code=500 ) ``` -------------------------------- ### Core Library and Framework Imports for DataStar Python Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/INDEX.md Import necessary components from the datastar_py library. Choose the framework integration that matches your project's web framework (FastAPI, Starlette, Django, Quart, Litestar, Sanic, FastHTML). ```python # Core library from datastar_py import ServerSentEventGenerator, SSE_HEADERS, attribute_generator # Framework integration (choose one) from datastar_py.fastapi import DatastarResponse, datastar_response, read_signals from datastar_py.starlette import DatastarResponse, datastar_response, read_signals from datastar_py.django import DatastarResponse, datastar_response, read_signals from datastar_py.quart import DatastarResponse, datastar_response, read_signals from datastar_py.litestar import DatastarResponse, datastar_response, read_signals from datastar_py.sanic import DatastarResponse, datastar_respond, read_signals from datastar_py.fasthtml import DatastarResponse, datastar_response, read_signals ``` -------------------------------- ### Prepend Content to Element with DataStar Python Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/examples.md Use SSE.patch_elements with mode 'prepend' to add new content to the beginning of a selected element's children. ```python # Prepend event = SSE.patch_elements( "
  • First item
  • ", selector="#todo-list", mode="prepend" ) ``` -------------------------------- ### Litestar Integration Imports Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/api-reference/modules.md Imports core components for Litestar integration, including DatastarResponse, datastar_response, read_signals, ServerSentEventGenerator, and SSE_HEADERS. DatastarResponse extends litestar.response.Stream. ```python from datastar_py.litestar import ( DatastarResponse, datastar_response, read_signals, ServerSentEventGenerator, SSE_HEADERS, ) ``` -------------------------------- ### Sanic DatastarResponse Initialization Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/api-reference/framework-responses.md Defines the DatastarResponse class for Sanic, detailing its constructor parameters for content, status, and headers. ```python from datastar_py.sanic import DatastarResponse class DatastarResponse(HTTPResponse): def __init__( self, content: DatastarEvent | Collection[DatastarEvent] | None = None, status: int | None = None, headers: Mapping[str, str] | None = None, ) -> None ``` -------------------------------- ### Configure Signal Persistence Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/configuration.md Set persistence options for signals using localStorage or sessionStorage. Supports custom storage keys and filtering signals to persist. ```python from datastar_py import attribute_generator as data # Simple persistence data.persist # Session storage data.persist.session # Custom key data.persist("app-state-v1") # With filtering data.persist( "user-prefs", include="theme,language", exclude="temp_*" ) # Chained modifiers data.persist.session ``` -------------------------------- ### Load Datastar Signals in Quart Source: https://github.com/starfederation/datastar-python/blob/develop/README.md Loads datastar signals within a Quart request. Ensure the request object is passed to `read_signals`. ```python from datastar_py.quart import read_signals @app.route("/updates") async def updates(): signals = await read_signals() ``` -------------------------------- ### Litestar DatastarResponse Initialization Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/api-reference/framework-responses.md Defines the DatastarResponse class for Litestar, specifying its constructor parameters for content, background tasks, cookies, headers, and status code. ```python from datastar_py.litestar import DatastarResponse class DatastarResponse(Stream): def __init__( self, content: DatastarEvents = None, *, background: BackgroundTask | BackgroundTasks | None = None, cookies: ResponseCookies | None = None, headers: Mapping[str, str] | None = None, status_code: int | None = None, ) -> None ``` -------------------------------- ### ServerSentEventGenerator Methods Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/README.md Factory methods for creating Datastar Server-Sent Events to update the DOM, manage signals, execute scripts, and perform redirects. ```APIDOC ## ServerSentEventGenerator ### Description Factory methods for creating Datastar events. ### Methods - `patch_elements()`: Update HTML in the DOM. - `remove_elements()`: Remove elements. - `patch_signals()`: Update reactive signals. - `execute_script()`: Run JavaScript. - `redirect()`: Browser redirect. ``` -------------------------------- ### InitAttr specialized builder with modifiers Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/api-reference/modules.md A specialized builder for 'data-init' attributes, supporting 'once' execution and 'delay()' for deferred initialization, along with 'viewtransition'. ```python class InitAttr: # Specialized builder for `data-init`. ``` -------------------------------- ### Configure Query String Synchronization Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/configuration.md Synchronize signals with the query string in the URL. Supports filtering signals and using the history API. ```python from datastar_py import attribute_generator as data # Sync all signals data.query_string # Specific signals data.query_string("page,sort,filter") # With history API data.query_string("page,sort").history # Exclude signals data.query_string(exclude="temp_*") ``` -------------------------------- ### Integrate with FastAPI for Streaming Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/README.md Use the datastar_response decorator to create a FastAPI endpoint that streams Server-Sent Events, updating signals in real-time. ```python from datastar_py import ServerSentEventGenerator as SSE, attribute_generator as data from datastar_py.fastapi import DatastarResponse, datastar_response import asyncio import time # Framework integration @app.get("/stream") @datastar_response async def stream(): while True: yield SSE.patch_signals({"time": time.time()}) await asyncio.sleep(1) ``` -------------------------------- ### Insert Element Before Target with DataStar Python Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/examples.md Use SSE.patch_elements with mode 'before' to insert new content immediately before a selected element. ```python # Insert before event = SSE.patch_elements( "
    ", selector="#reference", mode="before" ) ``` -------------------------------- ### Synchronize Signals with URL Query Parameters Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/types.md Use QueryStringAttr to build attributes for syncing signals with URL query parameters. Supports filtering signals and using the history API with the .history modifier. ```python from datastar_py import attribute_generator as data # Sync all signals to query string data.query_string # Only specific signals with history data.query_string("page,sort").history ``` -------------------------------- ### Execute JavaScript with Auto-Cleanup Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/README.md Creates an SSE event to execute JavaScript on the client. Scripts can be configured to automatically remove themselves after execution or persist. ```python from datastar_py.sse import SSE # Script automatically removes itself after execution event_auto_remove = SSE.execute_script("window.scrollTo(0, 0)", auto_remove=True) # Script persists (for state setup) event_persist = SSE.execute_script("window.API_KEY = '...'", auto_remove=False) ``` -------------------------------- ### Create Server-Sent Event with Various Signal Values Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/configuration.md Construct a Server-Sent Event using SSE.patch_signals with a dictionary containing various types of signal values, including nested structures. ```python from datastar_py import ServerSentEventGenerator as SSE # All value types signals = { "string_val": "hello", "int_val": 42, "float_val": 3.14, "bool_val": True, "null_val": None, "list_val": [1, "two", 3.0], "dict_val": { "nested": "value", "count": 5, "items": [1, 2, 3], }, } event = SSE.patch_signals(signals) ``` -------------------------------- ### Handle JavaScript Events in Datastar Python Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/types.md Use the `data.on()` method to attach event listeners. IDEs provide autocompletion for standard events. Custom events are also supported. ```python from datastar_py import attribute_generator as data # IDE will provide autocompletion data.on("click", "handleClick()") data.on("input", "$search = $event.target.value") data.on("keydown", "if ($event.key === 'Enter') submit()") # Custom events also work data.on("custom-event", "handle()") ``` -------------------------------- ### Type-Annotated SSE Event Handler Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/README.md Demonstrates how Datastar Python's type annotations enhance code clarity and enable static analysis. Type hints work seamlessly across different web frameworks. ```python from typing import TYPE_CHECKING from datastar_py.sse import DatastarEvents, SSE from datastar_py.attributes import SignalValue # Type annotations work across frameworks async def my_handler() -> DatastarEvents: signals: dict[str, SignalValue] = {"count": 42} return SSE.patch_signals(signals) ``` -------------------------------- ### show Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/api-reference/attribute-generator.md Shows or hides an element based on a boolean reactive expression. ```APIDOC ## show ### Description Shows or hides an element based on a boolean expression. ### Method `show(expression: str) -> BaseAttr` ### Parameters #### Path Parameters - **expression** (str) - Required - Expression that evaluates to true/false. ### Returns `BaseAttr` ### Example ```python Div("Admin panel", data.show("$isAdmin")) ``` ``` -------------------------------- ### SSE Module Exports Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/api-reference/modules.md Imports core components for Server-Sent Event generation from the datastar_py.sse module. This includes event generators, event types, and SSE-specific headers. ```python from datastar_py.sse import ( ServerSentEventGenerator, DatastarEvent, DatastarEvents, SSE_HEADERS, ) ``` -------------------------------- ### Persistent User Theme Preferences Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/examples.md Allows users to select a theme (Dark/Light) and persists this preference to localStorage using `data.persist`. It also includes a signal patch to apply the theme. ```python from datastar_py import attribute_generator as data # Persist theme selection to localStorage ThemeSwitcher = Div( Button("Dark", data.on("click", "$theme = 'dark'")), Button("Light", data.on("click", "$theme = 'light'")), # Persist theme across sessions data.persist("app-settings", include="theme"), data.on_signal_patch("applyTheme()").filter(include="theme"), ) ``` -------------------------------- ### Export Core Events and Headers Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/README.md Imports core event factory, HTTP headers, and the global AttributeGenerator instance from the main datastar_py package. ```python from datastar_py import ( ServerSentEventGenerator, # Core event factory SSE_HEADERS, # HTTP headers dict attribute_generator, # Global AttributeGenerator instance ) ``` -------------------------------- ### Real-time Data Table Update Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/examples.md Continuously fetches data and updates a table's body in real-time every 5 seconds. Assumes a `fetch_data` function is available. ```python @app.get("/table/live") @datastar_response async def live_table(): while True: # Fetch latest data rows = await fetch_data() # Update table html = "".join( f"{row.id}{row.name}" for row in rows ) yield SSE.patch_elements(html, selector="tbody", mode="inner") await asyncio.sleep(5) ``` -------------------------------- ### Master-Detail Pattern for Item Selection Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/examples.md Implements a master-detail pattern where clicking an item in a list fetches and displays its details in a separate area. Assumes `fetch_item` function is available. ```python @app.get("/items") def items_list(): return """
    • Item 1
    • Item 2
    """ @app.get("/item/{item_id}") async def item_detail(item_id: int): item = await fetch_item(item_id) html = f"

    {item.name}

    {item.description}

    " return DatastarResponse( SSE.patch_elements(html, selector="#detail") ) ``` -------------------------------- ### Django DatastarResponse Import Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/api-reference/framework-responses.md Import the `DatastarResponse` class for Django applications. ```python from datastar_py.django import DatastarResponse ``` -------------------------------- ### Show Loading Indicator with SSE Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/api-reference/attribute-generator.md The indicator function generates a signal that is true while a Server-Sent Events (SSE) request is in flight, useful for displaying loading states. ```python Div( data.indicator("loading"), data.show("$loading"), ) ``` -------------------------------- ### Infinite Scroll with Datastar Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/examples.md Implements infinite scrolling by loading more items as the user scrolls down. Uses SSE to patch elements and update signals. ```python @app.get("/infinite") def infinite_page(): return """
    Loading...
    """ @app.post("/load-more") @datastar_response async def load_more(request: Request): signals = await read_signals(request) page = signals.get("page", 0) + 1 items = await fetch_items(page) html = "".join(f"
    {item}
    " for item in items) yield SSE.patch_elements(html, selector="#items", mode="append") yield SSE.patch_signals({"page": page}) ``` -------------------------------- ### view_transition Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/api-reference/attribute-generator.md Explicitly sets the view-transition-name CSS property. ```APIDOC ## view_transition ### Description Sets the view-transition-name CSS property explicitly. ### Method ```python def view_transition(expression: str) -> BaseAttr ``` ### Parameters #### Parameters - **expression** (str) - Required - Expression evaluating to transition name. ### Returns `BaseAttr` ### Example ```python data.view_transition("'card-' + $id") ``` ``` -------------------------------- ### FastAPI/Starlette DatastarResponse Imports Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/api-reference/framework-responses.md Import the `DatastarResponse` class for FastAPI and Starlette applications. ```python from datastar_py.fastapi import DatastarResponse from datastar_py.starlette import DatastarResponse ``` -------------------------------- ### Configure Intersection Observer Options Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/configuration.md Set options for viewport intersection observers. Use 'once' for single triggers, 'threshold' for percentage visibility, 'full' for fully visible, and 'exit' to trigger when leaving the viewport. ```python from datastar_py import attribute_generator as data # Load more when element becomes visible data.on_intersect("loadMore()").once # Trigger animation at 75% visibility data.on_intersect("playAnimation()").threshold(75) # Trigger when fully visible data.on_intersect("highlightContent()").full # React to exit data.on_intersect("markAsOutOfView()").exit ``` -------------------------------- ### Django DatastarResponse Constructor Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/api-reference/framework-responses.md Defines the constructor for `DatastarResponse` in Django, specifying content, status, and headers as keyword-only arguments. ```python class DatastarResponse(StreamingHttpResponse): def __init__( self, content: DatastarEvents = None, *, status: int | None = None, headers: Mapping[str, str] | None = None, ) -> None ``` -------------------------------- ### style Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/api-reference/attribute-generator.md Sets inline CSS styles to reactive expressions. It accepts a dictionary of style properties and expressions or keyword arguments. ```APIDOC ## style ### Description Sets inline CSS styles to reactive expressions. ### Method `style(self, style_dict: Mapping | None = None, /, **styles: str) -> BaseAttr` ### Parameters #### Keyword Arguments - **styles** (str) - Required - Keyword arguments for styles. #### Optional Parameters - **style_dict** (Mapping | None) - Optional - Dictionary of {property: expression}. ### Returns `BaseAttr` ### Example ```python data.style(opacity="$isVisible ? 1 : 0.5", color="$themeColor") data.style({"display": "$show ? 'block' : 'none'"}) ``` ``` -------------------------------- ### datastar_py.fasthtml Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/api-reference/modules.md FastHTML integration module, re-exporting components from datastar_py.starlette. ```APIDOC ## datastar_py.fasthtml ### Description Integration module for FastHTML applications. This module re-exports components from `datastar_py.starlette` as FastHTML uses Starlette internally. ### Components - **DatastarResponse**: Extends `starlette.responses.StreamingResponse` (via Starlette). - **datastar_response**: Function to generate Datastar responses. - **read_signals**: Asynchronous function to read signals from the request. - Signature: `async def read_signals(request: Request) -> dict[str, Any] | None` - **ServerSentEventGenerator**: Generator for Server-Sent Events. - **SSE_HEADERS**: Standard headers for Server-Sent Events. ``` -------------------------------- ### OnSignalPatchAttr Class Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/api-reference/modules.md OnSignalPatchAttr is a specialized builder for `data-on-signal-patch` with filtering and timing modifiers. ```APIDOC ## OnSignalPatchAttr ### Description Specialized builder for `data-on-signal-patch`. ### Modifiers: `filter()`, `debounce()`, `throttle()`, `delay()` ``` -------------------------------- ### on_resize Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/api-reference/attribute-generator.md Executes an expression when element dimensions change, with debouncing and throttling options. ```APIDOC ## on_resize ### Description Executes an expression when element dimensions change. ### Method `on_resize(expression: str) -> OnResizeAttr` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **expression** (`str`) - Required - Expression to execute. ### Returns `OnResizeAttr` ### Modifiers - `.debounce(wait)` - Debounce calls - `.throttle(wait)` - Throttle calls ### Request Example ```python data.on_resize("$width = el.offsetWidth").debounce(200) ``` ### Response #### Success Response `OnResizeAttr` object. #### Response Example None explicitly defined, returns an `OnResizeAttr` object. ``` -------------------------------- ### Framework Responses Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/README.md Response handlers and utilities for integrating Datastar with various Python web frameworks. ```APIDOC ## Framework Responses ### Description Response handlers for each framework. ### Components - `DatastarResponse` class - `datastar_response` decorator - `read_signals()` function - Framework-specific helpers ``` -------------------------------- ### Integrate with FastAPI using DatastarResponse Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/00-START-HERE.md Handle Datastar SSE events within a FastAPI application using `DatastarResponse`. This snippet shows how to return a generated event. ```python from datastar_py.fastapi import DatastarResponse return DatastarResponse(event) ``` -------------------------------- ### Server-Sent Events (SSE) Format Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/README.md Illustrates the expected format for SSE messages, including event types and data payloads. ```python # Example event format event: datastar-patch-signals data: signals {"count": 1} event: datastar-patch-elements selector #app elements
    New content
    ``` -------------------------------- ### Using ElementPatchNamespace for SVG and MathML Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/types.md Shows how to apply patches to SVG and MathML elements using the ElementPatchNamespace. This ensures that elements are correctly interpreted within their respective XML namespaces. ```python from datastar_py import ServerSentEventGenerator as SSE from datastar_py.consts import ElementPatchNamespace # Patch SVG element event = SSE.patch_elements( '', selector="circle", namespace=ElementPatchNamespace.SVG ) # Patch MathML element event = SSE.patch_elements( "x", namespace=ElementPatchNamespace.MATHML ) ``` -------------------------------- ### Datastar Attribute Generator: Lifecycle Hooks Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/examples.md Implement lifecycle hooks for elements using Datastar attributes. Supports initialization on element insert, delayed initialization, and one-time execution. ```python from datastar_py import attribute_generator as data from fasthtml.common import Input # On element insert Input(data.init("this.focus()")) # Delayed initialization Div(data.init("initChart()").delay(100)) # Single execution Button(data.init("setupOnce()").once) ``` -------------------------------- ### Insert Element After Target with DataStar Python Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/examples.md Use SSE.patch_elements with mode 'after' to insert new content immediately after a selected element. ```python # Insert after event = SSE.patch_elements( "
    Added later
    ", selector="#last-item", mode="after" ) ``` -------------------------------- ### FastAPI/Starlette DatastarResponse Constructor Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/api-reference/framework-responses.md Defines the constructor for `DatastarResponse` in FastAPI/Starlette, specifying parameters for content, status code, headers, and background tasks. ```python class DatastarResponse(StreamingResponse): def __init__( self, content: DatastarEvents = None, status_code: int | None = None, headers: Mapping[str, str] | None = None, background: BackgroundTask | None = None, ) -> None ``` -------------------------------- ### Infinite Stream with FastAPI Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/examples.md Create an infinite stream of Server-Sent Events (SSE) from a FastAPI endpoint. Suitable for live data feeds like real-time clocks or status updates. ```python @app.get("/live") @datastar_response async def live(): while True: yield SSE.patch_signals({"time": time.time()}) await asyncio.sleep(1) ``` -------------------------------- ### _HtmlProvider Protocol Definition Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/api-reference/modules.md Defines the _HtmlProvider protocol, used to detect objects implementing the __html__() method, typically from libraries like FastHTML or htpy. This is relevant for rendering HTML within SSE. ```python @runtime_checkable class _HtmlProvider(Protocol): def __html__(self) -> str: ... ``` -------------------------------- ### datastar_py.fastapi Source: https://github.com/starfederation/datastar-python/blob/develop/_autodocs/api-reference/modules.md FastAPI integration module. Re-exports from datastar_py.starlette and provides FastAPI-specific dependencies. ```APIDOC ## datastar_py.fastapi ### Description Provides FastAPI integration by re-exporting components from `datastar_py.starlette` and offering FastAPI-specific dependency injection for signal reading. ### Usage ```python from datastar_py.fastapi import ReadSignals from fastapi import Depends, FastAPI app = FastAPI() @app.get("/signals") async def get_signals(signals: ReadSignals = Depends(ReadSignals)): return signals ``` ### Re-exports - `datastar_py.starlette` ### Additional Components - **ReadSignals**: An `Annotated` type for dependency injection of signals read from the request. ```