moujitx 9c32571560 fix(backend): keep third-party loggers quiet while DEBUG is on
With the shipped local default (DEBUG=true) the root logger was set to DEBUG, so
aiosqlite printed every cursor operation and the console became unreadable
(hundreds of lines per request).

- only the `app` namespace follows DEBUG; the root logger stays at INFO
- SQLAlchemy / aiosqlite / asyncpg / asyncio are pinned to WARNING, or INFO when
  DB_ECHO is explicitly enabled (the engine already emits SQL at INFO then)
- uvicorn loggers are aligned to INFO and propagate to our handler as before

Observed on the running dev server: startup went from ~40 driver lines to 4
(Starting / Database target / connection established / Application startup
complete) and requests log a single uvicorn.access line.

docs: also document the Windows `--reload` caveat found while verifying: uvicorn
restarts the child with CTRL_C_EVENT, which cannot reach a child in a different
console / redirected-stdio environment, so the reloader prints "Reloading..."
and then blocks in process.join() while the old code keeps serving.

Verification: ruff + ruff format clean, pytest 14 passed, and the fix was proven
in isolation (aiosqlite effective level 30, app 10) and on the restarted server.
2026-10-02 14:03:11 +08:00

FastAPI + Vue 全栈项目模板

一个开箱即用的前后端分离项目骨架:FastAPI 提供 REST 后端,Vue 3 渲染前端, 通过 DATABASE_URL 连接外部 PostgreSQL(或本地 SQLite 快速起步), 并配套 Docker / Docker Compose 打包方案(compose 只编排应用,不托管数据库)。

层次 技术选型
后端 FastAPI 0.142 · Python 3.13 · Pydantic v2 · pydantic-settings
数据库 SQLAlchemy 2.x(全异步)· 外部 PostgreSQL(asyncpg)· SQLite(aiosqlite,本地开发)
迁移 Alembic(异步 env.py,支持 autogenerate)
前端 Vue 3.5 · Vite 6 · TypeScript 5.7 · vue-router 4 · Pinia 3 · axios
包管理器 Yarn 1.22(classic,已提交 yarn.lock)
代码质量 ruff(后端)· ESLint 9 flat config + Prettier(前端)
打包部署 多阶段 Dockerfile(后端非 root 运行)· nginx 托管 SPA 并反向代理 /api · Docker Compose

目录结构

Template/
├── backend/                     # FastAPI 后端
│   ├── app/
│   │   ├── main.py              # 应用工厂 + lifespan(日志 / 建库目录 / DB 探活)
│   │   ├── core/                # config.py(配置)· logging.py(日志)
│   │   ├── db/                  # base.py(Base/TimestampMixin)· session.py(异步引擎/会话依赖)
│   │   ├── models/item.py       # 示例 ORM 模型
│   │   ├── schemas/             # pydantic 请求/响应模型
│   │   ├── api/
│   │   │   ├── deps.py          # SessionDep / SettingsDep
│   │   │   └── v1/endpoints/    # health.py · items.py
│   │   └── cli/wait_for_db.py   # 容器启动等待数据库
│   ├── alembic/                 # 迁移脚本(已含初始迁移)
│   ├── tests/                   # pytest(14 个用例,使用独立 SQLite 临时库)
│   ├── requirements*.txt        # 运行/开发依赖
│   ├── pyproject.toml           # ruff + pytest + coverage 配置
│   ├── Dockerfile               # 多阶段构建,非 root 用户
│   └── docker-entrypoint.sh     # 等库 → alembic upgrade head → uvicorn
├── frontend/                    # Vue 3 前端(Yarn 管理)
│   ├── src/
│   │   ├── api/                 # client.ts(axios 实例)· health.ts · items.ts
│   │   ├── stores/              # Pinia:app(健康状态)· items(CRUD 状态)
│   │   ├── views/               # HomeView · ItemsView(完整 CRUD 示例)· 404
│   │   ├── components/          # AppHeader · AppFooter · StatusBadge
│   │   └── assets/styles/       # 设计变量、明暗主题、布局与组件样式
│   ├── Dockerfile               # node 构建 → nginx 托管
│   ├── nginx.conf               # SPA history 回退 + /api 反向代理
│   └── yarn.lock
├── docker-compose.yml           # backend + frontend 两服务编排(数据库外部提供)
├── .env.example                 # Compose 变量样例(复制为 .env 使用)
└── .editorconfig / .gitattributes / .gitignore

快速开始

方式 A:Docker Compose(推荐,一条命令起全栈)

前置条件:一个已有的 PostgreSQL 实例(compose 只编排 backend + frontend, 不安装数据库)。先在实例中建好库和账号:

CREATE ROLE app LOGIN PASSWORD 'change-me-in-production';
CREATE DATABASE app OWNER app;

然后:

cp .env.example .env          # 关键:把 DATABASE_URL 改成本机/远程实例地址
docker compose up --build -d
docker compose logs -f backend

DATABASE_URL 示例(host.docker.internal = 容器访问宿主机上的数据库):

DATABASE_URL=postgresql+asyncpg://app:change-me-in-production@host.docker.internal:5432/app
# 远程/托管实例
DATABASE_URL=postgresql+asyncpg://app:secret@db.internal.example.com:5432/app

容器启动顺序为:等待数据库可连接 → alembic upgrade head 建表 → 启动 uvicorn。 若实例暂不可达,容器会按 DB_WAIT_TIMEOUT(默认 60s)重试而不是直接退出。

启动后:

地址 说明
http://localhost:8080 Vue 前端(nginx 托管,并把 /api 转发到后端)
http://localhost:8080/docs FastAPI Swagger UI(经 nginx 代理)
http://localhost:8000/api/v1/health 后端健康检查(含数据库连通性)

停止 / 清理(不涉及数据库,外部实例的数据不受影响):

docker compose down           # 停止并删除容器

方式 B:本地开发(前后端热重载)

1. 后端

cd backend
python -m venv .venv
.\.venv\Scripts\Activate.ps1            # Linux/macOS: source .venv/bin/activate
pip install -r requirements-dev.txt
cp .env.example .env                    # 默认使用 SQLite,零配置
alembic upgrade head                    # 建表
uvicorn app.main:app --reload           # http://localhost:8000/docs

2. 前端(另开一个终端)

cd frontend
yarn install
yarn dev                                # http://localhost:5173

Vite 开发服务器会把 /api、/docs、/redoc 代理到 VITE_PROXY_TARGET (默认 http://localhost:8000),因此前端代码里始终使用相对路径 /api/v1。


环境变量

根目录 .env(供 Docker Compose)

变量 默认值 说明
COMPOSE_PROJECT_NAME app 容器/网络前缀
DATABASE_URL postgresql+asyncpg://app:...@host.docker.internal:5432/app 外部数据库连接串(asyncpg 驱动)。host.docker.internal 指宿主机,换成远程实例域名即可;密码含特殊字符需百分号编码
DB_POOL_SIZE / DB_MAX_OVERFLOW 5 / 10 连接池大小(SQLite 忽略)
DB_WAIT_TIMEOUT 60 启动时等待数据库可连接的秒数,超时才失败
BACKEND_PORT 8000 后端映射端口
FRONTEND_PORT 8080 前端映射端口
ENVIRONMENT / DEBUG local / false 运行环境与调试开关
CORS_ORIGINS http://localhost:8080,... 允许的浏览器来源,逗号分隔,* 表示全部
SECRET_KEY change-me-in-production 生产环境务必替换

容器内不需要(也不应该)放数据库凭据文件:DATABASE_URL 通过 compose 环境变量注入,仓库中的 .env 已被 git 忽略。

backend/.env(本地开发)

完整清单见 backend/.env.example,其中数据库部分最关键:

# SQLite(默认,零配置)
DATABASE_URL=sqlite+aiosqlite:///./data/app.db
# 外部 PostgreSQL
DATABASE_URL=postgresql+asyncpg://app:app@localhost:5432/app

只需修改 DATABASE_URL 即可在 SQLite / PostgreSQL 之间切换,业务代码无需改动。 后端会依次读取仓库根目录 .env 与 backend/.env,后者优先;真实环境变量优先级最高。

frontend/.env(本地开发)

VITE_API_BASE_URL=/api/v1        # axios 基础路径
VITE_APP_TITLE=FastAPI + Vue Template
VITE_PROXY_TARGET=http://localhost:8000   # 仅开发期代理目标

API 端点(v1)

方法 路径 说明
GET /api/v1/health 就绪探针:应用信息 + 数据库连通性(不可用时返回 degraded,仍为 200)
GET /api/v1/health/live 存活探针:不访问数据库
GET /api/v1/items 分页列表(limit / offset,返回 total)
POST /api/v1/items 创建,返回 201
GET /api/v1/items/{id} 详情,不存在返回 404
PATCH /api/v1/items/{id} 局部更新(只更新提交的字段)
DELETE /api/v1/items/{id} 删除,返回 204
GET / 服务元信息(名称、版本、文档地址)
GET /docs · /redoc 交互式文档

数据库密码等敏感信息在健康检查响应中会被掩码(user:***@host)。


数据库与迁移

cd backend
alembic upgrade head                          # 应用全部迁移
alembic revision --autogenerate -m "add xxx"  # 依据模型差异生成迁移
alembic downgrade -1                          # 回退一步
alembic current                               # 当前版本
  • 迁移的数据库地址来自应用配置(backend/.env),与 API 运行时完全一致。
  • 新增模型后,记得在 app/models/__init__.py 中导入,autogenerate 才能发现它。
  • SQLite 下已自动启用 render_as_batch,可正常执行 ALTER 类操作。

常用命令

后端

pytest                       # 运行测试(14 passed)
pytest --cov=app --cov-report=term-missing
ruff check .                 # 静态检查
ruff format .                # 格式化

前端(全部通过 Yarn)

yarn dev          # 开发服务器(热更新)
yarn build        # 类型检查 + 生产构建
yarn type-check   # vue-tsc 类型检查
yarn lint         # ESLint(自动修复)
yarn format       # Prettier 格式化
yarn preview      # 预览构建产物

Docker 说明

compose 只编排应用本身,数据库由外部提供:

服务 镜像 端口 说明
backend 本地构建(python:3.13-slim 多阶段) ${BACKEND_PORT} → 8000 非 root 运行;启动时等待外部数据库 → alembic upgrade head → uvicorn
frontend 本地构建(node:22-alpine → nginx:1.27-alpine) ${FRONTEND_PORT} → 80 托管构建产物,/api、/docs、/redoc 反向代理到 backend

连接外部数据库的三种典型场景

数据库位置 DATABASE_URL 写法
宿主机(Windows/macOS/Linux 本机装好的 PostgreSQL) postgresql+asyncpg://user:pass@host.docker.internal:5432/app(compose 已配 extra_hosts: host-gateway,Linux 同样可用)
同一 Docker 网络的其它容器 postgresql+asyncpg://user:pass@db-service:5432/app,并把两个服务加入同一网络
远程 / 云托管实例 postgresql+asyncpg://user:pass@db.example.com:5432/app?ssl=require

凭据不写进仓库:在本地 .env(已被 git 忽略)中设置 DATABASE_URL 即可。

几个实用开关(backend 服务环境变量):

  • WAIT_FOR_DATABASE=false:跳过等待数据库;
  • RUN_MIGRATIONS=false:跳过自动迁移(例如由独立 Job 负责迁移时);
  • 二者都为 false 时,容器只启动 uvicorn,适合调试。

需要临时覆盖 compose 配置(例如换数据库地址、加挂载卷)时,新建一个被 git 忽略的 docker-compose.override.yml:

services:
  backend:
    environment:
      DATABASE_URL: postgresql+asyncpg://user:password@db.example.com:5432/app

扩展一个新模块

  1. backend/app/models/xxx.py 定义 ORM 模型,并在 models/__init__.py 导入;
  2. alembic revision --autogenerate -m "add xxx" && alembic upgrade head;
  3. backend/app/schemas/xxx.py 定义请求/响应模型;
  4. backend/app/api/v1/endpoints/xxx.py 写路由,注册到 api/v1/router.py;
  5. frontend/src/types/index.ts 补类型,src/api/xxx.ts 封装请求;
  6. frontend/src/stores/xxx.ts 管理状态,在 src/views/ 中渲染。

items(后端 CRUD + 前端表格/表单)就是按上述路径实现的最小范例,可直接照抄。


校验状态

本模板在初始化时已实际跑通以下验证:

项目 结果
ruff check / ruff format --check(后端) 通过
pytest(后端 14 用例:健康检查、CRUD、分页、校验失败、数据库不可用降级) 14 passed
Alembic upgrade head → downgrade base → upgrade head(SQLite) 通过,表/索引创建正确
真实 uvicorn 冒烟:/api/v1/health、items 增删查、/docs、OpenAPI 全部 200/正常
yarn install(生成并提交 lockfile) 通过
yarn type-check / yarn build 通过(产物 dist/)
yarn lint:check / yarn format:check 通过
前后端联调:yarn dev + uvicorn,Vite 代理 /api、/docs、/redoc 全部 200
docker-compose.yml 结构校验(YAML 解析、服务/依赖/端口断言、无嵌套变量默认值) 通过
docker-entrypoint.sh 语法(sh -n)与 python -m app.cli.wait_for_db 两条路径 通过

⚠️ 初始化环境未安装 Docker CLI,因此 Dockerfile / docker-compose.yml 只做了上述 静态与脚本级校验,未实际构建镜像、也未连接真实 PostgreSQL 跑通容器链路。 首次使用请执行 docker compose up --build 确认。


常见问题

  • 端口被占用:修改根目录 .env 中的 BACKEND_PORT / FRONTEND_PORT。
  • 后端连不上数据库(容器反复重启 / 日志停在 waiting):确认 .env 里的 DATABASE_URL 指向容器可访问的地址——宿主机上的数据库要用 host.docker.internal,不能写 localhost (那是容器自身);容器所在网络要能访问该地址与端口。
  • 外部 PostgreSQL 报认证失败:密码含 @、:、/ 等字符时需百分号编码, 或在数据库中改用不含特殊字符的密码。
  • 想用 SQLite 快速试跑容器:把 DATABASE_URL 设为 sqlite+aiosqlite:////app/data/app.db(需该路径可写;如需持久化请自行挂载卷)。
  • 前端 404(刷新页面):nginx 已配置 try_files ... /index.html history 回退; 若自行部署,请确认等价配置。
  • alembic upgrade head 报无法打开数据库:SQLite 需要 backend/data/ 目录, CLI 会自动创建;若手动指定了其他路径,请确保目录存在。
  • Windows 上 uvicorn --reload 改了代码不重启:uvicorn 在 Windows 通过给子进程发 CTRL_C_EVENT 来重启(见 uvicorn/supervisors/basereload.py),这要求父子进程处于同一 控制台。若在无控制台的环境启动(IDE 任务、后台作业、uvicorn ... > log.txt),事件送不到 子进程,日志只打印 Reloading... 然后卡在 process.join(),服务继续跑旧代码。 解决:在自己的终端里运行该命令,或去掉 --reload 并在改完代码后手动重启。
  • 想让后端接口在浏览器报 CORS:把前端地址加入 CORS_ORIGINS(逗号分隔)。
  • 升级到 Yarn 4:执行 corepack enable && yarn set version stable, 并同步修改 package.json 的 packageManager 字段与 Dockerfile 中的 yarn 安装方式。
S
Description
No description provided
Readme
125 KiB
0 Stars 1 Watchers 0 Forks
Languages
Python 51.9%
Vue 15.3%
TypeScript 13.9%
CSS 9%
Dockerfile 5.5%
Other 4.4%