# TurboAPI **Repository Path**: python_90/turbo_api ## Basic Information - **Project Name**: TurboAPI - **Description**: TurboAPI - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-04-30 - **Last Updated**: 2026-04-30 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # TurboAPI 快速开发脚手架 基于 **TurboAPI** + **Tortoise-ORM** + **JWT 认证** + **Loguru 日志** 的快速开发脚手架,采用分层架构设计。 ## ✨ 特性 - ⚡ **TurboAPI** - 高性能异步 Web 框架 - 🗄️ **Tortoise-ORM** - 异步 ORM,支持多种数据库 - 🔐 **JWT 认证** - 完整的认证授权系统 - 📝 **Loguru** - 现代化日志管理 - 🔄 **Aerich** - 数据库迁移管理 - 📐 **分层架构** - API层 -> Service层 -> Model层 - 🛡️ **中间件** - CORS/日志/错误处理中间件 - 📦 **模块化设计** - 易于扩展和维护 ## 🏗️ 项目结构(分层架构) ``` TurboAPI/ ├── app/ │ ├── api/ # API 层 - 路由定义与请求处理 │ │ ├── auth.py # 认证接口(注册/登录/刷新) │ │ ├── users.py # 用户管理(CRUD) │ │ └── todos.py # 待办事项(CRUD) │ ├── services/ # Service 层 - 业务逻辑 │ │ ├── __init__.py │ │ ├── auth_service.py # 认证业务逻辑 │ │ ├── user_service.py # 用户业务逻辑 │ │ └── todo_service.py # 待办事项业务逻辑 │ ├── schemas/ # Schema 层 - 数据验证与序列化 │ │ ├── __init__.py │ │ ├── base.py # 基础验证工具 │ │ ├── auth_schema.py # 认证数据验证 │ │ ├── user_schema.py # 用户数据验证 │ │ └── todo_schema.py # 待办数据验证 │ ├── models/ # Model 层 - 数据模型 │ │ ├── __init__.py │ │ ├── user.py # 用户模型 │ │ └── todo.py # 待办事项模型 │ ├── middleware/ # 中间件层 │ │ ├── __init__.py │ │ ├── logging_middleware.py # 请求日志中间件 │ │ ├── cors_middleware.py # 跨域中间件 │ │ └── error_middleware.py # 错误处理中间件 │ ├── core/ # 核心配置层 │ │ ├── config.py # 配置读取(.env) │ │ ├── logger.py # Loguru 日志配置 │ │ └── security.py # JWT/密码加密 │ ├── dependencies.py # 依赖注入(认证) │ └── router.py # 路由配置中心 ├── main.py # 应用入口 ├── pyproject.toml # 依赖配置 ├── .env # 环境变量配置 ├── .gitignore # Git 忽略规则 ├── migrate.bat # 数据库迁移脚本 ├── run.bat # 启动脚本 └── README.md # 文档 ``` ## 📐 分层架构说明 ``` ┌─────────────────────────────────────┐ │ Middleware 层 │ ← CORS / 日志 / 错误处理 │ Logging / CORS / Error │ ├─────────────────────────────────────┤ │ API 层 (Controllers) │ ← 路由定义、请求解析 │ auth.py / users.py / todos.py │ ├─────────────────────────────────────┤ │ Service 层 (Services) │ ← 业务逻辑 │ auth_service / user_service / ... │ ├─────────────────────────────────────┤ │ Schema 层 (Schemas) │ ← 数据验证 │ auth_schema / user_schema / ... │ ├─────────────────────────────────────┤ │ Model 层 (Models) │ ← 数据模型 │ User / Todo (Tortoise) │ └─────────────────────────────────────┘ ``` ### 各层职责 | 层级 | 职责 | 关键文件 | |------|------|----------| | **Middleware** | 请求预处理、跨域、日志、异常捕获 | `logging_middleware.py` | | **API** | 路由定义、参数解析、调用 Service | `router.py`, `auth.py` | | **Service** | 业务逻辑、调用 Model、返回结果 | `auth_service.py` | | **Schema** | 数据验证、类型转换、响应格式化 | `auth_schema.py` | | **Model** | 数据定义、数据库操作 | `user.py` | ## 🚀 快速开始 ### 1. 运行项目 ```bash # 运行应用(uv 会自动创建环境并安装依赖) run.bat ``` 或使用命令行: ```bash uv run main.py ``` ### 2. 初始化数据库 ```bash migrate.bat init ``` ### 3. 访问 API - API 文档: http://localhost:8000/docs - 健康检查: http://localhost:8000/health ## 📚 API 文档 ### 通用规范 #### 请求格式 - 请求体使用 JSON 格式 - Content-Type: `application/json` #### 响应格式 ```json { "success": true, // 操作是否成功 "message": "提示信息", // 操作结果描述 "data": {}, // 返回数据(可选) "error": null // 错误信息(失败时) } ``` #### 分页响应 ```json { "data": [...], "total": 100, // 总记录数 "skip": 0, // 跳过条数 "limit": 20, // 每页条数 "has_more": true // 是否还有更多 } ``` #### 状态码 | 状态码 | 含义 | 说明 | |--------|------|------| | 200 | OK | 请求成功 | | 201 | Created | 创建成功 | | 400 | Bad Request | 请求参数错误 | | 401 | Unauthorized | 未认证或令牌过期 | | 403 | Forbidden | 权限不足 | | 404 | Not Found | 资源不存在 | | 500 | Internal Server Error | 服务器内部错误 | --- ### 认证接口 #### 1. 用户注册 **POST** `/auth/register` **权限**: 公开 **请求参数**: | 字段 | 类型 | 必填 | 说明 | |------|------|------|------| | username | string | ✅ | 用户名,3-50字符,唯一 | | email | string | ✅ | 邮箱,唯一 | | password | string | ✅ | 密码,最少6位 | | full_name | string | ❌ | 全名 | **请求示例**: ```json { "username": "john_doe", "email": "john@example.com", "password": "123456", "full_name": "John Doe" } ``` **响应示例** (201): ```json { "message": "注册成功", "user": { "id": 1, "username": "john_doe", "email": "john@example.com", "full_name": "John Doe", "is_active": true, "is_superuser": false, "created_at": "2024-01-15T08:30:00", "last_login": null } } ``` **错误码**: - `400` - 用户名已存在 / 邮箱已被注册 / 参数验证失败 --- #### 2. 用户登录 **POST** `/auth/login` **权限**: 公开 **请求参数**: | 字段 | 类型 | 必填 | 说明 | |------|------|------|------| | username | string | ✅ | 用户名 | | password | string | ✅ | 密码 | **请求示例**: ```json { "username": "john_doe", "password": "123456" } ``` **响应示例** (200): ```json { "access_token": "eyJhbGciOiJIUzI1NiIs...", "refresh_token": "eyJhbGciOiJIUzI1NiIs...", "token_type": "bearer", "user": { "id": 1, "username": "john_doe", "email": "john@example.com", "full_name": "John Doe" } } ``` **错误码**: - `401` - 用户名或密码错误 / 用户已被禁用 --- #### 3. 刷新令牌 **POST** `/auth/refresh` **权限**: 公开 **请求参数**: | 字段 | 类型 | 必填 | 说明 | |------|------|------|------| | refresh_token | string | ✅ | 刷新令牌 | **请求示例**: ```json { "refresh_token": "eyJhbGciOiJIUzI1NiIs..." } ``` **响应示例** (200): ```json { "access_token": "eyJhbGciOiJIUzI1NiIs...", "token_type": "bearer" } ``` **错误码**: - `401` - 刷新令牌无效或已过期 --- #### 4. 获取当前用户信息 **GET** `/auth/me` **权限**: 需登录 **请求头**: ``` Authorization: Bearer ``` **响应示例** (200): ```json { "id": 1, "username": "john_doe", "email": "john@example.com", "full_name": "John Doe", "is_active": true, "is_superuser": false, "created_at": "2024-01-15T08:30:00", "last_login": "2024-01-15T09:00:00" } ``` **错误码**: - `401` - 令牌无效或已过期 --- ### 用户管理接口 > ⚠️ **注意**: 以下接口需要管理员权限 (`is_superuser=true`) #### 1. 获取用户列表 **GET** `/users` **权限**: 管理员 **查询参数**: | 参数 | 类型 | 默认值 | 说明 | |------|------|--------|------| | skip | int | 0 | 跳过条数(分页) | | limit | int | 100 | 返回条数,最大100 | **请求示例**: ``` GET /users?skip=0&limit=20 ``` **响应示例** (200): ```json { "data": [ { "id": 1, "username": "john_doe", "email": "john@example.com", "full_name": "John Doe", "is_active": true, "is_superuser": false, "created_at": "2024-01-15T08:30:00" } ], "total": 50, "skip": 0, "limit": 20, "has_more": true } ``` --- #### 2. 创建用户 **POST** `/users` **权限**: 管理员 **请求参数**: | 字段 | 类型 | 必填 | 说明 | |------|------|------|------| | username | string | ✅ | 用户名,唯一 | | email | string | ✅ | 邮箱,唯一 | | password | string | ✅ | 密码 | | full_name | string | ❌ | 全名 | | is_superuser | bool | ❌ | 是否管理员,默认false | **请求示例**: ```json { "username": "new_user", "email": "new@example.com", "password": "123456", "full_name": "New User", "is_superuser": false } ``` **响应示例** (201): ```json { "message": "用户创建成功", "data": { "id": 2, "username": "new_user", "email": "new@example.com", "full_name": "New User", "is_active": true, "is_superuser": false, "created_at": "2024-01-15T10:00:00" } } ``` --- #### 3. 获取用户详情 **GET** `/users/{id}` **权限**: 管理员 **路径参数**: | 参数 | 类型 | 说明 | |------|------|------| | id | int | 用户ID | **响应示例** (200): ```json { "id": 1, "username": "john_doe", "email": "john@example.com", "full_name": "John Doe", "is_active": true, "is_superuser": false, "created_at": "2024-01-15T08:30:00", "last_login": "2024-01-15T09:00:00" } ``` **错误码**: - `404` - 用户不存在 --- #### 4. 更新用户 **PUT** `/users/{id}` **权限**: 管理员 **路径参数**: | 参数 | 类型 | 说明 | |------|------|------| | id | int | 用户ID | **请求参数** (全部可选): | 字段 | 类型 | 说明 | |------|------|------| | email | string | 新邮箱 | | full_name | string | 新全名 | | password | string | 新密码 | | is_active | bool | 是否启用 | | is_superuser | bool | 是否管理员 | **请求示例**: ```json { "full_name": "Updated Name", "is_active": false } ``` **响应示例** (200): ```json { "message": "用户更新成功", "data": { "id": 1, "username": "john_doe", "full_name": "Updated Name", "is_active": false } } ``` **错误码**: - `400` - 没有要更新的字段 / 参数验证失败 - `404` - 用户不存在 --- #### 5. 删除用户 **DELETE** `/users/{id}` **权限**: 管理员 **路径参数**: | 参数 | 类型 | 说明 | |------|------|------| | id | int | 用户ID | **响应示例** (200): ```json { "message": "用户删除成功" } ``` **错误码**: - `404` - 用户不存在 --- ### 待办事项接口 > 🔒 **注意**: 以下接口需要登录,用户只能访问自己的待办事项 #### 1. 获取待办列表 **GET** `/todos` **权限**: 需登录 **查询参数**: | 参数 | 类型 | 默认值 | 说明 | |------|------|--------|------| | skip | int | 0 | 跳过条数(分页) | | limit | int | 100 | 返回条数,最大100 | | completed | bool | - | 筛选完成状态(true/false) | **请求示例**: ``` GET /todos?skip=0&limit=20&completed=false ``` **响应示例** (200): ```json { "data": [ { "id": 1, "title": "学习 TurboAPI", "description": "掌握分层架构", "completed": false, "priority": 1, "created_at": "2024-01-15T08:30:00", "updated_at": "2024-01-15T08:30:00", "completed_at": null } ], "total": 15, "skip": 0, "limit": 20, "has_more": false } ``` --- #### 2. 创建待办事项 **POST** `/todos` **权限**: 需登录 **请求参数**: | 字段 | 类型 | 必填 | 说明 | |------|------|------|------| | title | string | ✅ | 标题,1-200字符 | | description | string | ❌ | 描述,最多1000字符 | | priority | int | ❌ | 优先级,1-5,默认1 | | due_date | string | ❌ | 截止日期,ISO 8601格式 | **请求示例**: ```json { "title": "完成项目文档", "description": "编写 API 文档和使用说明", "priority": 2, "due_date": "2024-01-20T18:00:00" } ``` **响应示例** (201): ```json { "success": true, "message": "创建成功", "data": { "id": 1, "title": "完成项目文档", "description": "编写 API 文档和使用说明", "completed": false, "priority": 2, "created_at": "2024-01-15T10:00:00", "updated_at": "2024-01-15T10:00:00", "due_date": "2024-01-20T18:00:00" } } ``` --- #### 3. 获取待办详情 **GET** `/todos/{id}` **权限**: 需登录 **路径参数**: | 参数 | 类型 | 说明 | |------|------|------| | id | int | 待办事项ID | **响应示例** (200): ```json { "success": true, "data": { "id": 1, "title": "完成项目文档", "description": "编写 API 文档和使用说明", "completed": false, "priority": 2, "created_at": "2024-01-15T10:00:00", "updated_at": "2024-01-15T10:00:00", "completed_at": null, "due_date": "2024-01-20T18:00:00" } } ``` **错误码**: - `404` - 待办事项不存在或无权访问 --- #### 4. 更新待办事项 **PUT** `/todos/{id}` **权限**: 需登录 **路径参数**: | 参数 | 类型 | 说明 | |------|------|------| | id | int | 待办事项ID | **请求参数** (全部可选): | 字段 | 类型 | 说明 | |------|------|------| | title | string | 新标题 | | description | string | 新描述 | | completed | bool | 完成状态 | | priority | int | 优先级 1-5 | | due_date | string | 新截止日期 | **请求示例**: ```json { "title": "更新后的标题", "completed": true, "priority": 3 } ``` **响应示例** (200): ```json { "success": true, "message": "更新成功", "data": { "id": 1, "title": "更新后的标题", "completed": true, "priority": 3, "updated_at": "2024-01-15T11:00:00", "completed_at": "2024-01-15T11:00:00" } } ``` **错误码**: - `400` - 没有要更新的字段 / 参数验证失败 - `404` - 待办事项不存在或无权访问 --- #### 5. 删除待办事项 **DELETE** `/todos/{id}` **权限**: 需登录 **路径参数**: | 参数 | 类型 | 说明 | |------|------|------| | id | int | 待办事项ID | **响应示例** (200): ```json { "success": true, "message": "删除成功" } ``` **错误码**: - `404` - 待办事项不存在或无权访问 --- #### 6. 切换完成状态 **PATCH** `/todos/{id}/toggle` **权限**: 需登录 **路径参数**: | 参数 | 类型 | 说明 | |------|------|------| | id | int | 待办事项ID | **说明**: 自动切换 `completed` 状态,true 变 false,false 变 true **响应示例** (200): ```json { "success": true, "message": "已标记为已完成", "data": { "id": 1, "completed": true, "completed_at": "2024-01-15T11:30:00" } } ``` --- #### 7. 获取统计信息 **GET** `/todos/statistics` **权限**: 需登录 **响应示例** (200): ```json { "success": true, "data": { "total": 15, // 总数量 "completed": 8, // 已完成 "pending": 7, // 待完成 "high_priority": 3, // 高优先级(4-5) "overdue": 2 // 已逾期 } } ``` ## 💡 使用示例 ### 1. 注册用户 ```bash curl -X POST http://localhost:8000/auth/register \ -H "Content-Type: application/json" \ -d '{ "username": "admin", "email": "admin@example.com", "password": "admin123", "full_name": "管理员" }' ``` ### 2. 登录获取 Token ```bash curl -X POST http://localhost:8000/auth/login \ -H "Content-Type: application/json" \ -d '{ "username": "admin", "password": "admin123" }' ``` ### 3. 创建待办事项 ```bash curl -X POST http://localhost:8000/todos \ -H "Content-Type: application/json" \ -H "Authorization: Bearer " \ -d '{ "title": "学习 TurboAPI", "description": "掌握分层架构", "priority": 1 }' ``` ### 4. 获取统计信息 ```bash curl -X GET http://localhost:8000/todos/statistics \ -H "Authorization: Bearer " ``` ## 🗄️ 数据库迁移 ```bash # 初始化迁移环境(首次使用) migrate.bat init # 创建迁移(修改模型后) migrate.bat migrate "添加新字段" # 应用迁移 migrate.bat upgrade # 查看迁移历史 migrate.bat history # 降级数据库 migrate.bat downgrade ``` ## ⚙️ 配置说明 编辑 [`.env`](.env) 文件配置应用: ```env # 应用配置 APP_NAME=TurboAPI 脚手架 DEBUG=false HOST=0.0.0.0 PORT=8000 # 数据库配置 DATABASE_URL=sqlite://db.sqlite3 # JWT 配置 JWT_SECRET_KEY=your-secret-key JWT_ACCESS_TOKEN_EXPIRE_MINUTES=30 # CORS 配置 CORS_ORIGINS=["*"] CORS_ALLOW_METHODS=["*"] CORS_ALLOW_HEADERS=["*"] CORS_ALLOW_CREDENTIALS=true # 日志配置 LOG_LEVEL=INFO LOG_FILE=logs/app.log ``` ## 🔐 权限系统 - **公开接口** - 无需认证:`/auth/*`, `/`, `/health` - **登录用户** - 需要 JWT Token:`/auth/me`, `/todos/*` - **管理员** - 需要 `is_superuser=True`:`/users/*` 在请求头中添加认证: ``` Authorization: Bearer ``` ## 🛡️ 中间件说明 ### 中间件执行顺序 ``` 请求 → ErrorMiddleware → CORSMiddleware → LoggingMiddleware → 路由处理 ``` ### 1. ErrorMiddleware - 捕获所有未处理的异常 - 开发环境返回详细堆栈 - 生产环境返回简洁错误信息 ### 2. CORSMiddleware - 处理跨域请求 - 支持配置允许的来源、方法、头部 ### 3. LoggingMiddleware - 记录所有请求和响应 - 包含请求方法、路径、耗时、状态码 - 记录客户端 IP 和查询参数 ## 🛠️ 开发指南 ### 添加新功能示例 假设要添加 **文章管理** 功能: #### 1. 创建 Model (`app/models/post.py`) ```python from tortoise import fields from tortoise.models import Model class Post(Model): id = fields.IntField(pk=True) title = fields.CharField(max_length=200) content = fields.TextField() user = fields.ForeignKeyField("models.User", related_name="posts") created_at = fields.DatetimeField(auto_now_add=True) def to_dict(self): return { "id": self.id, "title": self.title, "content": self.content, "created_at": self.created_at.isoformat() if self.created_at else None } ``` #### 2. 创建 Schema (`app/schemas/post_schema.py`) ```python from .base import validate_required, validate_string class PostCreate: @staticmethod def validate(data: dict): error = validate_required(data, ["title", "content"]) if error: return None, error return { "title": data["title"].strip(), "content": data["content"] }, None ``` #### 3. 创建 Service (`app/services/post_service.py`) ```python class PostService: @staticmethod async def create_post(user, title, content): post = await Post.create(user=user, title=title, content=content) return post, None @staticmethod async def get_user_posts(user): return await Post.filter(user=user).order_by("-created_at") ``` #### 4. 创建 API (`app/api/posts.py`) ```python class PostController: @staticmethod async def create_post(request, user): body = await request.json() data, error = PostCreate.validate(body) if error: return JSONResponse({"error": error}, 400) post, error = await PostService.create_post(user, **data) return JSONResponse({"data": post.to_dict()}) ``` #### 5. 注册路由 (`app/router.py`) ```python @app.post("/posts") async def create_post(request): user = await get_current_active_user(request) if isinstance(user, JSONResponse): return user return await posts.create_post(request, user) ``` ## 📦 依赖清单 - `turboapi` - Web 框架 - `tortoise-orm` - 异步 ORM - `aerich` - 数据库迁移 - `python-jose` - JWT 处理 - `passlib` - 密码加密 - `python-dotenv` - 环境变量 - `loguru` - 日志管理 - `starlette` - ASGI 工具 ## 📄 License MIT License