You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
7 months ago | |
|---|---|---|
| .. | ||
| HTTP_RESPONSE_UTILS.md | 7 months ago | |
| LIMITER_CONFIG.md | 7 months ago | |
| README.md | 7 months ago | |
README.md
iTi-Flask 项目文档
📚 文档索引
核心文档
- HTTP_RESPONSE_UTILS.md - HTTP 响应包装工具使用指南
🎯 快速开始
HTTP 响应工具
统一的 API 响应格式包装工具,提供 success(), fail(), page() 等函数。
from iti.applications.common.utils import success, fail, page
# 成功响应
@app.get('/api/users/<int:user_id>')
def get_user(user_id):
user = User.query.get(user_id)
return success(user, message='获取成功')
# 失败响应
@app.get('/api/users/<int:user_id>')
def get_user(user_id):
user = User.query.get(user_id)
if not user:
return fail('用户不存在', code=404)
return success(user)
# 分页响应
@app.get('/api/users')
def get_users():
pagination = User.query.paginate(page=1, per_page=10)
return page(pagination, message='获取用户列表成功')
详细文档: HTTP_RESPONSE_UTILS.md
🗂️ 项目结构
back/
├── docs/ # 📚 文档目录
│ ├── README.md # 文档索引(本文件)
│ └── HTTP_RESPONSE_UTILS.md # HTTP 工具使用指南
│
├── src/
│ ├── applications/
│ │ ├── __init__.py # 应用工厂
│ │ ├── extensions/ # 扩展初始化
│ │ │ ├── http.py # BaseResponse Schema
│ │ │ └── ...
│ │ └── common/
│ │ └── utils/
│ │ ├── __init__.py # 工具导出
│ │ └── http.py # 🔥 HTTP 响应包装工具
│ │
│ ├── config.py # 配置文件
│ └── app.py # 应用入口
│
├── tests/ # 测试目录
├── hatch.toml # Hatch 配置
└── pyproject.toml # 项目配置
🔧 工具模块
applications.common.utils
提供的函数:
| 函数 | 说明 | 示例 |
|---|---|---|
success() |
成功响应包装 | return success(data, message='成功') |
fail() |
失败响应包装 | return fail('错误', code=404) |
page() |
分页响应包装 | return page(pagination) |
pagination_builder() |
分页信息构建器 | pagination_builder(None, page=1, size=10, total=100) |
提供的 Schema:
| Schema | 说明 |
|---|---|
PaginationSchema |
分页信息 Schema(per_page → size) |
PageDataSchema |
分页数据 Schema |
📝 编码规范
1. 统一返回格式
所有 API 响应必须使用统一格式:
{
"data": <返回数据>,
"code": <业务状态码>,
"message": <提示信息>
}
2. HTTP 状态码
- ✅ 成功和业务失败都返回 HTTP 200
- ✅ 由
code字段区分业务状态 - ✅ 前端统一处理,无需捕获 HTTP 异常
3. 分页参数
- ✅ 使用
page表示页码(从 1 开始) - ✅ 使用
size表示每页数量(不是per_page)
示例:
GET /api/users?page=1&size=10
🧪 测试
运行测试
# 运行 HTTP 工具测试
hatch run test tests/test_http_utils.py -v
# 运行所有测试
hatch run test
# 带详细输出
hatch run test -v
测试覆盖率
# 生成覆盖率报告
hatch run cov
# 查看 HTML 报告
# 打开 htmlcov/index.html
测试统计
| 测试文件 | 测试数量 | 说明 |
|---|---|---|
test_config.py |
7 个 | 配置相关测试 |
test_limiter.py |
6 个 | 限流器测试 |
test_http_utils.py |
33 个 | HTTP 工具测试 |
| 总计 | 46 个 | 全部通过 ✅ |
🚀 开发环境
启动开发服务器
hatch run dev
生产环境
hatch run prod:start
📖 相关链接
最后更新: 2025-10-14
维护者: iTi-Flask Team