王培顺的博客&WangPeishun’s Blog

以下是一份详细的 Python Reflex 使用手册,包含核心概念、组件使用和代码示例:

Python Reflex 全栈开发手册

目录

  1. 框架简介
  2. 环境配置
  3. 项目结构
  4. 核心概念
  5. 组件系统
  6. 状态管理
  7. 路由系统
  8. 样式处理
  9. API 集成
  10. 部署指南

框架简介

Reflex 是一个基于 React 的纯 Python 全栈框架,特点:

  • 实时前端更新
  • 自动处理客户端-服务器通信
  • 支持响应式布局
  • 内置组件库
  • 基于 FastAPI 的后端

环境配置

安装要求

  • Python 3.7+
  • Node.js 16+
  • # 创建虚拟环境
  • python -m venv reflex_env
  • source reflex_env/bin/activate # Linux/Mac
  • reflex_env\Scripts\activate # Windows
  • # 安装框架
  • pip install reflex

项目结构

  • my_app/
  • ├── my_app/ # 主包
  • │ ├── __init__.py # 项目初始化
  • │ └── my_app.py # 主应用文件
  • ├── assets/ # 静态资源
  • ├── .env # 环境变量
  • └── requirements.txt # 依赖列表

核心概念

基本应用结构

  • import reflex as rx
  • class State(rx.State):
  • """应用状态定义"""
  • def index():
  • """页面组件定义"""
  • return rx.container(
  • rx.heading("欢迎使用Reflex"),
  • rx.text("当前状态:", State.text_var)
  • )
  • app = rx.App()
  • app.add_page(index, route="/") # 注册页面
  • app.compile() # 编译应用

组件系统

基础组件使用

  • def form_example():
  • return rx.vstack(
  • rx.input(
  • placeholder="输入姓名",
  • on_change=State.set_name, # 绑定状态变更
  • width="300px"
  • ),
  • rx.button(
  • "提交",
  • on_click=State.handle_submit,
  • color_scheme="blue"
  • ),
  • rx.divider(),
  • rx.text("您输入的是:", State.name)
  • )

布局组件

  • def responsive_layout():
  • return rx.responsive_grid(
  • rx.box("左侧内容", bg="blue.100", p=4, col_span=2),
  • rx.box("右侧内容", bg="green.100", p=4),
  • columns=[1, 2, 3], # 响应式列数
  • spacing="4"
  • )

状态管理

基础状态类

  • class CounterState(rx.State):
  • count: int = 0 # 自动响应式变量
  • def increment(self):
  • self.count += 1
  • def decrement(self):
  • self.count -= 1
  • def counter():
  • return rx.hstack(
  • rx.button("-", on_click=CounterState.decrement),
  • rx.text(CounterState.count),
  • rx.button("+", on_click=CounterState.increment),
  • align="center"
  • )

复杂状态管理

  • class FormState(rx.State):
  • username: str = ""
  • password: str = ""
  • submitted: bool = False
  • def handle_submit(self):
  • self.submitted = True
  • yield [rx.set_value("password", "")] # 清除密码字段
  • @rx.var
  • def form_valid(self) -> bool:
  • return len(self.username) > 3 and len(self.password) > 6

路由系统

多页面配置

  • def about_page():
  • return rx.box(rx.heading("关于我们"), rx.link("返回首页", href="/"))
  • app = rx.App()
  • app.add_page(index, route="/")
  • app.add_page(about_page, route="/about")

动态路由

  • class PostState(rx.State):
  • @rx.var
  • def post_id(self) -> str:
  • return self.router.page.params.get("id", "0")
  • def post_detail():
  • return rx.vstack(
  • rx.heading(f"文章ID:{PostState.post_id}"),
  • rx.text("动态路由参数示例")
  • )
  • app.add_page(
  • post_detail,
  • route="/posts/[id]",
  • on_load=PostState.load_post # 页面加载时触发
  • )

样式处理

Tailwind CSS 集成

  • rx.box(
  • "样式示例",
  • class_name="p-4 bg-blue-500 rounded-lg shadow-lg",
  • _hover={"transform": "scale(1.05)"}
  • )

全局样式配置

  • app = rx.App(
  • style={
  • "font_family": "Inter",
  • "theme": rx.theme(
  • appearance="dark", # 暗黑模式
  • has_backdrop=True
  • )
  • }
  • )

API 集成

后端路由定义

  • import requests
  • class APICallState(rx.State):
  • data: dict = {}
  • loading: bool = False
  • async def fetch_data(self):
  • self.loading = True
  • yield
  • response = requests.get("https://api.example.com/data")
  • self.data = response.json()
  • self.loading = False
  • def api_example():
  • return rx.cond(
  • APICallState.loading,
  • rx.spinner(),
  • rx.json(data=APICallState.data)
  • )

部署指南

生产环境配置

  • # 安装生产依赖
  • pip install gunicorn uvicorn
  • # 设置环境变量
  • export REFLEX_ENV=production

Docker 部署

  • FROM python:3.9-slim
  • WORKDIR /app
  • COPY . .
  • RUN pip install --no-cache-dir -r requirements.txt
  • CMD ["reflex", "run", "--host", "0.0.0.0", "--port", "80"]

完整示例:待办事项应用

  • class TodoState(rx.State):
  • items: list[str] = ["学习Reflex"]
  • new_item: str = ""
  • def add_item(self):
  • if self.new_item.strip():
  • self.items.append(self.new_item)
  • self.new_item = ""
  • def delete_item(self, item: str):
  • self.items.remove(item)
  • def todo_list():
  • return rx.container(
  • rx.heading("待办事项"),
  • rx.input(
  • value=TodoState.new_item,
  • on_change=TodoState.set_new_item,
  • placeholder="添加新事项"
  • ),
  • rx.button("添加", on_click=TodoState.add_item),
  • rx.vstack(
  • rx.foreach(
  • TodoState.items,
  • lambda item: rx.hstack(
  • rx.text(item),
  • rx.button(
  • "删除",
  • on_click=lambda: TodoState.delete_item(item)
  • )
  • )
  • ),
  • spacing="2"
  • ),
  • max_width="600px",
  • padding="2rem"
  • )

最佳实践

  1. 使用小型状态类管理不同功能模块
  2. 优先使用内置组件保持一致性
  3. 合理使用 rx.foreach 处理列表数据
  4. 通过 @rx.var 创建计算属性
  5. 使用 rx.cond 处理条件渲染
  6. 为复杂组件创建自定义组件
  7. 定期运行 reflex db migrate 管理数据库变更

常见问题

Q: 如何调试状态变更?
A: 在开发模式下运行时,访问 /state 查看当前状态

Q: 如何自定义404页面?
A: 添加 app.add_page(not_found, route="/404")

Q: 如何集成第三方React组件?
A: 使用 rx.chakra 命名空间或创建自定义组件


本手册覆盖了Reflex的核心功能,建议通过官方文档和示例项目深入学习更高级的用法。

标签: none

添加新评论