集成 NiceGUI#
from fastapi import FastAPI
from nicegui import app as gui, ui
定义简单的 ui
:
@ui.page('/')
def show():
ui.label('Hello, FastAPI!')
# NOTE 深色模式将为每个用户在标签页和服务器重启之间保持持久
ui.dark_mode().bind_value(gui.storage.user, 'dark_mode')
ui.checkbox('dark mode').bind_value(gui.storage.user, 'dark_mode')
将 ui
附加到 app
:
app = FastAPI()
ui.run_with(
app,
mount_path='/gui', # NOTE 如果你希望传递给 `@ui.page` 的路径位于根目录,这个可以省略
storage_secret='在这里选择你的私人密钥', # NOTE 设置密钥是可选的,但允许每个用户进行持久存储。
)
最后按照普通运行 app
的方式运行即可。
附加 dash
到 ui
#
你可能需要把 Dash 集成到 ui
,只需要,在定义 app
之前添加如下代码即可:
from fastapi.middleware.wsgi import WSGIMiddleware
dash_app = create_dash_app(requests_pathname_prefix="/dash")
gui.mount("/dash", WSGIMiddleware(dash_app.server))
其中 create_dash_app
可以这样写:
import sys
import io
from pathlib import Path
import toml
import numpy as np
import dash
from dash import dcc, html
from dash.dependencies import Input, Output, State
from d2py.tools.dashstyle.server import create_app, run_server
def create_dash_app(requests_pathname_prefix: str = None) -> dash.Dash:
app = create_app(
__name__,
use_pages=True,
eager_loading=True, # 修复 dash.exceptions.DependencyException: Error loading dependency. "plotly" is not a registered library.
requests_pathname_prefix=requests_pathname_prefix)
app.scripts.config.serve_locally = False
dcc._js_dist[0]['external_url'] = 'https://cdn.plot.ly/plotly-basic-latest.min.js'
app.layout = html.Article([
html.H1('工具', className="w3-center"),
html.Header([
html.Div(
dcc.Link(f"{page['name']}", href=page["relative_path"]), className="w3-bar-item w3-button")
for page in dash.page_registry.values()
], className="w3-bar w3-light-grey"),
dash.page_container,
], className="w3-container w3-pale-yellow", style={"height": "800px", "width": "100%"})
return app
创建具有分页功能的 dash
子页面。