fb0a53676fcaf0321a3dca91f4b6ec49402948d7
TodoList 全栈项目(FastAPI + MySQL)
这是一个用于学习后端开发的 TodoList 项目。前端由 Nginx 提供,/api 请求反向代理到 FastAPI,FastAPI 使用参数化 SQL 读写 Docker 中的 MySQL 8.4。
架构
浏览器
-> Windows 局域网端口 8080(当前环境使用端口转发)
-> WSL Nginx :80
-> FastAPI/Uvicorn 127.0.0.1:8000
-> MySQL 127.0.0.1:3306
目录
main.py FastAPI 后端
frontend/index.html 前端页面
compose.yaml MySQL Docker Compose 配置
schema.sql 数据库建表脚本
requirements.txt Python 依赖及版本
.env.example 环境变量示例(不含真实密码)
deploy/nginx-todolist.conf Nginx 站点配置
deploy/todolist.service systemd 服务配置
验收记录.md 已完成测试和已知限制
环境要求
- Windows + WSL2 Ubuntu(当前部署方式)
- Python 3.12 或兼容版本
- Docker Engine 与 Docker Compose 插件
- Nginx
- systemd(用于后台运行 FastAPI)
1. 准备 Python 环境
cd /home/dwh/code/fastapi_todolist
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements.txt
如果部署用户或目录不同,需要同步修改 deploy/todolist.service 中的 User、WorkingDirectory 和 ExecStart。
2. 准备环境变量
cp .env.example .env
chmod 600 .env
vim .env
请替换两个密码占位符。不要提交或对外发送真实 .env。
3. 启动 MySQL 并建表
docker compose up -d
docker compose ps
首次创建数据卷后执行建表脚本:
docker compose exec -T mysql sh -lc 'exec mysql -u"$MYSQL_USER" -p"$MYSQL_PASSWORD" "$MYSQL_DATABASE"' < schema.sql
MySQL 端口仅绑定到 127.0.0.1:3306,不会直接暴露给局域网。
4. 安装前端与 Nginx 配置
sudo mkdir -p /var/www/todolist
sudo cp frontend/index.html /var/www/todolist/index.html
sudo cp deploy/nginx-todolist.conf /etc/nginx/sites-available/todolist
sudo ln -s /etc/nginx/sites-available/todolist /etc/nginx/sites-enabled/todolist
sudo nginx -t
sudo systemctl restart nginx
若 /etc/nginx/sites-enabled/default 与交付配置同时声明 default_server,请先停用默认站点或去掉其中一方的 default_server。
5. 安装 FastAPI systemd 服务
sudo cp deploy/todolist.service /etc/systemd/system/todolist.service
sudo systemctl daemon-reload
sudo systemctl enable --now todolist.service
sudo systemctl status todolist.service --no-pager -l
6. 验证
直连 FastAPI:
curl http://127.0.0.1:8000/health
curl http://127.0.0.1:8000/todos
通过 Nginx:
curl http://127.0.0.1/
curl http://127.0.0.1/api/todos
当前测试环境的 Windows 局域网入口为 http://192.168.10.55:8080。该地址属于环境配置,不应视为固定生产地址。
API
| 方法 | 路径 | 说明 |
|---|---|---|
| GET | /health |
健康检查 |
| GET | /todos |
获取全部任务 |
| POST | /todos |
新增任务 |
| PATCH | /todos/{todo_id} |
修改任务文字或完成状态 |
| DELETE | /todos/{todo_id} |
删除任务 |
Nginx 对外使用 /api 前缀,例如浏览器访问 /api/todos,代理到 FastAPI 的 /todos。
安全说明
- 所有带用户数据的 SQL 均使用参数化查询,不使用 f-string 拼接。
.env和 MySQL 数据卷不在交付包内。- 交付包中的
.env.example只有占位符。
Languages
Python
58.6%
HTML
22.3%
Shell
17%
Mako
2.1%