# Task_py **Repository Path**: Vallenbo/task_py ## Basic Information - **Project Name**: Task_py - **Description**: 一个基于 FastAPI、MySQL 和 Redis 的完整任务管理系统,提供用户认证、任务管理、日志记录、限流等功能。 学习python项目的该有姿势,学习的一个基本项目,整体学会python web开发 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-03-19 - **Last Updated**: 2026-03-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # Task_py - 任务管理系统 一个基于 FastAPI、MySQL 和 Redis 的完整任务管理系统,提供用户认证、任务管理、日志记录、限流等功能。 学习python项目的该有姿势,学习的一个基本项目,整体学会python web开发 ## 📋 目录 - [项目概述](#项目概述) - [技术栈](#技术栈) - [项目结构](#项目结构) - [环境配置](#环境配置) - [安装与运行](#安装与运行) - [API 文档](#api-文档) - [数据库架构](#数据库架构) - [中间件说明](#中间件说明) - [开发指南](#开发指南) ## 项目概述 ToList 是一个功能完整的任务管理系统,支持: - ✅ 用户注册、登录、认证 - ✅ 任务的创建、读取、更新、删除(CRUD) - ✅ 任务优先级和状态管理 - ✅ 请求日志记录 - ✅ API 限流保护 - ✅ Redis 缓存支持 - ✅ 完整的错误处理 - ✅ CORS 跨域支持 ## 技术栈 | 组件 | 版本 | 说明 | |------|------|------| | FastAPI | ≥0.109.0 | 现代化 Python Web 框架 | | Uvicorn | ≥0.27.0 | ASGI 服务器 | | SQLAlchemy | ≥2.0.25 | ORM 框架 | | MySQL | - | 关系型数据库 | | Redis | ≥5.0.1 | 缓存和会话存储 | | Pydantic | ≥2.0.0 | 数据验证 | | PyJWT | ≥3.3.0 | JWT 令牌处理 | | Passlib | ≥1.7.4 | 密码加密 | ## 项目结构 ``` ToList/ ├── app/ # 应用主目录 │ ├── api/ # API 路由 │ │ ├── users.py # 用户相关接口 │ │ └── tasks.py # 任务相关接口 │ ├── middleware/ # 中间件 │ │ ├── auth.py # 认证中间件 │ │ ├── logging.py # 日志中间件 │ │ └── rate_limit.py # 限流中间件 │ ├── models/ # 数据模型 │ │ ├── user.py # 用户模型 │ │ └── task.py # 任务模型 │ ├── schemas/ # Pydantic 数据验证模式 │ │ ├── user.py # 用户数据验证 │ │ └── task.py # 任务数据验证 │ ├── utils/ # 工具函数 │ │ └── security.py # 安全相关函数 │ ├── config.py # 配置管理 │ ├── database.py # 数据库连接 │ ├── redis_client.py # Redis 客户端 │ ├── exceptions.py # 自定义异常 │ ├── logger.py # 日志配置 │ └── main.py # 应用初始化 ├── logs/ # 日志文件 ├── script/ # 脚本文件 ├── main.py # 应用入口 ├── init_db.py # 数据库初始化脚本 ├── test_api.py # API 测试 ├── requirements.txt # 依赖列表 ├── .env.example # 环境变量示例 └── .gitignore # Git 忽略文件 ``` ## 环境配置 ### 1. 复制配置文件 ```bash cp config.example.yaml config.yaml ``` ### 2. 配置 config.yaml 文件 ```yaml # 应用配置 app: name: ToList version: 1.0.0 host: 0.0.0.0 port: 8000 debug: false environment: development # development, staging, production # 数据库配置 database: host: localhost port: 3306 user: root password: your_password name: python_learning pool_size: 10 max_overflow: 20 pool_recycle: 3600 # Redis 配置 redis: host: localhost port: 6379 db: 0 password: null timeout: 5 # 安全配置 security: secret_key: your-secret-key-change-this-in-production access_token_expire_minutes: 30 # 限流配置 rate_limit: enabled: true max_requests: 100 window_seconds: 60 # 日志配置 logging: level: INFO dir: logs max_bytes: 10485760 # 10MB backup_count: 10 # CORS 配置 cors: origins: - "*" allow_credentials: true allow_methods: - "*" allow_headers: - "*" ``` ## 安装与运行 ### 1. 创建虚拟环境 ```bash uv # Windows .venv\Scripts\activate # Linux/Mac source .venv/bin/activate ``` ### 2. 安装依赖 ```bash pip install -r requirements.txt ``` ### 3. 初始化数据库 ```bash python init_db.py ``` ### 4. 运行应用 ```bash python main.py ``` 应用将在 `http://localhost:8000` 启动 ### 5. 访问 API 文档 - Swagger UI: `http://localhost:8000/docs` - ReDoc: `http://localhost:8000/redoc` - OpenAPI JSON: `http://localhost:8000/openapi.json` ## API 文档 ### 用户相关接口 #### 注册用户 ``` POST /api/users/register Content-Type: application/json { "username": "user123", "email": "user@example.com", "password": "password123" } ``` #### 用户登录 ``` POST /api/users/login Content-Type: application/json { "username": "user123", "password": "password123" } ``` 响应: ```json { "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "token_type": "bearer" } ``` #### 获取当前用户信息 ``` GET /api/users/me Authorization: Bearer {access_token} ``` ### 任务相关接口 #### 创建任务 ``` POST /api/tasks Authorization: Bearer {access_token} Content-Type: application/json { "title": "完成项目文档", "description": "编写项目的完整文档", "priority": "high", "due_date": "2024-12-31T23:59:59" } ``` #### 获取任务列表 ``` GET /api/tasks Authorization: Bearer {access_token} ``` 查询参数: - `status`: 任务状态 (pending, in_progress, completed, cancelled) - `priority`: 优先级 (low, medium, high) - `skip`: 分页偏移 (默认: 0) - `limit`: 分页限制 (默认: 10) #### 获取单个任务 ``` GET /api/tasks/{task_id} Authorization: Bearer {access_token} ``` #### 更新任务 ``` PUT /api/tasks/{task_id} Authorization: Bearer {access_token} Content-Type: application/json { "title": "更新的标题", "status": "in_progress", "priority": "medium" } ``` #### 删除任务 ``` DELETE /api/tasks/{task_id} Authorization: Bearer {access_token} ``` #### 健康检查 ``` GET /health ``` 响应: ```json { "status": "ok", "message": "服务运行正常" } ``` ## 数据库架构 ### users 表 | 字段 | 类型 | 说明 | |------|------|------| | id | INT | 主键,自增 | | username | VARCHAR(50) | 用户名,唯一 | | email | VARCHAR(100) | 邮箱,唯一 | | hashed_password | VARCHAR(255) | 密码哈希 | | is_active | BOOLEAN | 是否激活 | | created_at | DATETIME | 创建时间 | | updated_at | DATETIME | 更新时间 | ### tasks 表 | 字段 | 类型 | 说明 | |------|------|------| | id | INT | 主键,自增 | | user_id | INT | 外键,关联用户 | | title | VARCHAR(200) | 任务标题 | | description | TEXT | 任务描述 | | status | VARCHAR(20) | 状态:pending, in_progress, completed, cancelled | | priority | VARCHAR(20) | 优先级:low, medium, high | | due_date | DATETIME | 截止日期 | | created_at | DATETIME | 创建时间 | | updated_at | DATETIME | 更新时间 | | completed_at | DATETIME | 完成时间 | ## 中间件说明 ### 1. 认证中间件 (AuthMiddleware) - 验证请求中的 JWT 令牌 - 将用户信息注入到请求上下文 - 保护需要认证的接口 ### 2. 日志中间件 (LoggingMiddleware) - 记录所有 HTTP 请求和响应 - 记录请求处理时间 - 记录错误信息 ### 3. 限流中间件 (RateLimitMiddleware) - 基于 IP 地址的请求限流 - 可配置的请求数和时间窗口 - 超限返回 429 状态码 ### 4. CORS 中间件 - 处理跨域请求 - 支持预检请求 ## 开发指南 ### 添加新的 API 端点 1. 在 `app/schemas/` 中定义数据验证模式 2. 在 `app/api/` 中创建路由处理函数 3. 在 `app/main.py` 中注册路由 ### 添加新的数据模型 1. 在 `app/models/` 中定义 SQLAlchemy 模型 2. 在 `app/schemas/` 中定义对应的 Pydantic 模式 3. 运行 `python init_db.py` 初始化表 ### 错误处理 使用自定义异常类处理业务逻辑错误: ```python from app.exceptions import CustomException raise CustomException(status_code=400, detail="错误信息") ``` ### 日志记录 ```python from app.logger import app_logger app_logger.info("信息日志") app_logger.warning("警告日志") app_logger.error("错误日志") ``` ### 测试 运行测试: ```bash pytest test_api.py -v ``` ## 常见问题 ### Q: 如何修改数据库连接? A: 修改 `.env` 文件中的数据库配置参数。 ### Q: 如何启用 Redis 缓存? A: 确保 Redis 服务运行,并在 `.env` 中配置正确的 Redis 连接参数。 ### Q: 如何生成新的 SECRET_KEY? A: 使用 Python 生成: ```python import secrets print(secrets.token_urlsafe(32)) ``` ### Q: 如何部署到生产环境? A: 1. 设置 `ENVIRONMENT=production` 2. 设置 `DEBUG=False` 3. 使用 Gunicorn 运行:`gunicorn -w 4 -b 0.0.0.0:8000 main:app` ## 许可证 MIT License ## 联系方式 如有问题或建议,请提交 Issue 或 Pull Request。