python中FastUI使用详解及案例_python .flat
一、FastUI简介
FastUI是一个基于Python的声明式Web应用界面开发框架,它允许开发者使用纯Python代码构建响应式Web应用,无需编写JavaScript或处理npm等前端工具。FastUI的核心理念是通过Pydantic模型和TypeScript接口定义用户界面,实现前后端的真正分离。
核心特点
声明式开发:使用Python代码定义UI组件,无需编写JavaScript
类型安全:结合Pydantic和TypeScript进行类型检查和验证
与FastAPI无缝集成:可快速构建完整的Web应用
丰富的组件库:提供Page、Heading、Table、Text等常用UI组件
预构建前端:通过CDN提供预构建的React应用,无需配置前端环境
二、安装与环境配置
安装FastUI
使用pip命令安装FastUI:
1pip install fastui
安装依赖
FastUI通常与FastAPI和Uvicorn一起使用:
1pip install fastapi uvicorn
三、核心概念与组件
1. 基本架构
FastUI由四个主要部分组成:
fastui PyPI包:包含UI组件的Pydantic模型和工具函数
@pydantic/fastui npm包:React TypeScript包,用于实现自定义组件
@pydantic/fastui-bootstrap npm包:使用Bootstrap实现的FastUI组件
@pydantic/fastui-prebuilt npm包:预构建的React应用,可通过CDN使用
2. 常用组件
FastUI提供了丰富的UI组件,以下是一些常用组件:
Page:提供基本的组件容器
Heading:标题组件,支持不同级别
Table:数据表格组件,支持排序和筛选
Text:文本显示组件
Link:链接组件
Details:详细信息展示组件
四、快速入门示例
创建简单FastUI应用
以下是一个基本的FastUI应用示例,使用FastAPI作为后端:
1from fastapi import FastAPI
2from fastapi.responses import HTMLResponse
3from fastui import FastUI, AnyComponent, prebuilt_html, components as c
4
5app = FastAPI()
6
7@app.get("/", response_class=HTMLResponse)
8async def root():
9 return prebuilt_html(title='FastUI Demo')
10
11@app.get("/api/", response_model=FastUI)
12def api() -> list[AnyComponent]:
13 return [
14 c.Page(
15 components=[
16 c.Heading(text='Hello, FastUI!', level=1),
17 c.Text(text='这是一个简单的FastUI应用示例。')
18 ]
19 )
20 ]
21
22# 运行应用:uvicorn main:app --reload
运行上述代码后,访问http://192.168.1.1:8000即可看到简单的FastUI页面。
五、具体案例
案例1:用户管理系统
以下示例展示如何创建一个简单的用户管理系统,包含用户列表和用户详情页面:
1from datetime import date
2from fastapi import FastAPI, HTTPException
3from fastapi.responses import HTMLResponse
4from fastui import FastUI, AnyComponent, prebuilt_html, components as c
5from fastui.components.display import DisplayMode, DisplayLookup
6from fastui.events import GoToEvent, BackEvent
7from pydantic import BaseModel, Field
8
9app = FastAPI()
10
11# 定义用户模型
12class User(BaseModel):
13 id: int
14 name: str
15 dob: date = Field(title='出生日期')
16
17# 模拟用户数据
18users = [
19 User(id=1, name='张三', dob=date(1990, 1, 1)),
20 User(id=2, name='李四', dob=date(1991, 5, 15)),
21 User(id=3, name='王五', dob=date(1992, 9, 30)),
22 User(id=4, name='赵六', dob=date(1993, 3, 22)),
23]
24
25# 用户列表页面
26@app.get("/api/", response_model=FastUI, response_model_exclude_none=True)
27def users_table() -> list[AnyComponent]:
28 return [
29 c.Page(
30 components=[
31 c.Heading(text='用户列表', level=2),
32 c.Table(
33 data=users,
34 columns=[
35 DisplayLookup(field='name', on_click=GoToEvent(url='/user/{id}/')),
36 DisplayLookup(field='dob', mode=DisplayMode.date),
37 ],
38 ),
39 ]
40 ),
41 ]
42
43# 用户详情页面
44@app.get("/api/user/{user_id}/", response_model=FastUI, response_model_exclude_none=True)
45def user_profile(user_id: int) -> list[AnyComponent]:
46 try:
47 user = next(u for u in users if u.id == user_id)
48 except StopIteration:
49 raise HTTPException(status_code=404, detail="用户不存在")
50
51 return [
52 c.Page(
53 components=[
54 c.Heading(text=user.name, level=2),
55 c.Link(components=[c.Text(text='返回')], on_click=BackEvent()),
56 c.Details(data=user),
57 ]
58 ),
59 ]
60
61# 提供HTML页面
62@app.get("/{path:path}", response_class=HTMLResponse)
63async def html_landing() -> HTMLResponse:
64 return prebuilt_html(title='用户管理系统')
65
66# 运行应用:uvicorn user_management:app --reload
案例2:简单计数器应用
以下示例展示如何创建一个带有交互功能的计数器应用:
1from fastapi import FastAPI
2from fastapi.responses import HTMLResponse
3from fastui import FastUI, AnyComponent, prebuilt_html, components as c
4from fastui.events import PageEvent
5
6app = FastAPI()
7
8# 全局状态 - 计数器
9counter = 0
10
11@app.get("/", response_class=HTMLResponse)
12async def root():
13 return prebuilt_html(title='FastUI Counter Demo')
14
15@app.get("/api/", response_model=FastUI)
16def counter_app() -> list[AnyComponent]:
17 global counter
18 return [
19 c.Page(
20 components=[
21 c.Heading(text=f'计数器: {counter}', level=1),
22 c.Button(
23 text='增加',
24 on_click=PageEvent(name='increment'),
25 ),
26 c.Button(
27 text='减少',
28 on_click=PageEvent(name='decrement'),
29 ),
30 ]
31 )
32 ]
33
34# 处理计数器事件
35@app.post("/api/events/increment")
36def increment_counter():
37 global counter
38 counter += 1
39 return {'status': 'ok'}
40
41@app.post("/api/events/decrement")
42def decrement_counter():
43 global counter
44 counter -= 1
45 return {'status': 'ok'}
46
47# 运行应用:uvicorn counter:app --reload
六、最佳实践
1. 组件复用
尽量使用FastUI提供的预构建组件,减少重复代码。例如,使用Table组件展示数据而不是手动创建HTML表格。
2. 类型安全
充分利用Pydantic和TypeScript的类型检查功能,确保数据模型的一致性和正确性。
3. 前后端分离
遵循FastUI的设计理念,保持前端只负责UI展示,后端处理业务逻辑和数据。
4. 模块化设计
将应用拆分为多个模块,每个模块负责特定功能,提高代码的可维护性。
七、总结
FastUI为Python开发者提供了一种简单高效的方式来构建Web用户界面,通过声明式Python代码和类型安全的设计,大大简化了Web应用的开发流程。结合FastAPI等后端框架,可以快速构建功能完善、交互丰富的Web应用。
随着FastUI生态系统的不断发展,它有望成为Python Web开发的重要工具之一。对于需要快速开发内部工具、管理系统或数据可视化平台的开发者来说,FastUI是一个值得尝试的选择。
参考资料
FastUI官方文档:
https://docs.pydantic.dev/fastui/
FastUI GitHub仓库:
https://github.com/pydantic/FastUI
FastUI PyPI页面:
https://pypi.org/project/fastui/