docs: 更新核心模块文档,添加新组件使用说明
This commit is contained in:
1 parent
e16d4ad193
commit
e2fbef5add
1 file changed
+176
-3
@@ -7,9 +7,19 @@ backend/app/
|
||||
├── core/ # 核心可复用组件
|
||||
│ ├── __init__.py # 模块导出
|
||||
│ ├── security.py # 统一安全装饰器
|
||||
│ └── responses.py # 统一响应格式
|
||||
└── services/ # 业务服务层(后续扩展)
|
||||
└── __init__.py
|
||||
│ ├── responses.py # 统一响应格式
|
||||
│ ├── task_executor.py # 后台任务执行器
|
||||
│ └── validators.py # 数据验证器
|
||||
├── services/ # 业务服务层
|
||||
│ ├── __init__.py
|
||||
│ └── model_cache.py # 模型缓存管理器
|
||||
├── utils/ # 工具模块
|
||||
│ ├── __init__.py
|
||||
│ ├── file_utils.py # 文件处理工具
|
||||
│ └── time_utils.py # 时间工具
|
||||
└── models/ # 数据模型
|
||||
├── __init__.py
|
||||
└── mixins.py # 模型混合类
|
||||
```
|
||||
|
||||
## 核心组件
|
||||
@@ -170,3 +180,166 @@ return error("error")
|
||||
2. **使用装饰器进行权限检查** - 不要手动检查用户权限
|
||||
3. **使用分页工具处理大数据** - 避免一次性加载所有数据
|
||||
4. **错误信息要具体** - 帮助用户理解问题所在
|
||||
|
||||
---
|
||||
|
||||
## 其他工具组件
|
||||
|
||||
### TaskExecutor - 后台任务执行器
|
||||
|
||||
```python
|
||||
from app.core import TaskExecutor, submit_task, get_task_status
|
||||
|
||||
# 提交简单任务
|
||||
task_id = submit_task(long_running_function, arg1, arg2)
|
||||
|
||||
# 提交带 Flask 上下文的 task
|
||||
task_id = submit_task_with_context(flask_function, arg1)
|
||||
|
||||
# 获取任务状态
|
||||
status = get_task_status(task_id)
|
||||
# 返回:{'task_id': '...', 'status': 'running', 'progress': 50, ...}
|
||||
|
||||
# 取消任务
|
||||
cancel_task(task_id)
|
||||
```
|
||||
|
||||
### Validator - 数据验证器
|
||||
|
||||
```python
|
||||
from app.core import Validator, RequestValidator, validate_request
|
||||
|
||||
# 使用 RequestValidator
|
||||
data = request.get_json()
|
||||
validator = RequestValidator(data)
|
||||
validated = (validator
|
||||
.validate('username', Validator.required, Validator.string(min_length=3))
|
||||
.validate('email', Validator.required, Validator.email)
|
||||
.validate('age', Validator.integer(min_value=0, max_value=150))
|
||||
.get_validated_data()
|
||||
)
|
||||
|
||||
# 使用装饰器
|
||||
@api.route('/users', methods=['POST'])
|
||||
@validate_request(
|
||||
('username', Validator.required, Validator.string(min_length=3)),
|
||||
('email', Validator.required, Validator.email),
|
||||
)
|
||||
def create_user(validated_data):
|
||||
# validated_data 已经过验证
|
||||
pass
|
||||
```
|
||||
|
||||
### FileUtils - 文件处理工具
|
||||
|
||||
```python
|
||||
from app.utils import FileUtils
|
||||
|
||||
# 保存文件
|
||||
file_path = FileUtils.save_file(
|
||||
file,
|
||||
folder='uploads',
|
||||
allowed_extensions=['pdf', 'docx'],
|
||||
max_size=10*1024*1024 # 10MB
|
||||
)
|
||||
|
||||
# 创建 ZIP
|
||||
zip_path = FileUtils.create_zip_folder('data_folder', 'output.zip')
|
||||
|
||||
# 解压 ZIP
|
||||
files = FileUtils.extract_zip('archive.zip', 'output_dir')
|
||||
|
||||
# 获取文件信息
|
||||
size = FileUtils.get_file_size_human('file.txt')
|
||||
hash_val = FileUtils.get_file_hash('file.txt', 'sha256')
|
||||
```
|
||||
|
||||
### TimeUtils - 时间工具
|
||||
|
||||
```python
|
||||
from app.utils import TimeUtils
|
||||
|
||||
# 获取当前时间
|
||||
now = TimeUtils.now()
|
||||
|
||||
# 解析和格式化
|
||||
dt = TimeUtils.parse('2024-01-01 12:00:00')
|
||||
formatted = TimeUtils.format(dt, '%Y-%m-%d')
|
||||
|
||||
# 相对时间
|
||||
relative = TimeUtils.format_relative(dt) # "3 小时前"
|
||||
|
||||
# 过期检查
|
||||
if TimeUtils.is_expired(expiration_date):
|
||||
print("已过期")
|
||||
|
||||
# 日期运算
|
||||
next_week = TimeUtils.add_days(now, 7)
|
||||
start_of_month = TimeUtils.get_start_of_month()
|
||||
```
|
||||
|
||||
### ModelCache - 模型缓存管理器
|
||||
|
||||
```python
|
||||
from app.services import ModelCache, get_cached_session
|
||||
|
||||
# 获取缓存实例
|
||||
cache = ModelCache(max_cache_size=3)
|
||||
|
||||
# 获取或加载 Session
|
||||
session = get_cached_session('model.onnx')
|
||||
|
||||
# 使用 Session
|
||||
outputs = session.run(None, {input_name: input_data})
|
||||
|
||||
# 缓存信息
|
||||
info = cache.get_cache_info()
|
||||
# {'size': 1, 'max_size': 3, 'hit_rate': 0.8, ...}
|
||||
```
|
||||
|
||||
### 模型混合类
|
||||
|
||||
```python
|
||||
from app.models import (
|
||||
TimestampMixin,
|
||||
SoftDeleteMixin,
|
||||
ExpirableMixin,
|
||||
FullAuditMixin
|
||||
)
|
||||
|
||||
# 使用时间戳混合类
|
||||
class DataEntry(TimestampMixin, db.Model):
|
||||
__tablename__ = 'data_entry'
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
# 自动拥有 created_at 和 updated_at 字段
|
||||
|
||||
# 使用软删除
|
||||
class User(SoftDeleteMixin, db.Model):
|
||||
__tablename__ = 'user'
|
||||
# 查询活跃用户
|
||||
active_users = User.query_active().all()
|
||||
|
||||
# 软删除
|
||||
user.delete(soft=True)
|
||||
|
||||
# 恢复
|
||||
user.restore()
|
||||
|
||||
# 使用可过期混合类
|
||||
class DataEntry(ExpirableMixin, db.Model):
|
||||
# 设置过期时间
|
||||
entry.set_expiration(days=30)
|
||||
|
||||
# 检查是否过期
|
||||
if entry.is_expired():
|
||||
...
|
||||
|
||||
# 检查是否可见
|
||||
if entry.is_visible_now():
|
||||
...
|
||||
|
||||
# 使用完整审计混合类
|
||||
class ProcessingJob(FullAuditMixin, db.Model):
|
||||
# 包含所有审计字段
|
||||
pass
|
||||
```
|
||||
Reference in new issue
Block a user