首页
/ FastUI 作为 FastAPI 子应用的实现方案

FastUI 作为 FastAPI 子应用的实现方案

2025-05-26 09:51:27作者:毕习沙Eudora

在 FastAPI 项目中集成 FastUI 作为子应用是一个常见的需求,特别是在需要为现有 API 添加管理界面时。本文将详细介绍如何正确地将 FastUI 挂载为 FastAPI 的子应用。

核心实现思路

FastUI 作为子应用有两种主要实现方式:

  1. 独立 FastAPI 应用挂载方式
    创建一个独立的 FastAPI 应用实例,然后通过主应用的 mount 方法挂载。这种方式适合需要完全隔离的子应用场景。

  2. 路由挂载方式
    使用 FastAPI 的 APIRouter 创建 UI 相关路由,然后通过 include_router 方法挂载到主应用。这种方式更加轻量,适合大多数场景。

实现细节

独立应用挂载方式

from fastapi import FastAPI
from fastui import FastUI, AnyComponent, prebuilt_html
from fastapi.responses import HTMLResponse

# 创建子应用
fastui_app = FastAPI()

@fastui_app.get("/api/", response_model=FastUI, response_model_exclude_none=True)
def ui_endpoint() -> list[AnyComponent]:
    return [
        c.Page(
            components=[
                c.Heading(text='FastUI 子应用', level=2)
            ]
        )
    ]

@fastui_app.get('/{path:path}')
async def html_landing() -> HTMLResponse:
    return HTMLResponse(prebuilt_html(title='FastUI 子应用'))

# 主应用
main_app = FastAPI()
main_app.mount("/ui", fastui_app)

路由挂载方式(推荐)

from fastapi import APIRouter, FastAPI
from fastui import FastUI, AnyComponent, prebuilt_html
from fastapi.responses import HTMLResponse

# 创建UI路由
ui_router = APIRouter()

@ui_router.get("/api/", response_model=FastUI)
async def ui_endpoint():
    return [
        c.Page(
            components=[
                c.Heading(text='FastUI 路由', level=2)
            ]
        )
    ]

@ui_router.get('/{path:path}')
async def html_landing():
    return HTMLResponse(prebuilt_html(title='FastUI 路由'))

# 主应用
app = FastAPI()
app.include_router(ui_router, prefix='/ui')

关键注意事项

  1. 路由匹配顺序
    FastUI 需要两个关键路由:一个处理 API 请求(通常为 /api/),一个处理页面请求(通配路由 /{path:path})。确保这两个路由定义正确。

  2. 响应模型
    API 路由必须指定 response_model=FastUI,这样才能正确序列化返回的组件。

  3. HTML 响应
    通配路由需要使用 prebuilt_html 生成基础 HTML 结构,这是 FastUI 前端渲染的基础。

  4. 前缀处理
    使用路由方式时,prefix 参数会自动为所有路由添加前缀,比手动拼接路径更可靠。

最佳实践建议

  1. 对于大多数项目,推荐使用路由挂载方式,它更简单且性能更好。

  2. 如果子应用需要完全独立的中间件、异常处理等,才考虑使用独立应用挂载方式。

  3. 将 UI 相关路由组织在单独的文件中,保持项目结构清晰。

  4. 考虑为生产环境添加适当的缓存头,提升静态资源加载性能。

通过以上方案,开发者可以灵活地将 FastUI 集成到现有 FastAPI 项目中,无论是作为独立子应用还是作为路由组,都能获得良好的开发体验。

登录后查看全文
热门项目推荐
相关项目推荐