fastapi-augment 0.1.4__tar.gz → 0.1.5__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/PKG-INFO +849 -779
  2. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/README.md +812 -742
  3. fastapi_augment-0.1.5/VERSION +1 -0
  4. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/pyproject.toml +115 -90
  5. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/setup.cfg +4 -4
  6. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/__init__.py +24 -24
  7. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/common/__init__.py +70 -61
  8. fastapi_augment-0.1.5/src/fastapi_augment/common/app_discovery.py +181 -0
  9. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/common/constants.py +27 -27
  10. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/common/exception_handlers.py +180 -178
  11. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/common/exceptions.py +165 -162
  12. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/common/utils/__init__.py +33 -32
  13. fastapi_augment-0.1.5/src/fastapi_augment/common/utils/paths.py +82 -0
  14. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/common/utils/strings.py +188 -188
  15. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/config/__init__.py +12 -12
  16. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/config/base_settings.py +262 -253
  17. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/config/database_settings.py +229 -219
  18. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/db/__init__.py +6 -6
  19. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/db/sqlalchemy/__init__.py +36 -32
  20. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/db/sqlalchemy/alembic/__init__.py +5 -5
  21. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/db/sqlalchemy/alembic/env.py +141 -141
  22. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/db/sqlalchemy/alembic/script.py.mako +28 -28
  23. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/db/sqlalchemy/base.py +9 -9
  24. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/db/sqlalchemy/engine.py +283 -252
  25. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/db/sqlalchemy/migrate.py +357 -356
  26. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/db/sqlalchemy/mixins/__init__.py +28 -18
  27. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/db/sqlalchemy/mixins/audit.py +61 -61
  28. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/db/sqlalchemy/mixins/soft_delete.py +85 -80
  29. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/db/sqlalchemy/mixins/timestamp.py +48 -48
  30. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/db/sqlalchemy/model_base.py +47 -47
  31. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/db/sqlalchemy/query_parser.py +456 -447
  32. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/db/sqlalchemy/repository_base.py +508 -490
  33. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/db/sqlalchemy/session.py +184 -182
  34. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/factory.py +262 -253
  35. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/health/__init__.py +34 -34
  36. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/health/checker.py +105 -105
  37. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/health/checkers.py +127 -126
  38. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/health/router.py +98 -92
  39. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/lifespan.py +453 -452
  40. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/logger/__init__.py +31 -26
  41. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/logger/filters.py +23 -23
  42. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/logger/handlers.py +98 -92
  43. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/logger/record_factory.py +41 -39
  44. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/logger/setup.py +221 -217
  45. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/middlewares/__init__.py +20 -20
  46. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/middlewares/base.py +86 -79
  47. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/middlewares/request_id.py +81 -82
  48. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/openapi.py +94 -94
  49. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/schemas/__init__.py +33 -29
  50. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/schemas/base.py +32 -32
  51. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/schemas/pagination.py +47 -46
  52. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/schemas/request.py +29 -28
  53. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/schemas/response.py +139 -139
  54. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/schemas/types.py +11 -11
  55. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment.egg-info/PKG-INFO +849 -779
  56. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment.egg-info/SOURCES.txt +4 -0
  57. fastapi_augment-0.1.5/tests/test_app_discovery.py +157 -0
  58. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/tests/test_config.py +228 -229
  59. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/tests/test_constants.py +43 -41
  60. fastapi_augment-0.1.5/tests/test_database_settings.py +238 -0
  61. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/tests/test_db_engine.py +248 -218
  62. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/tests/test_db_repository.py +451 -429
  63. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/tests/test_db_session_models.py +198 -182
  64. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/tests/test_exception_handlers.py +314 -315
  65. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/tests/test_exceptions.py +145 -133
  66. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/tests/test_factory.py +242 -239
  67. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/tests/test_health.py +211 -211
  68. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/tests/test_lifespan.py +336 -337
  69. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/tests/test_log.py +347 -343
  70. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/tests/test_middlewares.py +208 -211
  71. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/tests/test_migrate.py +127 -80
  72. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/tests/test_model_base.py +95 -89
  73. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/tests/test_openapi.py +101 -100
  74. fastapi_augment-0.1.5/tests/test_paths.py +57 -0
  75. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/tests/test_query_parser.py +261 -246
  76. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/tests/test_schemas.py +277 -268
  77. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/tests/test_settings.py +139 -128
  78. fastapi_augment-0.1.4/VERSION +0 -1
  79. fastapi_augment-0.1.4/src/fastapi_augment/common/utils/paths.py +0 -36
  80. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/db/sqlalchemy/alembic/README +0 -0
  81. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment/py.typed +0 -0
  82. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment.egg-info/dependency_links.txt +0 -0
  83. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment.egg-info/entry_points.txt +0 -0
  84. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment.egg-info/requires.txt +0 -0
  85. {fastapi_augment-0.1.4 → fastapi_augment-0.1.5}/src/fastapi_augment.egg-info/top_level.txt +0 -0
@@ -1,779 +1,849 @@
1
- Metadata-Version: 2.4
2
- Name: fastapi-augment
3
- Version: 0.1.4
4
- Summary: FastAPI 通用代码工具包,跨项目复用
5
- Author-email: zarkhan <hanguangzheng@qq.com>
6
- License-Expression: MIT
7
- Project-URL: Homepage, https://github.com/hgz1989/fastapi_augment
8
- Project-URL: Repository, https://github.com/hgz1989/fastapi_augment
9
- Project-URL: Documentation, https://github.com/hgz1989/fastapi_augment#readme
10
- Keywords: fastapi,fastapi-augment,augment,web,framework,async
11
- Classifier: Development Status :: 3 - Alpha
12
- Classifier: Framework :: FastAPI
13
- Classifier: Intended Audience :: Developers
14
- Classifier: Programming Language :: Python :: 3
15
- Classifier: Programming Language :: Python :: 3.11
16
- Classifier: Programming Language :: Python :: 3.12
17
- Classifier: Programming Language :: Python :: 3.13
18
- Classifier: Programming Language :: Python :: 3.14
19
- Classifier: Topic :: Internet :: WWW/HTTP
20
- Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
21
- Classifier: Typing :: Typed
22
- Requires-Python: >=3.11
23
- Description-Content-Type: text/markdown
24
- Requires-Dist: fastapi>=0.141.1
25
- Provides-Extra: uvicorn
26
- Requires-Dist: uvicorn[standard]>=0.24.0; extra == "uvicorn"
27
- Provides-Extra: sqlalchemy
28
- Requires-Dist: sqlalchemy[asyncio]>=2.0.52; extra == "sqlalchemy"
29
- Requires-Dist: python-ulid>=4.0.1; extra == "sqlalchemy"
30
- Requires-Dist: alembic>=1.19.2; extra == "sqlalchemy"
31
- Provides-Extra: orjson
32
- Requires-Dist: orjson>=3.10.0; extra == "orjson"
33
- Provides-Extra: config
34
- Requires-Dist: pydantic-settings>=2.15.0; extra == "config"
35
- Provides-Extra: standard
36
- Requires-Dist: fastapi-augment[config,orjson,sqlalchemy,uvicorn]; extra == "standard"
37
-
38
- # fastapi-augment
39
-
40
- 跨项目复用的 FastAPI 通用代码工具包,将多个项目中反复用到的应用工厂、生命周期管理、读写分离数据库层、通用 Mixin、统一响应模型与 HTTP 异常体系统一封装,开箱即用。
41
-
42
- ## 特性
43
-
44
- - **应用工厂** — 一行代码创建 FastAPI 实例,自动装配中间件、路由、生命周期与数据库
45
- - **生命周期管理** — 多注册表、优先级、超时控制、异常策略的启动/关闭钩子
46
- - **读写分离** — 单库 / 主从 / 集群拓扑的异步引擎管理,线程安全的 Session 自动路由
47
- - **泛型仓储** — 类型安全的异步 Repository,支持直接实例化与子类继承两种方式
48
- - **查询解析器** — REST 风格 query string 转 SQLAlchemy 表达式,支持 FIQL 条件、关键字搜索、排序
49
- - **可组合 Mixin** — 时间戳、审计、软删除等列混入,自由组合
50
- - **统一响应** — 全局 `APIResponse` 格式,自动追踪 `request_id`
51
- - **HTTP 异常** — 完整的 4xx 异常子类,内置默认文案
52
- - **OpenAPI 优化** — 自动清理 422 响应与验证错误模型
53
- - **日志管理** — request_id 自动注入、uvicorn 接管、多进程安全轮转、幂等初始化、一键配置
54
- - **健康检查** — 可扩展的检查器模式,内置应用状态与数据库连通性检查,一行开关
55
- - **配置管理** — 基于 pydantic-settings,支持 `.env` 文件、环境变量前缀、嵌套配置
56
- - **数据库迁移 CLI** — 一行命令生成/执行迁移,自动发现用户模型
57
-
58
- ## 安装
59
-
60
- ```bash
61
- pip install fastapi-augment
62
-
63
- # 推荐:安装全部可选依赖
64
- pip install fastapi-augment[standard]
65
-
66
- # 或按需单独安装
67
- pip install fastapi-augment[sqlalchemy]
68
- pip install fastapi-augment[uvicorn]
69
- pip install fastapi-augment[orjson]
70
- pip install fastapi-augment[config] # pydantic-settings 配置管理
71
- ```
72
-
73
- **要求:** Python >= 3.11
74
-
75
- ## 快速开始
76
-
77
- ```python
78
- from fastapi import APIRouter
79
- from fastapi_augment import create_app
80
- from fastapi_augment.db.sqlalchemy import (
81
- ClusterTopology, NodeConfig, EngineManager, SessionFactory,
82
- ModelBase, RepositoryBase,
83
- )
84
- from fastapi_augment.db.sqlalchemy.mixins import TimestampMixin
85
- from fastapi_augment.schemas import response_success
86
-
87
- # ── 1. 数据库拓扑 ──────────────────────────────────────
88
- topology = ClusterTopology(
89
- primary=NodeConfig(url='postgresql+asyncpg://user:pass@host/db'),
90
- )
91
- manager = EngineManager(topology).start()
92
- sessions = SessionFactory(manager)
93
-
94
-
95
- # ── 2. 定义模型 ────────────────────────────────────────
96
- class User(TimestampMixin, ModelBase):
97
- __tablename__ = 'users'
98
- name: str
99
-
100
-
101
- # ── 3. 路由 ────────────────────────────────────────────
102
- router = APIRouter()
103
- user_repo = RepositoryBase(User)
104
-
105
-
106
- @router.get('/users')
107
- async def list_users():
108
- async with sessions.read_session() as session:
109
- users = await user_repo.list(session, is_active=True, limit=10)
110
- return response_success(data=users)
111
-
112
-
113
- # ── 4. 创建应用 ────────────────────────────────────────
114
- app = create_app(
115
- title='My Service',
116
- version='1.0.0',
117
- engine_manager=manager,
118
- session_factory=sessions,
119
- routers=[router],
120
- )
121
- ```
122
-
123
- ## 核心模块
124
-
125
- ### 应用工厂 — `create_app()`
126
-
127
- 统一创建 FastAPI 实例,自动装配以下组件:
128
-
129
- | 组件 | 说明 |
130
- | -------- | ---------------------------------------------------------- |
131
- | 生命周期 | 接入 `fastapi_lifespan`,合并用户注册表与 `core_registry` |
132
- | 中间件 | 自动添加 `RequestIdMiddleware`,可选 CORS |
133
- | 路由 | 支持 `APIRouter` 列表或 `(router, kwargs)` 元组 |
134
- | OpenAPI | 自动清理 422 响应与验证错误模型 |
135
- | 数据库 | 可选挂载 `EngineManager` / `SessionFactory` 到 `app.state` |
136
- | 健康检查 | `health_check=True` 一键启用 `/health` 端点 |
137
-
138
- ```python
139
- from fastapi_augment import create_app, HookRegistry
140
-
141
- registry = HookRegistry()
142
-
143
- @registry.on_startup
144
- async def init_cache() -> None:
145
- ...
146
-
147
- app = create_app(
148
- title='My Service',
149
- registries=registry, # 单个或列表均可
150
- cors_allow_origins=['*'],
151
- health_check=True, # 启用健康检查
152
- )
153
- ```
154
-
155
- ### 生命周期 — `HookRegistry`
156
-
157
- 多注册表、优先级驱动的启动/关闭钩子管理:
158
-
159
- ```python
160
- from fastapi_augment import HookRegistry
161
-
162
- registry = HookRegistry()
163
-
164
- # 装饰器语法
165
- @registry.on_startup(priority=100)
166
- async def early_init() -> None: ...
167
-
168
- @registry.on_shutdown
169
- async def cleanup() -> None: ...
170
-
171
- # 直接注册
172
- registry.register_startup(func, priority=50, timeout=10, abort_on_exception=True)
173
- ```
174
-
175
- - **优先级** — 数值越大越先执行(启动降序,关闭升序)
176
- - **超时控制** — 可设置单个钩子的超时秒数
177
- - **异常策略** — `abort_on_exception` 控制异常时是否终止流程
178
-
179
- ### 数据库层 — `db.sqlalchemy`
180
-
181
- #### 引擎管理 — `EngineManager`
182
-
183
- 支持三种部署拓扑:
184
-
185
- ```python
186
- from fastapi_augment.db.sqlalchemy import ClusterTopology, NodeConfig, EngineManager
187
-
188
- # 单库
189
- topology = ClusterTopology(
190
- primary=NodeConfig(url='postgresql+asyncpg://user:pass@host/db'),
191
- )
192
-
193
- # 主从
194
- topology = ClusterTopology(
195
- primary=NodeConfig(url='postgresql+asyncpg://primary/db'),
196
- replicas=[NodeConfig(url='postgresql+asyncpg://replica-1/db')],
197
- )
198
-
199
- # 集群(主从 + 独立只读节点)
200
- topology = ClusterTopology(
201
- primary=NodeConfig(url='postgresql+asyncpg://primary/db'),
202
- replicas=[NodeConfig(url='postgresql+asyncpg://replica-1/db')],
203
- readonly=[NodeConfig(url='postgresql+asyncpg://readonly-1/db')],
204
- )
205
-
206
- manager = EngineManager(topology).start()
207
- # 读引擎轮询(round-robin),线程安全
208
- read_engine = manager.next_read_engine()
209
- ```
210
-
211
- #### 会话工厂 — `SessionFactory`
212
-
213
- 读写分离的异步 Session 工厂,支持 FastAPI `Depends()` 注入:
214
-
215
- ```python
216
- from fastapi_augment.db.sqlalchemy import SessionFactory
217
-
218
- sessions = SessionFactory(manager)
219
-
220
- # 写会话(自动 commit/rollback)
221
- async with sessions.transaction() as session:
222
- session.add(obj)
223
- # 自动 commit
224
-
225
- # 读会话(轮询读引擎)
226
- async with sessions.read_session() as session:
227
- result = await session.execute(select(User))
228
-
229
- # FastAPI 依赖注入
230
- from fastapi import Depends
231
- from sqlalchemy.ext.asyncio import AsyncSession
232
-
233
- @router.get('/users')
234
- async def list_users(session: AsyncSession = Depends(sessions.depends_read)):
235
- ...
236
- ```
237
-
238
- > **缓存说明:** `read_session()` 按 `AsyncEngine` 缓存 `async_sessionmaker`,线程安全,避免重复创建。打印 `SessionFactory` 实例可查看已缓存的引擎信息。
239
-
240
- #### 模型基类 — `ModelBase`
241
-
242
- 基于 ULID 主键的声明式模型基类:
243
-
244
- ```python
245
- from fastapi_augment.db.sqlalchemy import ModelBase, TimestampMixin
246
-
247
- class User(TimestampMixin, ModelBase):
248
- __tablename__ = 'users'
249
- name: str
250
- ```
251
-
252
- #### 泛型仓储 — `RepositoryBase`
253
-
254
- 类型安全的异步仓储基类,Repository 方法只 **flush**,不 commit,事务边界由调用方控制。
255
- 支持两种使用方式:
256
-
257
- ```python
258
- from fastapi_augment.db.sqlalchemy import RepositoryBase
259
-
260
- # 方式 1:直接实例化 — 显式传入模型类
261
- user_repo = RepositoryBase(User)
262
-
263
-
264
- # 方式 2:子类继承 — 通过泛型参数绑定模型,可扩展自定义方法
265
- class UserRepo(RepositoryBase[User]):
266
- async def find_by_email(self, session, email: str) -> User | None:
267
- return await self.get_first(session, email=email)
268
-
269
-
270
- user_repo = UserRepo() # 无需再传 User
271
- ```
272
-
273
- **CRUD 操作:**
274
-
275
- ```python
276
- # Create(静态方法)
277
- async with sessions.transaction() as session:
278
- await user_repo.create(session, User(name='alice'))
279
- await user_repo.create_many(session, [User(name='bob'), User(name='carol')])
280
-
281
- # Read(实例方法)
282
- async with sessions.read_session() as session:
283
- user = await user_repo.get(session, id_='01HXK...')
284
- user = await user_repo.get_first(session, name='alice') # 取第一条,无匹配返回 None
285
- user = await user_repo.get_unique(session, email='a@b.com') # 精确唯一,多条匹配抛 MultipleResultsFound
286
- users = await user_repo.list(session, role='admin', order_by=['-created_at'], limit=10)
287
- total = await user_repo.count(session, is_active=True)
288
- has_admin = await user_repo.exists(session, role='admin')
289
-
290
- # 分页查询(返回 dict:items / page / size / total / pages)
291
- result = await user_repo.paginate(session, page=1, size=10, role='admin', order_by=['-created_at'])
292
- # result = {'items': [...], 'page': 1, 'size': 10, 'total': 100, 'pages': 10}
293
-
294
- # Update
295
- async with sessions.transaction() as session:
296
- await user_repo.update(session, user, name='new_name')
297
- affected = await user_repo.update_by_id(session, id_='01HXK...', name='new_name')
298
-
299
- # Delete
300
- async with sessions.transaction() as session:
301
- await user_repo.delete(session, user)
302
- deleted = await user_repo.delete_by_id(session, id_='01HXK...')
303
- count = await user_repo.delete_where(session, is_active=False)
304
- ```
305
-
306
- **过滤语法:**
307
-
308
- ```python
309
- # 关键字过滤 — 等值匹配
310
- await user_repo.list(session, name='alice')
311
-
312
- # 序列 — 自动转为 IN 查询
313
- await user_repo.list(session, id_=['01HXK...', '01HXL...'])
314
-
315
- # None — 自动转为 IS NULL
316
- await user_repo.list(session, deleted_at=None)
317
-
318
- # 原生 SQLAlchemy 表达式
319
- await user_repo.list(session, expressions=(User.age > 18,))
320
-
321
- # 排序:字段名前缀 - 表示降序
322
- await user_repo.list(session, order_by=['-created_at', 'name'])
323
- ```
324
-
325
- ### 查询解析器 — `query_parser`
326
-
327
- 将 REST 风格的 query string 转为 SQLAlchemy `ColumnElement` 条件表达式,可直接传入 `RepositoryBase` 的 `expressions` / `order_by` 参数。
328
-
329
- #### where 组合条件(FIQL 风格)
330
-
331
- ```
332
- where = and_group ("," and_group)* , 表示 OR
333
- and_group = unit (";" unit)* ; 表示 AND
334
- unit = "(" where ")" | condition
335
- condition = field OP value
336
- ```
337
-
338
- **支持的操作符:**
339
-
340
- | 语法 | 含义 | 示例 |
341
- | ---------------- | -------------------- | ------------------------- |
342
- | `field==value` | 等于 | `status==1` |
343
- | `field!=value` | 不等 | `status!=0` |
344
- | `field~=value` | 模糊包含 (ILIKE) | `name~=张` |
345
- | `field>value` | 大于 | `age>18` |
346
- | `field>=value` | 大于等于 | `age>=18` |
347
- | `field<value` | 小于 | `age<60` |
348
- | `field<=value` | 小于等于 | `age<=60` |
349
- | `field~start~end`| 区间 (BETWEEN) | `age~18~60` |
350
-
351
- ```python
352
- from fastapi_augment.db.sqlalchemy import parse_where
353
-
354
- # 昵称含张 且 状态非禁用
355
- expr = parse_where('nickname~=张;status!=0', User)
356
-
357
- # 括号内 OR,与区间 AND
358
- expr = parse_where('(nickname~=张,username~=王);age~20~30', User)
359
- ```
360
-
361
- #### lookup 精确匹配
362
-
363
- ```python
364
- from fastapi_augment.db.sqlalchemy import parse_lookup
365
-
366
- # 单字段精确匹配
367
- expr = parse_lookup('phone==13800138000', User, fields={'phone', 'email'})
368
-
369
- # 多字段 AND(; 分隔)
370
- expr = parse_lookup('phone==138;status==1', User, fields={'phone', 'status'})
371
- ```
372
-
373
- #### 关键字搜索
374
-
375
- ```python
376
- from fastapi_augment.db.sqlalchemy import parse_keyword
377
-
378
- # 多字段 OR 模糊搜索
379
- expr = parse_keyword('admin', 'username,email,nickname', User)
380
- ```
381
-
382
- #### 排序
383
-
384
- ```python
385
- from fastapi_augment.db.sqlalchemy import parse_sort
386
-
387
- # - 前缀表示降序,无前缀为升序
388
- order_by = parse_sort('-created_at,nickname', User)
389
- ```
390
-
391
- #### 一键组合 — `build_query_expressions`
392
-
393
- ```python
394
- from fastapi_augment.db.sqlalchemy import build_query_expressions
395
-
396
- expressions, order_by = build_query_expressions(
397
- User,
398
- where='status!=0;age>=18',
399
- q='admin',
400
- q_field='username,nickname',
401
- sort='-created_at',
402
- )
403
-
404
- # 直接传给 paginate / list
405
- result = await user_repo.paginate(
406
- session, page=1, size=10,
407
- expressions=expressions, order_by=order_by,
408
- )
409
- ```
410
-
411
- ### 数据库迁移 CLI — `fastapi-augment-migrate`
412
-
413
- 内置 Alembic 迁移工具,提供 `init` / `generate` / `upgrade` 三个子命令,开箱即用。
414
-
415
- #### 快速开始
416
-
417
- ```bash
418
- # 1. 初始化(一次性操作,生成 alembic.ini + migrations/versions/)
419
- fastapi-augment-migrate init --db-url "sqlite:///test.db"
420
-
421
- # 2. 生成迁移
422
- fastapi-augment-migrate generate \
423
- --message "add_user_table" \
424
- --models "models,apps.ai.models"
425
-
426
- # 3. 执行迁移
427
- fastapi-augment-migrate upgrade
428
- ```
429
-
430
- #### 初始化 — `init`
431
-
432
- 在项目根目录生成 `alembic.ini` 和 `migrations/versions/` 目录。
433
- 若 `alembic.ini` 已存在则跳过,不会覆盖。
434
-
435
- ```bash
436
- # 初始化
437
- fastapi-augment-migrate init --db-url "sqlite:///test.db"
438
-
439
- # 指定项目根目录
440
- fastapi-augment-migrate init --db-url "postgresql+asyncpg://user:pass@host/db" --project-dir /path/to/project
441
- ```
442
-
443
- `alembic.ini` 中的 `script_location` 指向库内的 `env.py`,`version_locations` 指向本地 `migrations/versions/`。
444
- `env.py` 通过环境变量 `FASTAPI_AUGMENT_MODELS` 动态导入用户模型,无需手动修改。
445
-
446
- #### 生成迁移 — `generate`
447
-
448
- 通过 `--models` 指定模型模块(逗号分隔),调用 `alembic revision --autogenerate` 生成迁移脚本。
449
- 需要先执行 `init` 初始化。
450
-
451
- ```bash
452
- # 生成迁移
453
- fastapi-augment-migrate generate \
454
- --message "add_user_table" \
455
- --models "models,apps.ai.models"
456
-
457
- # 指定项目根目录
458
- fastapi-augment-migrate generate \
459
- --message "add_item" \
460
- --models "apps.ai.models" \
461
- --project-dir /path/to/project
462
- ```
463
-
464
- 迁移文件生成在 `<项目根>/migrations/versions/` 目录下。
465
-
466
- #### 升级 / 降级 — `upgrade`
467
-
468
- `--db-url` 为可选参数,不传时直接从 `alembic.ini` 读取 `sqlalchemy.url`。
469
-
470
- ```bash
471
- # 升级到最新版本(从 alembic.ini 读取数据库 URL)
472
- fastapi-augment-migrate upgrade
473
-
474
- # 指定数据库 URL(覆盖 alembic.ini 中的配置)
475
- fastapi-augment-migrate upgrade --db-url "sqlite:///test.db"
476
-
477
- # 升级到指定版本
478
- fastapi-augment-migrate upgrade --revision abc123
479
-
480
- # 降级一个版本
481
- fastapi-augment-migrate upgrade --downgrade
482
-
483
- # 降级到指定版本
484
- fastapi-augment-migrate upgrade --downgrade --revision abc123
485
-
486
- # 指定项目根目录
487
- fastapi-augment-migrate upgrade --project-dir /path/to/project
488
- ```
489
-
490
- #### CLI 参数一览
491
-
492
- | 子命令 | 参数 | 说明 |
493
- | ---------- | --------------- | --------------------------------------- |
494
- | `init` | `--db-url` | 数据库 URL(默认 `sqlite:///app.db`) |
495
- | | `--project-dir` | 项目根目录(默认当前目录) |
496
- | `generate` | `--message` | **必填**,迁移描述 |
497
- | | `--models` | **必填**,模型模块路径,逗号分隔 |
498
- | | `--project-dir` | 项目根目录(默认当前目录) |
499
- | `upgrade` | `--db-url` | 数据库 URL(不传则从 alembic.ini 读取) |
500
- | | `--revision` | 目标版本(默认 `head`) |
501
- | | `--downgrade` | 降级模式 |
502
- | | `--project-dir` | 项目根目录(默认当前目录) |
503
-
504
- ### 模型 Mixin — `db.sqlalchemy.mixins`
505
-
506
- 可组合的列混入,按需叠加:
507
-
508
- | Mixin | 提供的列 |
509
- | ---------------------- | ------------------------------------------ |
510
- | `CreatedAtMixin` | `created_at` |
511
- | `TimestampMixin` | `created_at` + `updated_at` |
512
- | `CreatedByMixin` | `created_by` |
513
- | `UpdatedByMixin` | `updated_by` |
514
- | `AuditMixin` | `created_by` + `updated_by` |
515
- | `SoftDeleteMixin` | `is_deleted` + `deleted_at` |
516
- | `SoftDeleteAuditMixin` | `is_deleted` + `deleted_at` + `deleted_by` |
517
-
518
- ```python
519
- from fastapi_augment.db.sqlalchemy import ModelBase
520
- from fastapi_augment.db.sqlalchemy.mixins import TimestampMixin, SoftDeleteMixin
521
-
522
- class User(TimestampMixin, SoftDeleteMixin, ModelBase):
523
- __tablename__ = 'users'
524
- name: str
525
- ```
526
-
527
- ### 统一响应 — `schemas`
528
-
529
- #### `APIResponse` — 全局返回格式
530
-
531
- ```json
532
- {
533
- "request_id": "019xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
534
- "code": 0,
535
- "message": "操作成功",
536
- "data": { ... },
537
- "extra": null
538
- }
539
- ```
540
-
541
- `request_id` 自动从 `ContextVar` 获取,无需手动传递。
542
-
543
- #### 工厂函数
544
-
545
- ```python
546
- from fastapi_augment.schemas import response_success, response_fail
547
-
548
- # 成功响应
549
- return response_success(data=user)
550
- return response_success(data=users, extra={'total': 100})
551
-
552
- # 失败响应
553
- return response_fail(code=40001, message='用户名已存在')
554
- ```
555
-
556
- #### 请求参数模型
557
-
558
- ```python
559
- from fastapi_augment.schemas import PageParams, TimeRangeParams, KeywordParams
560
-
561
- # 分页参数
562
- @router.get('/users')
563
- async def list_users(params: PageParams = Depends()):
564
- ...
565
-
566
- # 时间范围 + 关键词搜索
567
- @router.get('/orders')
568
- async def list_orders(
569
- time_range: TimeRangeParams = Depends(),
570
- keyword: KeywordParams = Depends(),
571
- ):
572
- ...
573
- ```
574
-
575
- ### HTTP 异常 — `common.exceptions`
576
-
577
- 完整的 4xx 异常子类,内置默认文案。子类只需声明 `_status_code` 类变量,无需重写 `__init__`:
578
-
579
- ```python
580
- from fastapi_augment.common.exceptions import (
581
- BadRequestError, # 400
582
- UnauthorizedError, # 401
583
- ForbiddenError, # 403
584
- NotFoundError, # 404
585
- ConflictError, # 409
586
- TooManyRequestsError, # 429(支持 retry_after 参数)
587
- # ... 更多异常
588
- )
589
-
590
- # 使用默认文案
591
- raise NotFoundError()
592
-
593
- # 自定义提示
594
- raise BadRequestError(detail='用户名不能为空')
595
-
596
- # 限流场景
597
- raise TooManyRequestsError(retry_after=60)
598
- ```
599
-
600
- ### 日志管理 — `logger`
601
-
602
- 导入即生效:自动注入 `request_id` 到每条日志、接管 uvicorn/fastapi 日志输出。
603
-
604
- ```python
605
- from fastapi_augment.logger import setup_logger, set_log_level
606
-
607
- # 一键配置:控制台 + 按天轮转文件日志
608
- setup_logger(log_dir='./logs', rotation='day', backup_count=30)
609
-
610
- # 动态调整日志级别
611
- set_log_level('info')
612
- ```
613
-
614
- **支持的轮转粒度:**
615
-
616
- | 粒度 | 说明 |
617
- | ---------------------------------- | -------------------- |
618
- | `'second'` / `'minute'` / `'hour'` | 每整秒/分/点 |
619
- | `'day'`(默认) | 每天 00:00 |
620
- | `'week'` | 每周一 00:00 |
621
- | `'month'` | 每月 1 日 00:00 |
622
- | `'year'` | 每年 1 月 1 日 00:00 |
623
-
624
- **核心能力:**
625
-
626
- - **request_id 注入** — 每条日志自动携带当前请求的 `request_id`,方便链路追踪
627
- - **uvicorn 接管** — 统一 `uvicorn.error` / `uvicorn.access` 的日志名称为 `uvicorn`,屏蔽第三方库 DEBUG 噪声
628
- - **多进程安全** — 日志轮转时捕获 `OSError`(含 `PermissionError`、`FileNotFoundError`),兼容多进程部署(如 `uvicorn --workers N`)
629
- - **幂等初始化** — 重复导入或多次调用 `setup_logger()` 不会叠加处理器或工厂链
630
- - **控制台开关** — `enable_console=False` 可关闭控制台输出,仅保留文件日志
631
-
632
- ### 健康检查 — `health`
633
-
634
- 可扩展的检查器模式,内置应用状态与数据库连通性检查。
635
-
636
- #### 一行启用
637
-
638
- ```python
639
- app = create_app(
640
- title='My Service',
641
- engine_manager=manager,
642
- health_check=True, # 自动注册 /health 端点
643
- )
644
- ```
645
-
646
- `GET /health` 响应示例:
647
-
648
- ```json
649
- {
650
- "status": "healthy",
651
- "checks": [
652
- {
653
- "name": "app",
654
- "status": "healthy",
655
- "latencyMs": 0,
656
- "details": {
657
- "status": "running",
658
- "version": "1.0.0",
659
- "uptimeSeconds": 3600
660
- }
661
- },
662
- { "name": "database", "status": "healthy", "latencyMs": 2.3 }
663
- ]
664
- }
665
- ```
666
-
667
- - 总体状态取所有检查项中**最差**的(healthy < degraded < unhealthy)
668
- - 任一检查项 unhealthy 时 HTTP 返回 **503**,便于负载均衡器/探针识别
669
- - 传入 `engine_manager` 时自动包含数据库检查,否则仅检查应用状态
670
-
671
- #### 自定义检查器
672
-
673
- ```python
674
- from fastapi_augment.health import BaseChecker, CheckResult, create_health_router
675
-
676
- class RedisChecker(BaseChecker):
677
- @property
678
- def name(self) -> str:
679
- return 'redis'
680
-
681
- async def check(self, app) -> CheckResult:
682
- # 检查 Redis 连通性
683
- ...
684
-
685
- # 手动注册(适合需要自定义路径或额外检查器的场景)
686
- app.include_router(create_health_router(
687
- path='/health',
688
- extra_checkers=[RedisChecker()],
689
- ))
690
- ```
691
-
692
- ### 配置管理 — `config`
693
-
694
- 基于 `pydantic-settings`,支持多种配置来源(环境变量、.env、JSON、YAML、TOML),通过不同类方法加载:
695
-
696
- ```python
697
- from fastapi_augment.config import AugmentBaseSettings
698
-
699
- class Settings(AugmentBaseSettings):
700
- database_url: str
701
- redis_url: str = ''
702
- debug: bool = False
703
- secret_key: str = 'change-me'
704
-
705
- # 从环境变量加载
706
- cfg = Settings.from_env(env_prefix='APP_', env_nested_delimiter='__')
707
-
708
- # 从 .env 文件加载
709
- cfg = Settings.from_dotenv('.env', env_prefix='APP_')
710
-
711
- # 从 JSON / YAML / TOML 文件加载
712
- cfg = Settings.from_json('config.json')
713
- cfg = Settings.from_yaml('config.yaml')
714
- cfg = Settings.from_toml('config.toml')
715
- ```
716
-
717
- 支持 `SettingsConfigDict` 的所有参数(`env_prefix`、`secrets_dir`、`yaml_file` 等),
718
- 与模型字段值自动区分,无需关心分类。
719
-
720
- ### 中间件 — `middlewares`
721
-
722
- #### `RequestIdMiddleware`
723
-
724
- 自动为每个请求生成/传递 `request_id`(ULID 格式),通过 `ContextVar` 在全链路中可用:
725
-
726
- ```python
727
- from fastapi_augment.middlewares import get_request_id
728
-
729
- request_id = get_request_id()
730
- ```
731
-
732
- ## 项目结构
733
-
734
- ```
735
- fastapi_augment/
736
- ├── common/
737
- │ ├── constants.py # 全局常量与默认错误文案
738
- │ ├── exceptions.py # 4xx HTTP 异常体系
739
- │ ├── exception_handlers.py # 全局异常处理器
740
- │ └── utils/
741
- │ └── strings.py # 字符串工具 / JSON 序列化
742
- ├── config/
743
- │ ├── base_settings.py # AugmentBaseSettings 配置管理
744
- │ └── database_settings.py # DatabaseSettings 数据库配置
745
- ├── db/
746
- │ └── sqlalchemy/
747
- │ ├── engine.py # EngineManager / NodeConfig / ClusterTopology
748
- │ ├── session.py # SessionFactory(读写分离)
749
- │ ├── model_base.py # ModelBase(ULID 主键)
750
- │ ├── repository_base.py # RepositoryBase(泛型仓储 + paginate)
751
- │ ├── query_parser.py # 查询解析器(where / lookup / keyword / sort)
752
- │ ├── migrate.py # 数据库迁移 CLI
753
- │ ├── migrations/ # Alembic 迁移环境(env.py / script.py.mako)
754
- │ └── mixins/ # Timestamp / Audit / SoftDelete
755
- ├── health/
756
- │ ├── checker.py # BaseChecker / CheckResult / HealthResponse
757
- │ ├── checkers.py # AppChecker / DatabaseChecker
758
- │ └── router.py # create_health_router()
759
- ├── logger/
760
- │ ├── record_factory.py # request_id 注入工厂
761
- │ ├── filters.py # UvicornNameRewriteFilter
762
- │ ├── handlers.py # 多进程安全轮转处理器
763
- │ └── setup.py # setup_logger / set_log_level / set_log_format
764
- ├── middlewares/
765
- │ ├── base.py # BaseASGIMiddleware
766
- │ └── request_id.py # RequestId 中间件
767
- ├── schemas/
768
- │ ├── base.py # SchemaBase / ORMSchemaBase
769
- │ ├── request.py # PageParams / TimeRangeParams / KeywordParams
770
- │ ├── response.py # APIResponse / response_success / response_fail
771
- │ └── pagination.py # PageData 分页模型
772
- ├── factory.py # create_app 应用工厂
773
- ├── lifespan.py # HookRegistry 生命周期管理
774
- └── openapi.py # OpenAPI schema 优化
775
- ```
776
-
777
- ## 许可证
778
-
779
- MIT
1
+ Metadata-Version: 2.4
2
+ Name: fastapi-augment
3
+ Version: 0.1.5
4
+ Summary: FastAPI 通用代码工具包,跨项目复用
5
+ Author-email: zarkhan <hanguangzheng@qq.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/hgz1989/fastapi_augment
8
+ Project-URL: Repository, https://github.com/hgz1989/fastapi_augment
9
+ Project-URL: Documentation, https://github.com/hgz1989/fastapi_augment#readme
10
+ Keywords: fastapi,fastapi-augment,augment,web,framework,async
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Framework :: FastAPI
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Topic :: Internet :: WWW/HTTP
20
+ Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.11
23
+ Description-Content-Type: text/markdown
24
+ Requires-Dist: fastapi>=0.141.1
25
+ Provides-Extra: uvicorn
26
+ Requires-Dist: uvicorn[standard]>=0.24.0; extra == "uvicorn"
27
+ Provides-Extra: sqlalchemy
28
+ Requires-Dist: sqlalchemy[asyncio]>=2.0.52; extra == "sqlalchemy"
29
+ Requires-Dist: python-ulid>=4.0.1; extra == "sqlalchemy"
30
+ Requires-Dist: alembic>=1.19.2; extra == "sqlalchemy"
31
+ Provides-Extra: orjson
32
+ Requires-Dist: orjson>=3.10.0; extra == "orjson"
33
+ Provides-Extra: config
34
+ Requires-Dist: pydantic-settings>=2.15.0; extra == "config"
35
+ Provides-Extra: standard
36
+ Requires-Dist: fastapi-augment[config,orjson,sqlalchemy,uvicorn]; extra == "standard"
37
+
38
+ # fastapi-augment
39
+
40
+ 跨项目复用的 FastAPI 通用代码工具包,将多个项目中反复用到的应用工厂、生命周期管理、读写分离数据库层、通用 Mixin、统一响应模型与 HTTP 异常体系统一封装,开箱即用。
41
+
42
+ ## 特性
43
+
44
+ - **应用工厂** — 一行代码创建 FastAPI 实例,自动装配中间件、路由、生命周期与数据库
45
+ - **生命周期管理** — 多注册表、优先级、超时控制、异常策略的启动/关闭钩子
46
+ - **读写分离** — 单库 / 主从 / 集群拓扑的异步引擎管理,线程安全的 Session 自动路由
47
+ - **泛型仓储** — 类型安全的异步 Repository,支持直接实例化与子类继承两种方式
48
+ - **查询解析器** — REST 风格 query string 转 SQLAlchemy 表达式,支持 FIQL 条件、关键字搜索、排序
49
+ - **可组合 Mixin** — 时间戳、审计、软删除等列混入,自由组合
50
+ - **统一响应** — 全局 `APIResponse` 格式,自动追踪 `request_id`
51
+ - **HTTP 异常** — 完整的 4xx 异常子类,内置默认文案
52
+ - **OpenAPI 优化** — 自动清理 422 响应与验证错误模型
53
+ - **日志管理** — request_id 自动注入、uvicorn 接管、多进程安全轮转、幂等初始化、一键配置
54
+ - **健康检查** — 可扩展的检查器模式,内置应用状态与数据库连通性检查,一行开关
55
+ - **配置管理** — 基于 pydantic-settings,支持 `.env` 文件、环境变量前缀、嵌套配置
56
+ - **数据库迁移 CLI** — 一行命令生成/执行迁移,自动发现用户模型
57
+ - **应用发现** — 自动发现子包 `__all__` 导出的 FastAPI 应用,支持排除与导入串校验
58
+
59
+ ## 安装
60
+
61
+ ```bash
62
+ pip install fastapi-augment
63
+
64
+ # 推荐:安装全部可选依赖
65
+ pip install fastapi-augment[standard]
66
+
67
+ # 或按需单独安装
68
+ pip install fastapi-augment[sqlalchemy]
69
+ pip install fastapi-augment[uvicorn]
70
+ pip install fastapi-augment[orjson]
71
+ pip install fastapi-augment[config] # pydantic-settings 配置管理
72
+ ```
73
+
74
+ **要求:** Python >= 3.11
75
+
76
+ ## 快速开始
77
+
78
+ ```python
79
+ from fastapi import APIRouter
80
+ from fastapi_augment import create_app
81
+ from fastapi_augment.db.sqlalchemy import (
82
+ ClusterTopology, NodeConfig, EngineManager, SessionFactory,
83
+ ModelBase, RepositoryBase,
84
+ )
85
+ from fastapi_augment.db.sqlalchemy.mixins import TimestampMixin
86
+ from fastapi_augment.schemas import response_success
87
+
88
+ # ── 1. 数据库拓扑 ──────────────────────────────────────
89
+ topology = ClusterTopology(
90
+ primary=NodeConfig(url='postgresql+asyncpg://user:pass@host/db'),
91
+ )
92
+ manager = EngineManager(topology).start()
93
+ sessions = SessionFactory(manager)
94
+
95
+
96
+ # ── 2. 定义模型 ────────────────────────────────────────
97
+ class User(TimestampMixin, ModelBase):
98
+ __tablename__ = 'users'
99
+ name: str
100
+
101
+
102
+ # ── 3. 路由 ────────────────────────────────────────────
103
+ router = APIRouter()
104
+ user_repo = RepositoryBase(User)
105
+
106
+
107
+ @router.get('/users')
108
+ async def list_users():
109
+ async with sessions.read_session() as session:
110
+ users = await user_repo.list(session, is_active=True, limit=10)
111
+ return response_success(data=users)
112
+
113
+
114
+ # ── 4. 创建应用 ────────────────────────────────────────
115
+ app = create_app(
116
+ title='My Service',
117
+ version='1.0.0',
118
+ engine_manager=manager,
119
+ session_factory=sessions,
120
+ routers=[router],
121
+ )
122
+ ```
123
+
124
+ ## 核心模块
125
+
126
+ ### 应用工厂 — `create_app()`
127
+
128
+ 统一创建 FastAPI 实例,自动装配以下组件:
129
+
130
+ | 组件 | 说明 |
131
+ | -------- | ---------------------------------------------------------- |
132
+ | 生命周期 | 接入 `fastapi_lifespan`,合并用户注册表与 `core_registry` |
133
+ | 中间件 | 自动添加 `RequestIdMiddleware`,可选 CORS |
134
+ | 路由 | 支持 `APIRouter` 列表或 `(router, kwargs)` 元组 |
135
+ | OpenAPI | 自动清理 422 响应与验证错误模型 |
136
+ | 数据库 | 可选挂载 `EngineManager` / `SessionFactory` 到 `app.state` |
137
+ | 健康检查 | `health_check=True` 一键启用 `/health` 端点 |
138
+
139
+ ```python
140
+ from fastapi_augment import create_app, HookRegistry
141
+
142
+ registry = HookRegistry()
143
+
144
+ @registry.on_startup
145
+ async def init_cache() -> None:
146
+ ...
147
+
148
+ app = create_app(
149
+ title='My Service',
150
+ registries=registry, # 单个或列表均可
151
+ cors_allow_origins=['*'],
152
+ health_check=True, # 启用健康检查
153
+ )
154
+ ```
155
+
156
+ ### 生命周期 — `HookRegistry`
157
+
158
+ 多注册表、优先级驱动的启动/关闭钩子管理:
159
+
160
+ ```python
161
+ from fastapi_augment import HookRegistry
162
+
163
+ registry = HookRegistry()
164
+
165
+ # 装饰器语法
166
+ @registry.on_startup(priority=100)
167
+ async def early_init() -> None: ...
168
+
169
+ @registry.on_shutdown
170
+ async def cleanup() -> None: ...
171
+
172
+ # 直接注册
173
+ registry.register_startup(func, priority=50, timeout=10, abort_on_exception=True)
174
+ ```
175
+
176
+ - **优先级** — 数值越大越先执行(启动降序,关闭升序)
177
+ - **超时控制** — 可设置单个钩子的超时秒数
178
+ - **异常策略** — `abort_on_exception` 控制异常时是否终止流程
179
+
180
+ ### 数据库层 — `db.sqlalchemy`
181
+
182
+ #### 引擎管理 — `EngineManager`
183
+
184
+ 支持三种部署拓扑:
185
+
186
+ ```python
187
+ from fastapi_augment.db.sqlalchemy import ClusterTopology, NodeConfig, EngineManager
188
+
189
+ # 单库
190
+ topology = ClusterTopology(
191
+ primary=NodeConfig(url='postgresql+asyncpg://user:pass@host/db'),
192
+ )
193
+
194
+ # 主从
195
+ topology = ClusterTopology(
196
+ primary=NodeConfig(url='postgresql+asyncpg://primary/db'),
197
+ replicas=[NodeConfig(url='postgresql+asyncpg://replica-1/db')],
198
+ )
199
+
200
+ # 集群(主从 + 独立只读节点)
201
+ topology = ClusterTopology(
202
+ primary=NodeConfig(url='postgresql+asyncpg://primary/db'),
203
+ replicas=[NodeConfig(url='postgresql+asyncpg://replica-1/db')],
204
+ readonly=[NodeConfig(url='postgresql+asyncpg://readonly-1/db')],
205
+ )
206
+
207
+ manager = EngineManager(topology).start()
208
+ # 读引擎轮询(round-robin),线程安全
209
+ read_engine = manager.next_read_engine()
210
+ ```
211
+
212
+ #### 会话工厂 — `SessionFactory`
213
+
214
+ 读写分离的异步 Session 工厂,支持 FastAPI `Depends()` 注入:
215
+
216
+ ```python
217
+ from fastapi_augment.db.sqlalchemy import SessionFactory
218
+
219
+ sessions = SessionFactory(manager)
220
+
221
+ # 写会话(自动 commit/rollback)
222
+ async with sessions.transaction() as session:
223
+ session.add(obj)
224
+ # 自动 commit
225
+
226
+ # 读会话(轮询读引擎)
227
+ async with sessions.read_session() as session:
228
+ result = await session.execute(select(User))
229
+
230
+ # FastAPI 依赖注入
231
+ from fastapi import Depends
232
+ from sqlalchemy.ext.asyncio import AsyncSession
233
+
234
+ @router.get('/users')
235
+ async def list_users(session: AsyncSession = Depends(sessions.depends_read)):
236
+ ...
237
+ ```
238
+
239
+ > **缓存说明:** `read_session()` 按 `AsyncEngine` 缓存 `async_sessionmaker`,线程安全,避免重复创建。打印 `SessionFactory` 实例可查看已缓存的引擎信息。
240
+
241
+ #### 模型基类 — `ModelBase`
242
+
243
+ 基于 ULID 主键的声明式模型基类:
244
+
245
+ ```python
246
+ from fastapi_augment.db.sqlalchemy import ModelBase, TimestampMixin
247
+
248
+ class User(TimestampMixin, ModelBase):
249
+ __tablename__ = 'users'
250
+ name: str
251
+ ```
252
+
253
+ #### 泛型仓储 — `RepositoryBase`
254
+
255
+ 类型安全的异步仓储基类,Repository 方法只 **flush**,不 commit,事务边界由调用方控制。
256
+ 支持两种使用方式:
257
+
258
+ ```python
259
+ from fastapi_augment.db.sqlalchemy import RepositoryBase
260
+
261
+ # 方式 1:直接实例化 — 显式传入模型类
262
+ user_repo = RepositoryBase(User)
263
+
264
+
265
+ # 方式 2:子类继承 — 通过泛型参数绑定模型,可扩展自定义方法
266
+ class UserRepo(RepositoryBase[User]):
267
+ async def find_by_email(self, session, email: str) -> User | None:
268
+ return await self.get_first(session, email=email)
269
+
270
+
271
+ user_repo = UserRepo() # 无需再传 User
272
+ ```
273
+
274
+ **CRUD 操作:**
275
+
276
+ ```python
277
+ # Create(静态方法)
278
+ async with sessions.transaction() as session:
279
+ await user_repo.create(session, User(name='alice'))
280
+ await user_repo.create_many(session, [User(name='bob'), User(name='carol')])
281
+
282
+ # Read(实例方法)
283
+ async with sessions.read_session() as session:
284
+ user = await user_repo.get(session, id_='01HXK...')
285
+ user = await user_repo.get_first(session, name='alice') # 取第一条,无匹配返回 None
286
+ user = await user_repo.get_unique(session, email='a@b.com') # 精确唯一,多条匹配抛 MultipleResultsFound
287
+ users = await user_repo.list(session, role='admin', order_by=['-created_at'], limit=10)
288
+ total = await user_repo.count(session, is_active=True)
289
+ has_admin = await user_repo.exists(session, role='admin')
290
+
291
+ # 分页查询(返回 dict:items / page / size / total / pages;size 上限 1000,超限静默截断)
292
+ result = await user_repo.paginate(session, page=1, size=10, role='admin', order_by=['-created_at'])
293
+ # result = {'items': [...], 'page': 1, 'size': 10, 'total': 100, 'pages': 10}
294
+
295
+ # Update
296
+ async with sessions.transaction() as session:
297
+ await user_repo.update(session, user, name='new_name')
298
+ affected = await user_repo.update_by_id(session, id_='01HXK...', name='new_name')
299
+
300
+ # Delete
301
+ async with sessions.transaction() as session:
302
+ await user_repo.delete(session, user)
303
+ deleted = await user_repo.delete_by_id(session, id_='01HXK...')
304
+ count = await user_repo.delete_where(session, is_active=False)
305
+ ```
306
+
307
+ **过滤语法:**
308
+
309
+ ```python
310
+ # 关键字过滤 — 等值匹配
311
+ await user_repo.list(session, name='alice')
312
+
313
+ # 序列 — 自动转为 IN 查询
314
+ await user_repo.list(session, id_=['01HXK...', '01HXL...'])
315
+
316
+ # None — 自动转为 IS NULL
317
+ await user_repo.list(session, deleted_at=None)
318
+
319
+ # 原生 SQLAlchemy 表达式
320
+ await user_repo.list(session, expressions=(User.age > 18,))
321
+
322
+ # 排序:字段名前缀 - 表示降序
323
+ await user_repo.list(session, order_by=['-created_at', 'name'])
324
+ ```
325
+
326
+ ### 查询解析器 — `query_parser`
327
+
328
+ 将 REST 风格的 query string 转为 SQLAlchemy `ColumnElement` 条件表达式,可直接传入 `RepositoryBase` 的 `expressions` / `order_by` 参数。
329
+
330
+ #### where 组合条件(FIQL 风格)
331
+
332
+ ```
333
+ where = and_group ("," and_group)* , 表示 OR
334
+ and_group = unit (";" unit)* ; 表示 AND
335
+ unit = "(" where ")" | condition
336
+ condition = field OP value
337
+ ```
338
+
339
+ **支持的操作符:**
340
+
341
+ | 语法 | 含义 | 示例 |
342
+ | ---------------- | -------------------- | ------------------------- |
343
+ | `field==value` | 等于 | `status==1` |
344
+ | `field!=value` | 不等 | `status!=0` |
345
+ | `field~=value` | 模糊包含 (ILIKE) | `name~=张` |
346
+ | `field>value` | 大于 | `age>18` |
347
+ | `field>=value` | 大于等于 | `age>=18` |
348
+ | `field<value` | 小于 | `age<60` |
349
+ | `field<=value` | 小于等于 | `age<=60` |
350
+ | `field~start~end`| 区间 (BETWEEN) | `age~18~60` |
351
+
352
+ ```python
353
+ from fastapi_augment.db.sqlalchemy import parse_where
354
+
355
+ # 昵称含张 且 状态非禁用
356
+ expr = parse_where('nickname~=张;status!=0', User)
357
+
358
+ # 括号内 OR,与区间 AND
359
+ expr = parse_where('(nickname~=张,username~=王);age~20~30', User)
360
+ ```
361
+
362
+ #### lookup 精确匹配
363
+
364
+ ```python
365
+ from fastapi_augment.db.sqlalchemy import parse_lookup
366
+
367
+ # 单字段精确匹配
368
+ expr = parse_lookup('phone==13800138000', User, fields={'phone', 'email'})
369
+
370
+ # 多字段 AND(; 分隔)
371
+ expr = parse_lookup('phone==138;status==1', User, fields={'phone', 'status'})
372
+ ```
373
+
374
+ #### 关键字搜索
375
+
376
+ ```python
377
+ from fastapi_augment.db.sqlalchemy import parse_keyword
378
+
379
+ # 多字段 OR 模糊搜索
380
+ expr = parse_keyword('admin', 'username,email,nickname', User)
381
+ ```
382
+
383
+ #### 排序
384
+
385
+ ```python
386
+ from fastapi_augment.db.sqlalchemy import parse_sort
387
+
388
+ # - 前缀表示降序,无前缀为升序
389
+ order_by = parse_sort('-created_at,nickname', User)
390
+ ```
391
+
392
+ #### 一键组合 — `build_query_expressions`
393
+
394
+ ```python
395
+ from fastapi_augment.db.sqlalchemy import build_query_expressions
396
+
397
+ expressions, order_by = build_query_expressions(
398
+ User,
399
+ where='status!=0;age>=18',
400
+ q='admin',
401
+ q_field='username,nickname',
402
+ sort='-created_at',
403
+ )
404
+
405
+ # 直接传给 paginate / list
406
+ result = await user_repo.paginate(
407
+ session, page=1, size=10,
408
+ expressions=expressions, order_by=order_by,
409
+ )
410
+ ```
411
+
412
+ ### 数据库迁移 CLI — `fastapi-augment-migrate`
413
+
414
+ 内置 Alembic 迁移工具,提供 `init` / `generate` / `upgrade` 三个子命令,开箱即用。
415
+
416
+ #### 快速开始
417
+
418
+ ```bash
419
+ # 1. 初始化(一次性操作,生成 alembic.ini + migrations/versions/)
420
+ fastapi-augment-migrate init --db-url "sqlite:///test.db"
421
+
422
+ # 2. 生成迁移
423
+ fastapi-augment-migrate generate \
424
+ --message "add_user_table" \
425
+ --models "models,apps.ai.models"
426
+
427
+ # 3. 执行迁移
428
+ fastapi-augment-migrate upgrade
429
+ ```
430
+
431
+ #### 初始化 — `init`
432
+
433
+ 在项目根目录生成 `alembic.ini` 和 `migrations/versions/` 目录。
434
+ 若 `alembic.ini` 已存在则跳过,不会覆盖。
435
+
436
+ ```bash
437
+ # 初始化
438
+ fastapi-augment-migrate init --db-url "sqlite:///test.db"
439
+
440
+ # 指定项目根目录
441
+ fastapi-augment-migrate init --db-url "postgresql+asyncpg://user:pass@host/db" --project-dir /path/to/project
442
+ ```
443
+
444
+ `alembic.ini` 中的 `script_location` 指向库内的 `env.py`,`version_locations` 指向本地 `migrations/versions/`。
445
+ `env.py` 通过环境变量 `FASTAPI_AUGMENT_MODELS` 动态导入用户模型,无需手动修改。
446
+
447
+ #### 生成迁移 — `generate`
448
+
449
+ 通过 `--models` 指定模型模块(逗号分隔),调用 `alembic revision --autogenerate` 生成迁移脚本。
450
+ 需要先执行 `init` 初始化。
451
+
452
+ ```bash
453
+ # 生成迁移
454
+ fastapi-augment-migrate generate \
455
+ --message "add_user_table" \
456
+ --models "models,apps.ai.models"
457
+
458
+ # 指定项目根目录
459
+ fastapi-augment-migrate generate \
460
+ --message "add_item" \
461
+ --models "apps.ai.models" \
462
+ --project-dir /path/to/project
463
+ ```
464
+
465
+ 迁移文件生成在 `<项目根>/migrations/versions/` 目录下。
466
+
467
+ #### 升级 / 降级 — `upgrade`
468
+
469
+ `--db-url` 为可选参数,不传时直接从 `alembic.ini` 读取 `sqlalchemy.url`。
470
+
471
+ ```bash
472
+ # 升级到最新版本(从 alembic.ini 读取数据库 URL)
473
+ fastapi-augment-migrate upgrade
474
+
475
+ # 指定数据库 URL(覆盖 alembic.ini 中的配置)
476
+ fastapi-augment-migrate upgrade --db-url "sqlite:///test.db"
477
+
478
+ # 升级到指定版本
479
+ fastapi-augment-migrate upgrade --revision abc123
480
+
481
+ # 降级一个版本
482
+ fastapi-augment-migrate upgrade --downgrade
483
+
484
+ # 降级到指定版本
485
+ fastapi-augment-migrate upgrade --downgrade --revision abc123
486
+
487
+ # 指定项目根目录
488
+ fastapi-augment-migrate upgrade --project-dir /path/to/project
489
+ ```
490
+
491
+ #### CLI 参数一览
492
+
493
+ | 子命令 | 参数 | 说明 |
494
+ | ---------- | --------------- | --------------------------------------- |
495
+ | `init` | `--db-url` | 数据库 URL(默认 `sqlite:///app.db`) |
496
+ | | `--project-dir` | 项目根目录(默认当前目录) |
497
+ | `generate` | `--message` | **必填**,迁移描述 |
498
+ | | `--models` | **必填**,模型模块路径,逗号分隔 |
499
+ | | `--project-dir` | 项目根目录(默认当前目录) |
500
+ | `upgrade` | `--db-url` | 数据库 URL(不传则从 alembic.ini 读取) |
501
+ | | `--revision` | 目标版本(默认 `head`) |
502
+ | | `--downgrade` | 降级模式 |
503
+ | | `--project-dir` | 项目根目录(默认当前目录) |
504
+
505
+ ### 模型 Mixin — `db.sqlalchemy.mixins`
506
+
507
+ 可组合的列混入,按需叠加:
508
+
509
+ | Mixin | 提供的列 |
510
+ | ---------------------- | ------------------------------------------ |
511
+ | `CreatedAtMixin` | `created_at` |
512
+ | `TimestampMixin` | `created_at` + `updated_at` |
513
+ | `CreatedByMixin` | `created_by` |
514
+ | `UpdatedByMixin` | `updated_by` |
515
+ | `AuditMixin` | `created_by` + `updated_by` |
516
+ | `SoftDeleteMixin` | `is_deleted` + `deleted_at` |
517
+ | `SoftDeleteAuditMixin` | `is_deleted` + `deleted_at` + `deleted_by` |
518
+
519
+ ```python
520
+ from fastapi_augment.db.sqlalchemy import ModelBase
521
+ from fastapi_augment.db.sqlalchemy.mixins import TimestampMixin, SoftDeleteMixin
522
+
523
+ class User(TimestampMixin, SoftDeleteMixin, ModelBase):
524
+ __tablename__ = 'users'
525
+ name: str
526
+ ```
527
+
528
+ ### 统一响应 — `schemas`
529
+
530
+ #### `APIResponse` — 全局返回格式
531
+
532
+ ```json
533
+ {
534
+ "request_id": "019xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
535
+ "code": 0,
536
+ "message": "操作成功",
537
+ "data": { ... },
538
+ "extra": null
539
+ }
540
+ ```
541
+
542
+ `request_id` 自动从 `ContextVar` 获取,无需手动传递。
543
+
544
+ #### 工厂函数
545
+
546
+ ```python
547
+ from fastapi_augment.schemas import response_success, response_fail
548
+
549
+ # 成功响应
550
+ return response_success(data=user)
551
+ return response_success(data=users, extra={'total': 100})
552
+
553
+ # 失败响应
554
+ return response_fail(code=40001, message='用户名已存在')
555
+ ```
556
+
557
+ #### 请求参数模型
558
+
559
+ ```python
560
+ from fastapi_augment.schemas import PageParams, TimeRangeParams, KeywordParams
561
+
562
+ # 分页参数
563
+ @router.get('/users')
564
+ async def list_users(params: PageParams = Depends()):
565
+ ...
566
+
567
+ # 时间范围 + 关键词搜索
568
+ @router.get('/orders')
569
+ async def list_orders(
570
+ time_range: TimeRangeParams = Depends(),
571
+ keyword: KeywordParams = Depends(),
572
+ ):
573
+ ...
574
+ ```
575
+
576
+ ### HTTP 异常 — `common.exceptions`
577
+
578
+ 完整的 4xx 异常子类,内置默认文案。子类只需声明 `_status_code` 类变量,无需重写 `__init__`:
579
+
580
+ ```python
581
+ from fastapi_augment.common.exceptions import (
582
+ BadRequestError, # 400
583
+ UnauthorizedError, # 401
584
+ ForbiddenError, # 403
585
+ NotFoundError, # 404
586
+ ConflictError, # 409
587
+ TooManyRequestsError, # 429(支持 retry_after 参数)
588
+ # ... 更多异常
589
+ )
590
+
591
+ # 使用默认文案
592
+ raise NotFoundError()
593
+
594
+ # 自定义提示
595
+ raise BadRequestError(detail='用户名不能为空')
596
+
597
+ # 限流场景
598
+ raise TooManyRequestsError(retry_after=60)
599
+ ```
600
+
601
+ ### 日志管理 — `logger`
602
+
603
+ 导入即生效:自动注入 `request_id` 到每条日志、接管 uvicorn/fastapi 日志输出。
604
+
605
+ ```python
606
+ from fastapi_augment.logger import setup_logger, set_log_level
607
+
608
+ # 一键配置:控制台 + 按天轮转文件日志
609
+ setup_logger(log_dir='./logs', rotation='day', backup_count=30)
610
+
611
+ # 动态调整日志级别
612
+ set_log_level('info')
613
+ ```
614
+
615
+ **支持的轮转粒度:**
616
+
617
+ | 粒度 | 说明 |
618
+ | ---------------------------------- | -------------------- |
619
+ | `'second'` / `'minute'` / `'hour'` | 每整秒/分/点 |
620
+ | `'day'`(默认) | 每天 00:00 |
621
+ | `'week'` | 每周一 00:00 |
622
+ | `'month'` | 每月 1 日 00:00 |
623
+ | `'year'` | 每年 1 月 1 日 00:00 |
624
+
625
+ **核心能力:**
626
+
627
+ - **request_id 注入** — 每条日志自动携带当前请求的 `request_id`,方便链路追踪
628
+ - **uvicorn 接管** — 统一 `uvicorn.error` / `uvicorn.access` 的日志名称为 `uvicorn`,屏蔽第三方库 DEBUG 噪声
629
+ - **多进程安全** — 日志轮转时捕获 `OSError`(含 `PermissionError`、`FileNotFoundError`),兼容多进程部署(如 `uvicorn --workers N`)
630
+ - **幂等初始化** — 重复导入或多次调用 `setup_logger()` 不会叠加处理器或工厂链
631
+ - **控制台开关** — `enable_console=False` 可关闭控制台输出,仅保留文件日志
632
+
633
+ ### 健康检查 — `health`
634
+
635
+ 可扩展的检查器模式,内置应用状态与数据库连通性检查。
636
+
637
+ #### 一行启用
638
+
639
+ ```python
640
+ app = create_app(
641
+ title='My Service',
642
+ engine_manager=manager,
643
+ health_check=True, # 自动注册 /health 端点
644
+ )
645
+ ```
646
+
647
+ `GET /health` 响应示例:
648
+
649
+ ```json
650
+ {
651
+ "status": "healthy",
652
+ "checks": [
653
+ {
654
+ "name": "app",
655
+ "status": "healthy",
656
+ "latencyMs": 0,
657
+ "details": {
658
+ "status": "running",
659
+ "version": "1.0.0",
660
+ "uptimeSeconds": 3600
661
+ }
662
+ },
663
+ { "name": "database", "status": "healthy", "latencyMs": 2.3 }
664
+ ]
665
+ }
666
+ ```
667
+
668
+ - 总体状态取所有检查项中**最差**的(healthy < degraded < unhealthy)
669
+ - 任一检查项 unhealthy 时 HTTP 返回 **503**,便于负载均衡器/探针识别
670
+ - 传入 `engine_manager` 时自动包含数据库检查,否则仅检查应用状态
671
+
672
+ #### 自定义检查器
673
+
674
+ ```python
675
+ from fastapi_augment.health import BaseChecker, CheckResult, create_health_router
676
+
677
+ class RedisChecker(BaseChecker):
678
+ @property
679
+ def name(self) -> str:
680
+ return 'redis'
681
+
682
+ async def check(self, app) -> CheckResult:
683
+ # 检查 Redis 连通性
684
+ ...
685
+
686
+ # 手动注册(适合需要自定义路径或额外检查器的场景)
687
+ app.include_router(create_health_router(
688
+ path='/health',
689
+ extra_checkers=[RedisChecker()],
690
+ ))
691
+ ```
692
+
693
+ ### 配置管理 — `config`
694
+
695
+ 基于 `pydantic-settings`,支持多种配置来源(环境变量、.env、JSON、YAML、TOML),通过不同类方法加载:
696
+
697
+ ```python
698
+ from fastapi_augment.config import AugmentBaseSettings
699
+
700
+ class Settings(AugmentBaseSettings):
701
+ database_url: str
702
+ redis_url: str = ''
703
+ debug: bool = False
704
+ secret_key: str = 'change-me'
705
+
706
+ # 从环境变量加载
707
+ cfg = Settings.from_env(env_prefix='APP_', env_nested_delimiter='__')
708
+
709
+ # 从 .env 文件加载
710
+ cfg = Settings.from_dotenv('.env', env_prefix='APP_')
711
+
712
+ # 从 JSON / YAML / TOML 文件加载
713
+ cfg = Settings.from_json('config.json')
714
+ cfg = Settings.from_yaml('config.yaml')
715
+ cfg = Settings.from_toml('config.toml')
716
+ ```
717
+
718
+ 支持 `SettingsConfigDict` 的所有参数(`env_prefix`、`secrets_dir`、`yaml_file` 等),
719
+ 与模型字段值自动区分,无需关心分类。
720
+
721
+ ### 中间件 — `middlewares`
722
+
723
+ #### `RequestIdMiddleware`
724
+
725
+ 自动为每个请求生成/传递 `request_id`(ULID 格式),通过 `ContextVar` 在全链路中可用:
726
+
727
+ ```python
728
+ from fastapi_augment.middlewares import get_request_id
729
+
730
+ request_id = get_request_id()
731
+ ```
732
+
733
+ ### 应用发现 — `common.app_discovery`
734
+
735
+ 递归发现 `apps` 包下所有子包通过 `__all__` 导出的 FastAPI 应用实例,用于多应用聚合部署与启动前校验。
736
+
737
+ **约定:** 每个业务子包(如 `apps.platform`)在 `__init__.py` 的 `__all__` 中导出自己创建的 FastAPI 实例(如 `platform_app`);只有出现在 `__all__` 且确实是 `FastAPI` 实例的对象才被识别为"应用"。
738
+
739
+ ```python
740
+ from fastapi_augment.common import discover_fastapi_apps, FastAPIAppSpec, validate_asgi_import
741
+
742
+ # 发现全部应用(排除主应用,获取主应用之外的其它应用)
743
+ apps: list[FastAPIAppSpec] = discover_fastapi_apps(root='apps', exclude='apps.platform:platform_app')
744
+
745
+ # 每个应用可直接启动(import_string 即 uvicorn 导入串)
746
+ for spec in apps:
747
+ uvicorn.run(spec.import_string) # 'apps.platform:platform_app'
748
+
749
+ # 启动前校验主应用导入串是否真实存在且为 FastAPI 实例
750
+ validate_asgi_import('apps.platform:platform_app')
751
+ ```
752
+
753
+ - **`exclude` 支持三种标识** — 模块名(`apps.platform`)、导出名(`platform_app`)或 `module:name` 导入串(`apps.platform:platform_app`)
754
+ - 结果按模块名排序,顺序稳定
755
+
756
+ ## 开发与发布
757
+
758
+ ### 分支策略
759
+
760
+ - **`master`** — 受保护分支,**禁止直接提交代码**,仅可通过其它分支 PR 合并
761
+ - **`develop`**(或功能分支)— 日常开发与版本号更新,完成后通过 PR 合并到 `master`
762
+ - 发布类操作(Release 打 tag / 上传、PyPI 发布)**仅 `master` 分支可执行**,workflow 已做分支校验
763
+
764
+ ### 代码检查与测试
765
+
766
+ ```bash
767
+ # lint(读取 pyproject.toml 的 [tool.ruff] 配置)
768
+ uvx ruff check src tests
769
+
770
+ # 测试
771
+ uv run --frozen pytest -q
772
+ ```
773
+
774
+ CI 已配置自动检查(`.github/workflows/lint.yml`):每次 push / PR 自动运行 ruff。
775
+
776
+ ### 发布 Release
777
+
778
+ `.github/workflows/release.yml` 触发方式:
779
+
780
+ - **推送到 `master`(自动)** — 本次合并变更了 `VERSION` 时自动发布新版本(打 tag + 上传 GitHub Release);未变更则跳过,避免重复发布
781
+ - **master 分支手动触发**(workflow_dispatch)— `release` 发布新版本 / `rebuild` 重新打包指定版本
782
+
783
+ 发布类操作仅 master 分支可执行,自动完成:
784
+
785
+ 1. **检查** — pytest + ruff,任一失败即停止,不发布
786
+ 2. **确定版本** — 无 tag 用代码版本(`VERSION` 文件);代码版本 > 最高 tag 用代码版本;否则以最高 tag 版本为准
787
+ 3. **校验版本一致性** — 目标版本与代码版本不一致时终止并引导(master 受保护,需先在 `develop` 更新 `VERSION` 与 `factory.py` 版本,PR 合并后重试)
788
+ 4. **打包** — 源码打包为 `fastapi_augment-<版本>.zip` / `.tar.gz`(排除 `.venv`、缓存、构建产物)
789
+ 5. **打 tag + 发布** — 打包成功后才创建/更新 `v<版本>` tag 并上传 GitHub Release;失败不留任何 tag/Release,重试不会跳版本
790
+
791
+ 建议发布前先在 `develop` 分支完成版本号更新并 PR 合并到 `master`——合并触发自动发布,发布流程将直接复用代码版本。
792
+
793
+ PyPI 发布(`.github/workflows/publish.yml`)同样支持合并 `master` 自动触发,仅 `VERSION` 变更时发布(PyPI 版本不可覆盖)。
794
+
795
+ 支持两种模式:
796
+
797
+ - **release**(默认)— 按版本规则发布新版本
798
+ - **rebuild** — 指定已有 tag(如 `v1.2.3`)重新打包上传,不修改代码版本
799
+
800
+ ## 项目结构
801
+
802
+ ```
803
+ fastapi_augment/
804
+ ├── common/
805
+ │ ├── app_discovery.py # FastAPI 应用发现(__all__ 约定)
806
+ │ ├── constants.py # 全局常量与默认错误文案
807
+ │ ├── exceptions.py # 4xx HTTP 异常体系
808
+ │ ├── exception_handlers.py # 全局异常处理器
809
+ │ └── utils/
810
+ │ ├── paths.py # 路径工具(get_root_dir / find_project_root)
811
+ │ └── strings.py # 字符串工具 / JSON 序列化
812
+ ├── config/
813
+ │ ├── base_settings.py # AugmentBaseSettings 配置管理
814
+ │ └── database_settings.py # DatabaseSettings 数据库配置
815
+ ├── db/
816
+ │ └── sqlalchemy/
817
+ │ ├── engine.py # EngineManager / NodeConfig / ClusterTopology
818
+ │ ├── session.py # SessionFactory(读写分离)
819
+ │ ├── model_base.py # ModelBase(ULID 主键)
820
+ │ ├── repository_base.py # RepositoryBase(泛型仓储 + paginate)
821
+ │ ├── query_parser.py # 查询解析器(where / lookup / keyword / sort)
822
+ │ ├── migrate.py # 数据库迁移 CLI
823
+ │ ├── migrations/ # Alembic 迁移环境(env.py / script.py.mako)
824
+ │ └── mixins/ # Timestamp / Audit / SoftDelete
825
+ ├── health/
826
+ │ ├── checker.py # BaseChecker / CheckResult / HealthResponse
827
+ │ ├── checkers.py # AppChecker / DatabaseChecker
828
+ │ └── router.py # create_health_router()
829
+ ├── logger/
830
+ │ ├── record_factory.py # request_id 注入工厂
831
+ │ ├── filters.py # UvicornNameRewriteFilter
832
+ │ ├── handlers.py # 多进程安全轮转处理器
833
+ │ └── setup.py # setup_logger / set_log_level / set_log_format
834
+ ├── middlewares/
835
+ │ ├── base.py # BaseASGIMiddleware
836
+ │ └── request_id.py # RequestId 中间件
837
+ ├── schemas/
838
+ │ ├── base.py # SchemaBase / ORMSchemaBase
839
+ │ ├── request.py # PageParams / TimeRangeParams / KeywordParams
840
+ │ ├── response.py # APIResponse / response_success / response_fail
841
+ │ └── pagination.py # PageData 分页模型
842
+ ├── factory.py # create_app 应用工厂
843
+ ├── lifespan.py # HookRegistry 生命周期管理
844
+ └── openapi.py # OpenAPI schema 优化
845
+ ```
846
+
847
+ ## 许可证
848
+
849
+ MIT