Files
jdy_fastapi/ARCHITECTURE.md
T
2025-11-07 17:48:49 +08:00

6.2 KiB
Raw Blame History

FastAPI项目架构说明文档

项目架构概览

本项目采用模块化、可扩展的架构设计,主要包含以下核心组件:

fastapi_app/
├── app/
│   ├── core/                    # 核心模块(可选)
│   │   ├── header_manager.py   # 请求头管理器
│   │   ├── module_registry.py  # 模块注册表
│   │   └── __init__.py         # 核心模块导出
│   ├── module/                 # 业务模块
│   │   ├── F6_Plugin_module.py
│   │   ├── module.py
│   │   └── other_module.py
│   ├── tasks/                  # 后台任务模块
│   │   ├── common.py
│   │   ├── brand_tasks.py
│   │   ├── delete_tasks.py
│   │   └── customer_tasks.py
│   ├── utils/                  # 工具模块
│   │   └── app_tools.py
│   └── api.py                  # API接口
├── main.py                     # FastAPI应用入口
└── requirements_fastapi.txt    # 依赖清单

核心组件说明

1. 请求头管理器(HeaderManager

统一管理不同模块的请求头配置。

预定义配置:

  • default: 默认请求头
  • f6_login: F6系统登录请求头
  • jiandaoyun_api: 简道云API请求头

使用示例:

from app.core.header_manager import HeaderManager

# 获取默认请求头
headers = HeaderManager.get_headers()

# 获取F6登录请求头
headers = HeaderManager.get_headers('f6_login')

# 自定义请求头
headers = HeaderManager.get_headers(
    'default',
    referer='https://example.com',
    custom_headers={'X-Custom-Header': 'value'}
)

# 注册新模块的请求头
from app.core.header_manager import HeaderConfig
custom_config = HeaderConfig(
    referer='https://new-module.com',
    user_agent='Custom Agent'
)
HeaderManager.register_module_headers('new_module', custom_config)

2. 模块注册表(ModuleRegistry

统一注册和管理所有功能模块和操作(可选使用,主要用于请求头管理)。

注册操作:

from app.core import core_manager

core_manager.register_action(
    action_name='my_action',
    handler=my_handler_function,
    module_name='my_module',
    description='操作描述',
    requires_auth=True,
    header_module='default'
)

获取操作:

action_config = core_manager.registry.get_action('my_action')
if action_config:
    result = action_config.handler(data)

添加新功能模块

步骤1:创建模块文件

app/module/ 目录下创建新模块文件,例如 new_module.py

class NewModule:
    def my_action(self, data):
        """即刻执行的操作"""
        # 处理逻辑
        return {'msg': '执行成功'}
    
    def my_background_action(self, data):
        """后台执行的操作"""
        # 这个函数会启动后台线程
        from app import back_ground_tasks
        import threading
        
        thread = threading.Thread(
            target=back_ground_tasks.my_background_task,
            args=(data,)
        )
        thread.start()
        return {'msg': '正在执行中'}

步骤2:创建后台任务(如果需要)

app/tasks/ 目录下创建任务文件,例如 new_tasks.py

from app.tasks.common import update_jiandaoyun, approve_workflow

def my_background_task(data):
    """后台任务函数"""
    # 执行耗时操作
    result = "执行结果"
    
    # 更新简道云表单
    msg = update_jiandaoyun(data, result)
    
    # 提交工作流
    if msg.get('msg'):
        approve_workflow(data)

步骤3:在 main.py 中注册操作

main.pyget_action_map() 函数中添加:

def get_action_map() -> dict:
    # ... 现有代码 ...
    new_module = NewModule()
    return {
        # ... 现有操作 ...
        'my_action': new_module.my_action,
        'my_background_action': new_module.my_background_action,
    }

步骤4:注册新的请求头(如果需要)

app/core/header_manager.py 中添加:

# 在 HeaderManager 类中添加
NEW_MODULE_HEADERS = HeaderConfig(
    referer='https://new-module.com',
    user_agent='Custom User Agent',
    custom_headers={'X-API-Key': 'your-api-key'}
)

_module_headers: Dict[str, HeaderConfig] = {
    # ... 现有配置 ...
    'new_module': NEW_MODULE_HEADERS,
}

执行方式说明

调度机制

项目使用原有的任务队列调度方式:

  1. 所有操作都通过 app_tools.enqueue_task() 放入任务队列
  2. 同步等待结果通过 response_queue.get() 获取
  3. 后台任务在模块函数内部使用 threading.Thread 启动线程

即刻执行 vs 后台执行

  • 即刻执行:函数直接返回结果,通过任务队列同步执行
  • 后台执行:函数内部启动线程执行耗时操作,立即返回"正在执行中"的提示

所有操作都通过统一的任务队列处理,后台任务由模块函数内部管理。

API接口

POST /webhook

统一处理所有请求的主接口。

请求头:

  • Action: 操作名称
  • Check: (可选)F6_Plugin 操作时的检查标志

请求体:

{
  "api_key": "...",
  "entry_id": "...",
  "data_id": "...",
  "Action": "..."  // F6_Plugin 操作时需要
}

最佳实践

  1. 模块职责单一:每个模块只负责一类功能
  2. 统一注册:所有操作都在 main.pyget_action_map() 中统一注册
  3. 请求头管理:使用 HeaderManager 统一管理请求头,避免硬编码(可选)
  4. 错误处理:在模块函数中统一处理异常
  5. 日志记录:使用统一的日志记录器 logging.getLogger('app')
  6. 向后兼容:保持 app.back_ground_tasks 的向后兼容性
  7. 任务队列:所有操作都通过 app_tools.enqueue_task() 放入任务队列统一处理

后续扩展建议

  1. 添加中间件:用于请求验证、日志记录等
  2. 添加配置管理:使用配置文件管理不同环境的设置
  3. 添加任务队列:使用 Celery 或 RQ 管理后台任务
  4. 添加API文档:使用 FastAPI 的自动文档功能
  5. 添加单元测试:为每个模块添加测试用例