{"id":51136904,"url":"https://github.com/1111mp/fastapi-app","last_synced_at":"2026-06-25T19:01:33.963Z","repository":{"id":353972535,"uuid":"1221622892","full_name":"1111mp/fastapi-app","owner":"1111mp","description":"一个基于 FastAPI + PostgreSQL + Redis + Taskiq + APScheduler 的后端服务模板","archived":false,"fork":false,"pushed_at":"2026-04-26T13:30:10.000Z","size":94,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-04-26T15:22:02.996Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/1111mp.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-04-26T13:18:49.000Z","updated_at":"2026-04-26T13:30:53.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/1111mp/fastapi-app","commit_stats":null,"previous_names":["1111mp/fastapi-app"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/1111mp/fastapi-app","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/1111mp%2Ffastapi-app","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/1111mp%2Ffastapi-app/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/1111mp%2Ffastapi-app/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/1111mp%2Ffastapi-app/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/1111mp","download_url":"https://codeload.github.com/1111mp/fastapi-app/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/1111mp%2Ffastapi-app/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34788254,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-25T02:00:05.521Z","response_time":101,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2026-06-25T19:01:16.738Z","updated_at":"2026-06-25T19:01:33.951Z","avatar_url":"https://github.com/1111mp.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# FastAPI App\n\n一个生产可用的 FastAPI 后端模板，内置认证、数据库、缓存、异步任务与可观测性能力。\n\n## 功能特性\n\n- 基于 `fastapi-users` 的完整认证体系（JWT / 注册 / 找回密码 / 邮箱验证）\n- GitHub OAuth 登录\n- 用户资料接口（`/users/me`）\n- Post 示例业务接口（鉴权后可访问）\n- PostgreSQL + SQLAlchemy（异步）\n- Redis 缓存/连接管理\n- Alembic 数据库迁移\n- Taskiq 异步任务（worker + scheduler）\n- APScheduler 应用内定时任务\n- Prometheus 指标 + 健康检查（`/healthz` / `/readyz`）\n- OpenTelemetry 链路追踪（可选）\n- Correlation ID 与结构化日志\n\n---\n\n## 技术栈\n\n- Python 3.14+\n- FastAPI\n- SQLAlchemy + Psycopg\n- PostgreSQL\n- Redis\n- FastAPI Users\n- Alembic\n- Taskiq / taskiq-redis / taskiq-fastapi\n- APScheduler\n- Prometheus FastAPI Instrumentator\n- OpenTelemetry\n- Structlog\n- uv\n\n---\n\n## 项目结构\n\n```text\napp/\n├── api/               # 路由与 API 入口\n├── auth/              # 认证相关（backend / manager / deps）\n├── core/              # 配置、日志、数据库、Redis、可观测性\n├── db/                # 数据访问层（CRUD）\n├── models/            # ORM 模型\n├── schemas/           # Pydantic 模型\n├── scheduler/         # APScheduler 任务定义与生命周期\n└── workers/           # Taskiq broker、任务与调度器\ntests/\n├── integration/       # 集成测试\n└── unit/              # 单元测试\nalembic/               # 数据库迁移\n```\n\n---\n\n## 快速开始（本地开发）\n\n### 1) 安装依赖\n\n```bash\nuv sync\n```\n\n### 2) 配置环境变量\n\n配置通过 `pydantic-settings` 加载，支持以下文件（后者覆盖前者）：\n\n1. `.env`\n2. `.env.local`\n3. `.env.prod`\n\n最小示例：\n\n```env\nPROJECT_NAME=fastapi-app\nENVIRONMENT=local\nPORT=8000\nFRONTEND_HOST=http://localhost:5173\nBACKEND_CORS_ORIGINS=http://localhost:5173,http://127.0.0.1:5173\nSECRET_KEY=change-me\nLOGGER_LEVEL=INFO\n\nPOSTGRES_HOST=127.0.0.1\nPOSTGRES_PORT=5432\nPOSTGRES_DB=fastapi_app\nPOSTGRES_USER=postgres\nPOSTGRES_PASSWORD=postgres\n\nREDIS_HOST=127.0.0.1\nREDIS_PORT=6379\nREDIS_DB=0\nREDIS_PASSWORD=redispass\n# 或直接使用 REDIS_URL 覆盖上面四项\n# REDIS_URL=redis://:redispass@127.0.0.1:6379/0\n\nGITHUB_CLIENT_ID=your_github_client_id\nGITHUB_CLIENT_SECRET=your_github_client_secret\n\nSLOW_QUERY_THRESHOLD_MS=1000\nMETRICS_ENABLED=true\n\nOTEL_ENABLED=false\nOTEL_EXPORTER_OTLP_ENDPOINT=\nOTEL_EXPORTER_OTLP_INSECURE=true\n\nFIRST_SUPERUSER=admin@example.com\nFIRST_SUPERUSER_PASSWORD=password\n```\n\n### 3) 启动基础依赖\n\n```bash\ndocker compose up -d db redis\n```\n\n### 4) 执行迁移\n\n```bash\nuv run alembic upgrade head\n```\n\n### 5) 启动 API\n\n```bash\nuv run fastapi run app/main.py --reload --port 8000\n```\n\n访问：\n\n- Swagger UI: `http://127.0.0.1:8000/docs`\n- OpenAPI JSON: `http://127.0.0.1:8000/api/v1/openapi.json`\n\n---\n\n## Docker Compose 启动（完整栈）\n\n一键启动 API + PostgreSQL + Redis + Taskiq Worker + Taskiq Scheduler：\n\n```bash\ndocker compose up --build\n```\n\n默认端口：\n\n- API: `http://127.0.0.1:80`\n- PostgreSQL: `127.0.0.1:5432`\n- Redis: `127.0.0.1:6379`\n\n---\n\n## 常用命令\n\n### 数据库迁移\n\n```bash\n# 生成迁移\nuv run alembic revision --autogenerate -m \"your message\"\n\n# 应用迁移\nuv run alembic upgrade head\n\n# 回滚一步\nuv run alembic downgrade -1\n```\n\n### 运行单元测试\n\n```bash\n# 首次安装（包含 dev 依赖）\nuv sync --group dev\n\n# 执行全部测试（默认附带 coverage）\nuv run pytest\n\n# 生成覆盖率报告（终端 + coverage.xml）\nuv run pytest --cov=app --cov-report=term-missing --cov-report=xml\n```\n\n### 集成测试数据回滚（避免脏数据）\n\n项目提供了 `tests/integration/conftest.py` 的 `db_transaction` 夹具：\n\n- 每个测试独立创建 `AsyncSession`。\n- 覆盖 `get_async_session`，确保接口走测试会话。\n- 测试期间把 `session.commit()` 临时替换为 `session.flush()`，结束后统一 `rollback()`。\n- 默认 `uv run pytest` 不执行集成测试（只跑 `not integration`）。\n\n```bash\n# 显式执行集成测试\nuv run pytest -m integration\n```\n\n`integration` 标记用法示例（如 `tests/integration/api/post_test.py`）：\n\n```python\nimport pytest\n\npytestmark = [pytest.mark.integration, pytest.mark.asyncio]\n```\n\n运行方式：\n\n- 只跑集成测试：`uv run pytest -m integration`\n- 排除集成测试：`uv run pytest -m \"not integration\"`\n- 跑某个集成测试文件：`uv run pytest tests/integration/api/post_test.py -m integration`\n\n### 启动 Taskiq Worker / Scheduler（本地）\n\n```bash\n# Worker\nuv run taskiq worker app.workers.provider:broker\n\n# Scheduler\nuv run taskiq scheduler app.workers.scheduler:scheduler --fs-discover --tasks-pattern \"app/**/tasks.py\"\n```\n\n---\n\n## API 概览\n\n默认前缀：`/api/v1`\n\n### 认证与用户\n\n- `POST /auth/jwt/login`\n- `POST /auth/jwt/logout`\n- `POST /auth/register`\n- `POST /auth/forgot-password`\n- `POST /auth/reset-password`\n- `POST /auth/verify`\n- `POST /auth/request-verify-token`\n- `GET /auth/github/authorize`\n- `GET /auth/github/callback`\n- `GET /users/me`\n- `PATCH /users/me`\n\n### Posts\n\n- `POST /posts/`（需登录）\n- `GET /posts/{id}`（需登录）\n\n### 运维接口\n\n- `GET /healthz`（存活检查）\n- `GET /readyz`（就绪检查，含 DB/Redis）\n- `GET /metrics`（Prometheus 指标，`METRICS_ENABLED=true` 时启用）\n\n\n---\n\n## CORS 配置说明\n\n`BACKEND_CORS_ORIGINS` 支持两种格式：\n\n- 逗号分隔字符串：`http://a.com,http://b.com`\n- JSON 数组：`[\"http://a.com\", \"http://b.com\"]`\n\n系统会自动把 `FRONTEND_HOST` 追加到允许列表中。\n\n---\n\n## 定时任务说明\n\n本项目有两类定时能力：\n\n1. **应用内 APScheduler**（`app/scheduler`）\n2. **Taskiq Scheduler**（`app/workers/tasks.py` 中使用 `schedule=[{\"cron\": \"* * * * *\"}]`）\n\n如果你只需要一种调度方式，建议在实际项目中保留一种以降低复杂度。\n\n---\n\n## 可观测性与稳定性\n\n本项目已提供基础可观测能力：\n\n- `/healthz` + `/readyz`：容器探针与依赖可用性检查\n- `/metrics`：Prometheus 文本格式指标\n  - 由 `prometheus-fastapi-instrumentator` 自动采集 HTTP 指标\n- OpenTelemetry tracing（可选开启）\n  - `OTEL_ENABLED=true` 后自动启用 FastAPI / SQLAlchemy / Redis tracing\n  - 设置 `OTEL_EXPORTER_OTLP_ENDPOINT` 可上报到 OTLP Collector\n  - gRPC 本地示例：`OTEL_EXPORTER_OTLP_ENDPOINT=localhost:4319` + `OTEL_EXPORTER_OTLP_INSECURE=true`\n\n---\n\n## 生产环境建议\n\n- 使用强随机 `SECRET_KEY`\n- 为 PostgreSQL 与 Redis 设置强密码\n- 将 `ENVIRONMENT` 设为 `production`\n- 正确配置 `BACKEND_CORS_ORIGINS`\n- 通过反向代理（Nginx / Traefik）暴露 API\n- 配置日志采集与告警\n\n---\n\n## License\n\n[MIT](./LICENSE)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2F1111mp%2Ffastapi-app","html_url":"https://awesome.ecosyste.ms/projects/github.com%2F1111mp%2Ffastapi-app","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2F1111mp%2Ffastapi-app/lists"}