亲身体验 FastUI:用 Python 快速构建美观的用户界面
最近,我有幸接触到一个非常有趣的 Python 库 FastUI,它是一个简单但强大的框架,可以帮助我们快速构建用户界面(UI)。作为一名 Python 开发者,UI 开发一直让我有点头疼,特别是当需要处理复杂交互或者界面设计的时候。而 FastUI 的出现给了我一种全新的体验,它简化了创建 UI 的流程,同时保持了足够的灵活性。
想象一下,只需定义python后端模型,前端界面和交互功能交给FastUI 自动完成,这样会给我们带来怎样的惊喜!
1. 初识 FastUI
第一次听说 FastUI,我立刻被它的简单性和强大的潜力吸引住了。这个框架是基于 Pydantic 的,Pydantic 大家可能都不陌生,是一个非常棒的数据验证和解析库。而 FastUI 则利用 Pydantic 的模型定义能力,将其应用到 UI 开发中,这让整个框架变得非常简洁。
安装 FastUI 也非常方便,只需一个命令:
pip install fastui
安装完后,我就迫不及待地开始试验了。让我兴奋的是,不管是创建表单、输入框,还是复杂的界面布局,FastUI 的代码都极其简洁。比如说,我们定义一个简单但完整的 FastAPI 应用程序,它使用 FastUI 显示一些用户配置文件:
简单的示例
from datetime import date
from fastapi import FastAPI, HTTPException
from fastapi.responses import HTMLResponse
from fastui import FastUI, AnyComponent, prebuilt_html, components as c
from fastui.components.display import DisplayMode, DisplayLookup
from fastui.events import GoToEvent, BackEvent
from pydantic import BaseModel, Field
app = FastAPI()
class User(BaseModel):
id: int
name: str
dob: date = Field(title='Date of Birth')
# define some users
users = [
User(id=1, name='John', dob=date(1990, 1, 1)),
User(id=2, name='Jack', dob=date(1991, 1, 1)),
User(id=3, name='Jill', dob=date(1992, 1, 1)),
User(id=4, name='Jane', dob=date(1993, 1, 1)),
]
@app.get("/api/", response_model=FastUI, response_model_exclude_none=True)
def users_table() -> list[AnyComponent]:
"""
Show a table of four users, `/api` is the endpoint the frontend will connect to
when a user visits `/` to fetch components to render.
"""
return [
c.Page( # Page provides a basic container for components
components=[
c.Heading(text='Users', level=2), # renders `Users
`
c.Table(
data=users,
# define two columns for the table
columns=[
# the first is the users, name rendered as a link to their profile
DisplayLookup(field='name', on_click=GoToEvent(url='/user/{id}/')),
# the second is the date of birth, rendered as a date
DisplayLookup(field='dob', mode=DisplayMode.date),
],
),
]
),
]
@app.get("/api/user/{user_id}/", response_model=FastUI, response_model_exclude_none=True)
def user_profile(user_id: int) -> list[AnyComponent]:
"""
User profile page, the frontend will fetch this when the user visits `/user/{id}/`.
"""
try:
user = next(u for u in users if u.id == user_id)
except StopIteration:
raise HTTPException(status_code=404, detail="User not found")
return [
c.Page(
components=[
c.Heading(text=user.name, level=2),
c.Link(components=[c.Text(text='Back')], on_click=BackEvent()),
c.Details(data=user),
]
),
]
@app.get('/{path:path}')
async def html_landing() -> HTMLResponse:
"""Simple HTML page which serves the React app, comes last as it matches all paths."""
return HTMLResponse(prebuilt_html(title='FastUI Demo'))
这段代码展示了 FastUI 的简单性。你只需要定义一些界面元素,FastUI 就会自动生成相应的用户界面。当我第一次运行这段代码时,看到简洁而美观的界面时,那种成就感让我觉得,构建用户界面其实也没有那么难嘛!
2. 我为什么喜欢 FastUI?
2.1 代码简单易读
我喜欢 FastUI 的一个主要原因就是它的代码结构非常简洁和直观。不需要繁琐的配置,也不需要学习复杂的 UI 架构,只要熟悉 Python,就可以很快上手。这对于像我这样的开发者来说,真的是一大福音,尤其是在处理那些并非前端为主的项目时。
所有的 UI 元素都是以组件的形式组织起来的,例如按钮(Button)、输入框(TextInput)、选择框(Select)等。每个组件都有自己独特的属性,比如文本、提示、颜色等,这让我可以灵活地设计用户界面。
2.2 Pydantic 的强大结合
因为 FastUI 是基于 Pydantic 的,所以它支持通过 Pydantic 的模型定义和验证用户输入。比如,如果你有一个用户注册表单,你可以直接定义 Pydantic 模型来验证用户输入的数据格式,这大大简化了处理表单数据的流程。
class User(BaseModel):
id: int
name: str
dob: date = Field(title='Date of Birth')
你会发现,数据的解析、验证和处理变得非常自然,几乎没有多余的代码。而且如果输入不符合定义的规则,FastUI 会自动给用户反馈错误信息,这让应用程序的交互体验更加流畅。
2.3 灵活的界面设计
FastUI 允许我们通过简单的组合来构建各种复杂的界面。我曾经使用 Tkinter 和其他 GUI 库,但经常因为布局和设计浪费不少时间。而在 FastUI 里,所有 UI 元素都可以很方便地排列和组合。你可以用栅格、表格布局等方式让界面内容更加有条理。
举个例子,我可以用栅格系统设计一个复杂的界面布局,处理输入、按钮、表单等元素,代码仍然保持简单。
@app.get("/api/", response_model=FastUI, response_model_exclude_none=True)
def users_table() -> list[AnyComponent]:
"""
Show a table of four users, `/api` is the endpoint the frontend will connect to
when a user visits `/` to fetch components to render.
"""
return [
c.Page( # Page provides a basic container for components
components=[
c.Heading(text='Users', level=2), # renders `Users
`
c.Table(
data=users,
# define two columns for the table
columns=[
# the first is the users, name rendered as a link to their profile
DisplayLookup(field='name', on_click=GoToEvent(url='/user/{id}/')),
# the second is the date of birth, rendered as a date
DisplayLookup(field='dob', mode=DisplayMode.date),
],
),
]
),
]
这种直观的布局方式,让我可以非常方便地构建复杂的界面,而且代码依然保持简洁。
3. 应用场景
在日常开发中,FastUI 特别适合用来开发那些需要简单交互的应用程序,比如:
- 数据输入表单:通过 Pydantic 的模型验证,可以快速搭建数据录入和验证的表单。
- 内部工具:如果你需要为团队或公司开发一些内部工具,FastUI 可以帮助你快速搭建一个界面友好的应用,省去前端开发的麻烦。
- 轻量级桌面应用:虽然它并不是为桌面应用专门设计的,但在一些简单的桌面应用中,FastUI 也能轻松胜任。
4. 个人总结
从我自己的体验来看,FastUI 是一个非常适合想快速上手并构建简洁 UI 应用的开发者工具。它不仅仅是一个 UI 框架,它充分利用了 Python 语言的简洁性和 Pydantic 的强大验证能力,帮助我们在开发用户界面时减少不必要的繁琐工作。
当然,FastUI 还处于相对早期的开发阶段,功能可能不像一些成熟的框架那样丰富,但它的极简设计和高效的开发体验,已经让它成为我未来考虑构建小型项目时的首选工具之一。
如果你和我一样,对 Python UI 开发感兴趣,或者正在寻找一种快速实现用户界面的方法,FastUI 值得你尝试。相信我,它会让你感受到 UI 开发的另一种乐趣!
你有没有使用过 FastUI 或其他类似的工具呢?你觉得它有哪些潜在的应用场景?欢迎大家一起交流!