uvicorn startup
This commit is contained in:
@@ -1,12 +1,15 @@
|
|||||||
---
|
---
|
||||||
name: nicegui
|
name: nicegui
|
||||||
description: 'Reference hub for NiceGUI and FastAPI application structure, UI composition, styling, bindable state, interactions, troubleshooting, testing, and source documentation. Use when planning, implementing, reviewing, or debugging NiceGUI applications; load only the references relevant to the task.'
|
description: 'Reference hub for NiceGUI and FastAPI application structure, ASGI and Uvicorn startup, UI composition, styling, bindable state, interactions, troubleshooting, testing, and source documentation. Use when planning, implementing, reviewing, deploying, or debugging NiceGUI applications; load only the references relevant to the task.'
|
||||||
x-personal-mcp:
|
x-personal-mcp:
|
||||||
id: nicegui
|
id: nicegui
|
||||||
version: 2.2.0
|
version: 2.3.0
|
||||||
tags:
|
tags:
|
||||||
- nicegui
|
- nicegui
|
||||||
- fastapi
|
- fastapi
|
||||||
|
- asgi
|
||||||
|
- uvicorn
|
||||||
|
- deployment
|
||||||
- ui
|
- ui
|
||||||
- architecture
|
- architecture
|
||||||
- scaffolding
|
- scaffolding
|
||||||
@@ -51,6 +54,17 @@ Load [application architecture](./references/architecture.md) for:
|
|||||||
- optional persistence, LangGraph, or mounted documentation
|
- optional persistence, LangGraph, or mounted documentation
|
||||||
- async responsiveness and baseline tests
|
- async responsiveness and baseline tests
|
||||||
|
|
||||||
|
### FastAPI And Uvicorn Startup
|
||||||
|
|
||||||
|
Load [FastAPI and Uvicorn startup](./references/fastapi-uvicorn-startup.md) for:
|
||||||
|
|
||||||
|
- choosing between `ui.run()` and `ui.run_with()`
|
||||||
|
- understanding the parent FastAPI app and NiceGUI's internal app
|
||||||
|
- composing ASGI lifespan and mounted routes
|
||||||
|
- serving an app instance or factory with Uvicorn
|
||||||
|
- exposing programmatic startup through `[project.scripts]`
|
||||||
|
- reload, worker, and process-local state constraints
|
||||||
|
|
||||||
### Components And Styling
|
### Components And Styling
|
||||||
|
|
||||||
Load [architecture and styling](./references/architecture-and-styling.md) for:
|
Load [architecture and styling](./references/architecture-and-styling.md) for:
|
||||||
@@ -104,7 +118,8 @@ Load [source documentation](./references/source-documentation.md) when:
|
|||||||
### New Application Or Architecture Review
|
### New Application Or Architecture Review
|
||||||
|
|
||||||
1. Load [application architecture](./references/architecture.md).
|
1. Load [application architecture](./references/architecture.md).
|
||||||
2. Add [architecture and styling](./references/architecture-and-styling.md) only when page and component design is in scope.
|
2. Add [FastAPI and Uvicorn startup](./references/fastapi-uvicorn-startup.md) when FastAPI owns the application or startup must be exposed as a project command.
|
||||||
|
3. Add [architecture and styling](./references/architecture-and-styling.md) only when page and component design is in scope.
|
||||||
|
|
||||||
### Page Or Component Work
|
### Page Or Component Work
|
||||||
|
|
||||||
|
|||||||
@@ -56,6 +56,8 @@ Recommended base shape:
|
|||||||
- FastAPI exposes a health route such as `/healthz`.
|
- FastAPI exposes a health route such as `/healthz`.
|
||||||
- Imports do not trigger runtime global side effects.
|
- Imports do not trigger runtime global side effects.
|
||||||
|
|
||||||
|
For the ownership relationship between a caller-created FastAPI app, `nicegui.app`, `ui.run_with()`, Uvicorn, and a packaged startup command, load [FastAPI and Uvicorn startup](./fastapi-uvicorn-startup.md).
|
||||||
|
|
||||||
## Dependency Direction
|
## Dependency Direction
|
||||||
|
|
||||||
Prefer:
|
Prefer:
|
||||||
|
|||||||
@@ -0,0 +1,249 @@
|
|||||||
|
# FastAPI And Uvicorn Startup
|
||||||
|
|
||||||
|
Use this reference when FastAPI owns the application and NiceGUI is one part of it. The central distinction is between **composing an ASGI application** and **starting an ASGI server**:
|
||||||
|
|
||||||
|
- [`ui.run_with()`](https://github.com/zauberzeug/nicegui/blob/main/nicegui/ui_run_with.py) composes NiceGUI with a caller-owned FastAPI application. It does not start Uvicorn.
|
||||||
|
- [`uvicorn.run()`](https://www.uvicorn.org/#running-programmatically) starts the server and tells it which ASGI application to serve.
|
||||||
|
|
||||||
|
## Ownership Model
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
E["Project script: my-app"] --> M["main()"]
|
||||||
|
M --> U["uvicorn.run()"]
|
||||||
|
U --> F["create_app()"]
|
||||||
|
F --> P["Parent FastAPI app"]
|
||||||
|
P --> A["API routes and middleware"]
|
||||||
|
P -->|"mount_path=/gui"| N["NiceGUI App"]
|
||||||
|
U -->|"ASGI requests and lifespan"| P
|
||||||
|
```
|
||||||
|
|
||||||
|
The objects have separate responsibilities:
|
||||||
|
|
||||||
|
| Object | Owner | Responsibility |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Parent `FastAPI` instance | Application code | Root ASGI app, API routes, middleware, lifespan, and mounted applications |
|
||||||
|
| `nicegui.app` | NiceGUI | A process-local [`App`](https://github.com/zauberzeug/nicegui/blob/main/nicegui/app/app.py) instance that subclasses `FastAPI` |
|
||||||
|
| `ui.run_with(parent_app)` | NiceGUI integration | Configures NiceGUI, mounts `nicegui.app` into `parent_app`, and integrates lifecycle handling |
|
||||||
|
| Uvicorn | Server process | Imports or receives the root ASGI app, opens sockets, drives lifespan, and serves requests |
|
||||||
|
|
||||||
|
Uvicorn must serve the **parent FastAPI app** when using `ui.run_with()`. Passing `nicegui.app` to `ui.run_with()` is rejected because it would mount NiceGUI into itself and recurse on unmatched routes.
|
||||||
|
|
||||||
|
## Choose One Startup Mode
|
||||||
|
|
||||||
|
### Let NiceGUI Own Startup
|
||||||
|
|
||||||
|
Use `ui.run()` when NiceGUI is the main application. Add ordinary FastAPI routes to the exported `nicegui.app` object:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from nicegui import app, ui
|
||||||
|
|
||||||
|
|
||||||
|
@app.get('/healthz')
|
||||||
|
def health() -> dict[str, str]:
|
||||||
|
return {'status': 'ok'}
|
||||||
|
|
||||||
|
|
||||||
|
@ui.page('/')
|
||||||
|
def home() -> None:
|
||||||
|
ui.label('Home')
|
||||||
|
|
||||||
|
|
||||||
|
ui.run()
|
||||||
|
```
|
||||||
|
|
||||||
|
In this mode, NiceGUI configures and starts its own [Uvicorn-derived server](https://github.com/zauberzeug/nicegui/blob/main/nicegui/server.py). Do not also call `uvicorn.run()`.
|
||||||
|
|
||||||
|
### Let FastAPI Own The Application
|
||||||
|
|
||||||
|
Use `ui.run_with()` when an existing FastAPI application owns middleware, API routers, OpenAPI configuration, lifespan resources, or deployment startup. The [official NiceGUI FastAPI example](https://github.com/zauberzeug/nicegui/blob/main/examples/fastapi/main.py) follows this model.
|
||||||
|
|
||||||
|
`mount_path` controls where the NiceGUI application appears externally. A NiceGUI page declared as `/` is reachable at `/gui/` when mounted at `/gui`, while parent routes such as `/healthz` remain at the root. A dedicated UI prefix usually makes ownership and route conflicts clearer than mounting both applications at `/`.
|
||||||
|
|
||||||
|
## Canonical Factory Layout
|
||||||
|
|
||||||
|
Keep application composition importable and server startup explicit:
|
||||||
|
|
||||||
|
```text
|
||||||
|
.
|
||||||
|
├─ pyproject.toml
|
||||||
|
└─ src/
|
||||||
|
└─ my_app/
|
||||||
|
├─ __init__.py
|
||||||
|
└─ main.py
|
||||||
|
```
|
||||||
|
|
||||||
|
```python title="src/my_app/main.py"
|
||||||
|
from collections.abc import AsyncIterator
|
||||||
|
from contextlib import asynccontextmanager
|
||||||
|
|
||||||
|
import uvicorn
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from nicegui import ui
|
||||||
|
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
|
||||||
|
app.state.ready = True
|
||||||
|
try:
|
||||||
|
yield
|
||||||
|
finally:
|
||||||
|
app.state.ready = False
|
||||||
|
|
||||||
|
|
||||||
|
def register_pages() -> None:
|
||||||
|
@ui.page('/')
|
||||||
|
def dashboard() -> None:
|
||||||
|
ui.label('Dashboard')
|
||||||
|
|
||||||
|
|
||||||
|
def create_app() -> FastAPI:
|
||||||
|
app = FastAPI(lifespan=lifespan)
|
||||||
|
|
||||||
|
@app.get('/healthz')
|
||||||
|
def health() -> dict[str, str]:
|
||||||
|
return {'status': 'ok'}
|
||||||
|
|
||||||
|
register_pages()
|
||||||
|
ui.run_with(
|
||||||
|
app,
|
||||||
|
mount_path='/gui',
|
||||||
|
storage_secret='replace-with-a-secret-from-settings',
|
||||||
|
)
|
||||||
|
return app
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
uvicorn.run(
|
||||||
|
'my_app.main:create_app',
|
||||||
|
factory=True,
|
||||||
|
host='0.0.0.0',
|
||||||
|
port=8000,
|
||||||
|
log_level='info',
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
|
```
|
||||||
|
|
||||||
|
The `storage_secret` is optional unless the application uses `ui.storage.user` or `ui.storage.browser`. Load the real value from typed settings or an environment-backed secret rather than committing it.
|
||||||
|
|
||||||
|
The example passes an [import string and `factory=True`](https://www.uvicorn.org/settings/#application) to Uvicorn. Uvicorn imports `my_app.main`, calls the zero-argument `create_app` factory, and serves the returned parent FastAPI app. Import strings are also required when Uvicorn creates reload or worker subprocesses; passing `create_app()` directly only supports the simple single-process case.
|
||||||
|
|
||||||
|
NiceGUI keeps framework state in its process-local app singleton. Treat `create_app()` as a once-per-worker factory. Calling it repeatedly in one interpreter can register the same pages and lifecycle handlers more than once; tests that create multiple apps must isolate or reset NiceGUI state.
|
||||||
|
|
||||||
|
## Lifespan Ordering
|
||||||
|
|
||||||
|
The [ASGI lifespan protocol](https://asgi.readthedocs.io/en/latest/specs/lifespan.html) is driven by the server. Uvicorn sends startup before accepting requests and sends shutdown while terminating the process. Lifespan runs once per event loop, including once in each worker process.
|
||||||
|
|
||||||
|
Current NiceGUI source integrates with the parent application by:
|
||||||
|
|
||||||
|
1. Capturing the parent FastAPI lifespan context.
|
||||||
|
2. Mounting NiceGUI's internal app on the parent.
|
||||||
|
3. Replacing the parent lifespan with a wrapper.
|
||||||
|
4. Starting NiceGUI before entering the original parent lifespan.
|
||||||
|
5. Exiting the original parent lifespan before shutting down NiceGUI.
|
||||||
|
|
||||||
|
This exact ordering comes from the current [`ui.run_with` implementation](https://github.com/zauberzeug/nicegui/blob/main/nicegui/ui_run_with.py) and is version-sensitive. Check the pinned NiceGUI version before making one startup handler depend on another framework's internal ordering.
|
||||||
|
|
||||||
|
Create database pools, HTTP clients, and similar resources in the parent [FastAPI lifespan](https://fastapi.tiangolo.com/advanced/events/), then close them after `yield`. Do not create event-loop-bound resources at import time or assume that globals are shared between workers.
|
||||||
|
|
||||||
|
## Expose The Server As A Project Script
|
||||||
|
|
||||||
|
Map a command name to the no-argument startup function:
|
||||||
|
|
||||||
|
```toml title="pyproject.toml"
|
||||||
|
[project]
|
||||||
|
name = "my-app"
|
||||||
|
version = "0.1.0"
|
||||||
|
requires-python = ">=3.12"
|
||||||
|
dependencies = [
|
||||||
|
"fastapi",
|
||||||
|
"nicegui",
|
||||||
|
"uvicorn[standard]",
|
||||||
|
]
|
||||||
|
|
||||||
|
[project.scripts]
|
||||||
|
my-app = "my_app.main:main"
|
||||||
|
|
||||||
|
[build-system]
|
||||||
|
requires = ["hatchling"]
|
||||||
|
build-backend = "hatchling.build"
|
||||||
|
|
||||||
|
[tool.hatch.build.targets.wheel]
|
||||||
|
packages = ["src/my_app"]
|
||||||
|
```
|
||||||
|
|
||||||
|
Run the installed command through uv:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
uv run my-app
|
||||||
|
```
|
||||||
|
|
||||||
|
The uv [project entry-point documentation](https://docs.astral.sh/uv/concepts/projects/config/#entry-points) requires a build system so uv installs the project and generates its command. The `[project.scripts]` target follows the [PyPA entry-point specification](https://packaging.python.org/en/latest/specifications/entry-points/#use-for-scripts): its generated wrapper imports `main`, calls it without arguments, and uses the return value as the process exit status. Returning `None` means successful completion.
|
||||||
|
|
||||||
|
Use application settings or environment variables for host, port, and logging configuration. Add an explicit CLI parser only when the project command needs user-supplied arguments; the entry-point callable itself still receives no arguments.
|
||||||
|
|
||||||
|
## Development Reload
|
||||||
|
|
||||||
|
Because `main()` supplies an import string, it can enable Uvicorn reload for local development:
|
||||||
|
|
||||||
|
```python
|
||||||
|
def main() -> None:
|
||||||
|
uvicorn.run(
|
||||||
|
'my_app.main:create_app',
|
||||||
|
factory=True,
|
||||||
|
host='127.0.0.1',
|
||||||
|
port=8000,
|
||||||
|
reload=True,
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
Keep reload disabled in production. Uvicorn documents [`reload` and `workers` as mutually exclusive](https://www.uvicorn.org/settings/#production), and each worker would have independent NiceGUI state, lifespan resources, and WebSocket connections. Use one worker by default unless the application has explicitly validated session affinity and externalized every stateful dependency needed across processes.
|
||||||
|
|
||||||
|
## Anti-Patterns
|
||||||
|
|
||||||
|
| Anti-pattern | Why it fails | Preferred approach |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `ui.run_with(nicegui.app)` | Mounts NiceGUI into itself | Pass a separately created `FastAPI()` instance |
|
||||||
|
| Calling both `ui.run()` and `ui.run_with()` | Gives two paths responsibility for startup | Choose one ownership model |
|
||||||
|
| `uvicorn.run(create_app(), reload=True)` | Reload subprocesses cannot import the app object | Use an import string with `factory=True` |
|
||||||
|
| Calling `uvicorn.run()` at module import time | Importing the module starts a blocking server and breaks subprocess startup | Call it from `main()` |
|
||||||
|
| Top-level `ui.label(...)` with `ui.run_with()` | Script-mode elements are discarded by this integration | Register UI in `@ui.page` functions or a root callable |
|
||||||
|
| Multiple workers by default | Process-local UI state and WebSockets are not automatically shared | Start with one worker and validate a distributed design explicitly |
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
Use `TestClient` as a context manager so the parent ASGI lifespan runs:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from my_app.main import create_app
|
||||||
|
|
||||||
|
|
||||||
|
def test_application_routes() -> None:
|
||||||
|
with TestClient(create_app()) as client:
|
||||||
|
assert client.get('/healthz').json() == {'status': 'ok'}
|
||||||
|
assert client.get('/gui/').status_code == 200
|
||||||
|
```
|
||||||
|
|
||||||
|
Also verify:
|
||||||
|
|
||||||
|
- startup resources exist while the client context is active and are released afterward
|
||||||
|
- the mounted UI returns HTML and parent API failures retain FastAPI's JSON responses
|
||||||
|
- `uv run my-app` starts the server and responds on both the API and UI paths
|
||||||
|
- shutdown signals complete without orphaned background tasks
|
||||||
|
|
||||||
|
## Primary Sources
|
||||||
|
|
||||||
|
- [NiceGUI pages, routing, and FastAPI integration](https://www.nicegui.io/documentation/section_pages_routing)
|
||||||
|
- [NiceGUI `ui.run_with` implementation](https://github.com/zauberzeug/nicegui/blob/main/nicegui/ui_run_with.py)
|
||||||
|
- [NiceGUI FastAPI example](https://github.com/zauberzeug/nicegui/blob/main/examples/fastapi/main.py)
|
||||||
|
- [FastAPI lifespan events](https://fastapi.tiangolo.com/advanced/events/)
|
||||||
|
- [ASGI lifespan protocol](https://asgi.readthedocs.io/en/latest/specs/lifespan.html)
|
||||||
|
- [Uvicorn settings](https://www.uvicorn.org/settings/)
|
||||||
|
- [Uvicorn programmatic startup](https://www.uvicorn.org/#running-programmatically)
|
||||||
|
- [uv project entry points](https://docs.astral.sh/uv/concepts/projects/config/#entry-points)
|
||||||
|
- [PyPA entry points specification](https://packaging.python.org/en/latest/specifications/entry-points/)
|
||||||
@@ -6,6 +6,8 @@ Use these links to verify framework-specific behavior before relying on version-
|
|||||||
|
|
||||||
!!! info "NiceGUI sources"
|
!!! info "NiceGUI sources"
|
||||||
- [Pages, routing, and FastAPI integration](https://www.nicegui.io/documentation/section_pages_routing)
|
- [Pages, routing, and FastAPI integration](https://www.nicegui.io/documentation/section_pages_routing)
|
||||||
|
- [`ui.run_with` implementation](https://github.com/zauberzeug/nicegui/blob/main/nicegui/ui_run_with.py)
|
||||||
|
- [FastAPI integration example](https://github.com/zauberzeug/nicegui/blob/main/examples/fastapi/main.py)
|
||||||
- [Binding properties and bindable dataclasses](https://www.nicegui.io/documentation/section_binding_properties)
|
- [Binding properties and bindable dataclasses](https://www.nicegui.io/documentation/section_binding_properties)
|
||||||
- [Action events](https://www.nicegui.io/documentation/section_action_events)
|
- [Action events](https://www.nicegui.io/documentation/section_action_events)
|
||||||
- [Security best practices](https://www.nicegui.io/documentation/section_security)
|
- [Security best practices](https://www.nicegui.io/documentation/section_security)
|
||||||
@@ -19,6 +21,21 @@ Use these links to verify framework-specific behavior before relying on version-
|
|||||||
- [Server-sent events](https://fastapi.tiangolo.com/advanced/server-sent-events/)
|
- [Server-sent events](https://fastapi.tiangolo.com/advanced/server-sent-events/)
|
||||||
- [WebSockets](https://fastapi.tiangolo.com/advanced/websockets/)
|
- [WebSockets](https://fastapi.tiangolo.com/advanced/websockets/)
|
||||||
|
|
||||||
|
## ASGI And Uvicorn
|
||||||
|
|
||||||
|
!!! info "Server and lifespan sources"
|
||||||
|
- [ASGI lifespan protocol](https://asgi.readthedocs.io/en/latest/specs/lifespan.html)
|
||||||
|
- [Uvicorn settings](https://www.uvicorn.org/settings/)
|
||||||
|
- [Uvicorn programmatic startup](https://www.uvicorn.org/#running-programmatically)
|
||||||
|
- [Uvicorn deployment](https://www.uvicorn.org/deployment/)
|
||||||
|
|
||||||
|
## uv And Project Scripts
|
||||||
|
|
||||||
|
!!! info "Packaging and command sources"
|
||||||
|
- [uv project entry points](https://docs.astral.sh/uv/concepts/projects/config/#entry-points)
|
||||||
|
- [uv project packaging](https://docs.astral.sh/uv/concepts/projects/config/#project-packaging)
|
||||||
|
- [PyPA entry points specification](https://packaging.python.org/en/latest/specifications/entry-points/)
|
||||||
|
|
||||||
## Styling
|
## Styling
|
||||||
|
|
||||||
!!! info "Styling sources"
|
!!! info "Styling sources"
|
||||||
|
|||||||
Reference in New Issue
Block a user