Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,9 @@ async def my_route(request):
await asyncio.sleep(1)
```

> [!NOTE]
> The `datastar_response` decorator is not needed, (and not provided by the fastapi module,) for FastAPI. Instead, `response_class=DatastarResponse` should be specified in the route decorator to achieve the same result.

## 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
Expand Down
16 changes: 6 additions & 10 deletions examples/fastapi/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,15 @@

import uvicorn
from fastapi import FastAPI
from fastapi.responses import HTMLResponse, StreamingResponse
from fastapi.responses import HTMLResponse

from datastar_py.fastapi import (
DatastarResponse,
ReadSignals,
ServerSentEventGenerator,
)

app = FastAPI()
app = FastAPI(debug=True)


HTML = """\
Expand Down Expand Up @@ -64,7 +64,10 @@ async def read_root():
return HTMLResponse(HTML.replace("CURRENT_TIME", f"{datetime.isoformat(datetime.now())}"))


async def time_updates():
@app.get("/updates", response_class=DatastarResponse)
async def time_updates(signals: ReadSignals):
# ReadSignals is a dependency that automatically loads the signals from the request
print(signals)
while True:
yield ServerSentEventGenerator.patch_elements(
f"""<span id="currentTime">{datetime.now().isoformat()}"""
Expand All @@ -76,12 +79,5 @@ async def time_updates():
await asyncio.sleep(1)


@app.get("/updates", response_class=StreamingResponse)
async def updates(signals: ReadSignals):
# ReadSignals is a dependency that automatically loads the signals from the request
print(signals)
return DatastarResponse(time_updates())


if __name__ == "__main__":
uvicorn.run(app)
3 changes: 1 addition & 2 deletions src/datastar_py/fastapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,13 @@
from fastapi import Depends

from .sse import SSE_HEADERS, ServerSentEventGenerator
from .starlette import DatastarResponse, datastar_response, read_signals
from .starlette import DatastarResponse, read_signals

__all__ = [
"SSE_HEADERS",
"DatastarResponse",
"ReadSignals",
"ServerSentEventGenerator",
"datastar_response",
"read_signals",
]

Expand Down