# Home Automation Backend 这是当前 `home-automation` 项目的 Python 重构基础骨架。当前仓库仍保留 Go 版本作为事实基线,而这个 Python 部分的目标是为后续逐模块迁移提供稳定工程基础。 为便于清理仓库,重构开始前就存在的 Go 实现和相关资产已经统一移动到 `legacy/go-backend/`。这样在 Python 重构完成后,可以按目录整体删除旧实现。 当前阶段只包含: - FastAPI 基础应用骨架 - 环境变量配置体系 - SQLite + SQLAlchemy + Alembic 基础设施 - 极简 server-side templates - pytest 测试基础 - OpenAPI 导出脚本 - Docker / Compose 基础骨架 当前阶段明确不包含: - TickTick 业务逻辑迁移 - Home Assistant 业务逻辑迁移 - poo records 业务迁移 - location / life trajectory 业务迁移 - Notion 模块 Notion 在 Go 版本中仍然存在,但已被明确视为 legacy / removed scope,不进入新的 Python 系统目标。 旧 Go 代码位置: - `legacy/go-backend/src/` - `legacy/go-backend/helper/` - `legacy/go-backend/.github/workflows/` ## 当前目录 Python 骨架的主要目录如下: - `app/`: FastAPI 应用代码 - `alembic/`: Alembic migration 环境 - `tests/`: pytest 测试 - `docs/`: 架构说明与迁移文档 - `scripts/`: 辅助脚本,例如 OpenAPI 导出 ## 依赖管理 项目现在采用 `pip-tools` 管理依赖: - 生产依赖源文件:`requirements.in` - 开发依赖源文件:`dev-requirements.in` - 编译产物: - `requirements.txt` - `dev-requirements.txt` 更新依赖时建议使用: ```bash python -m venv .venv source .venv/bin/activate pip install pip-tools pip-compile requirements.in pip-compile dev-requirements.in ``` 如果要升级某个依赖,可以用: ```bash pip-compile --upgrade-package fastapi requirements.in pip-compile dev-requirements.in ``` ## 本地启动 建议使用 Python 3.11 或以上版本。 1. 创建虚拟环境并安装依赖 ```bash python -m venv .venv source .venv/bin/activate pip install -r dev-requirements.txt ``` 2. 准备环境变量 ```bash cp .env.example .env ``` 3. 启动服务 ```bash uvicorn app.main:app --reload --host 0.0.0.0 --port 8000 ``` 启动后可访问: - 应用首页:`http://localhost:8000/` - 健康检查:`http://localhost:8000/status` - Swagger UI:`http://localhost:8000/docs` - ReDoc:`http://localhost:8000/redoc` ## 数据库与 Alembic 当前默认数据库使用 SQLite。 - 默认数据库地址:`sqlite:///./data/app.db` - 数据目录:`./data/` 初始化 migration 环境后,可继续添加模型并生成迁移: ```bash alembic revision --autogenerate -m "init tables" alembic upgrade head ``` 这一轮尚未引入业务表,因此 Alembic 目前主要是基础设施就绪状态。 ## 运行测试 ```bash pytest ``` 当前测试包含: - app 基本启动测试 - `/status` endpoint 测试 ## OpenAPI 导出 FastAPI 默认会暴露 OpenAPI。若需要导出静态 schema 文件,可运行: ```bash python scripts/export_openapi.py ``` 输出文件会写到: - `openapi/openapi.json` - `openapi/openapi.yaml` ## 容器启动 1. 准备环境变量文件 ```bash cp .env.example .env ``` 2. 启动容器 ```bash docker compose up --build ``` 默认端口: - `8000:8000` SQLite 持久化目录: - 本地 `./data` - 容器内 `/app/data` ## 后续迁移建议 后续可以在当前骨架上逐步迁移这些模块: - TickTick integration - Home Assistant integration - poo records - location / life trajectory 建议继续参考: - [当前系统盘点](docs/current-system-inventory.md) - [Python 重构方案](docs/python-rewrite-plan.md) - [迁移风险清单](docs/migration-risks.md)