51 lines
1.8 KiB
Python
51 lines
1.8 KiB
Python
"""
|
||||
|
|
Example Worker 插件 — 演示 @rpc_method + 显式模型绑定用法
|
|||
|
|
|
|||
|
|
本插件展示如何使用 chongming_worker 框架定义 RPC 端点。
|
|||
|
|
|
|||
|
|
核心工作流:
|
|||
|
|
1. 编写 config/workers/example/*.toml 配置文件
|
|||
|
|
2. 执行 uv run gen_models 生成 Pydantic 模型
|
|||
|
|
3. 在 __init__.py 中用 @rpc_method 定义业务函数
|
|||
|
|
4. 显式导入模型并绑定到对应端点(替代 auto_bind_models)
|
|||
|
|
|
|||
|
|
关键约定:
|
|||
|
|
- 模型命名: <Operation><Method>{Request|Response}
|
|||
|
|
(如 AddGetRequest, AddGetResponse 由 gen_models 自动生成)
|
|||
|
|
- 装饰器 subject 中的操作名 → 模型前缀(驼峰)
|
|||
|
|
example.add → Add, example.subtract → Subtract
|
|||
|
|
"""
|
|||
|
|
import modelvault
|
|||
|
|
from pathlib import Path
|
|||
|
|
|
|||
|
|
from chongming_worker import auto_bind_models
|
|||
|
|
from chongming_worker.runtime import create_workers as _create_workers
|
|||
|
|
|
|||
|
|
from .router import *
|
|||
|
|
|
|||
|
|
auto_bind_models("example")
|
|||
|
|
|
|||
|
|
|
|||
|
|
# ============================================================
|
|||
|
|
# 工厂函数 — 供 app lifespan 动态加载
|
|||
|
|
# ============================================================
|
|||
|
|
# 框架通过 __import__ + getattr 获取此函数,
|
|||
|
|
# 然后调用 create_workers(session, config, count, worker_manager=worker_manager)。
|
|||
|
|
# 详见 src/chongming/app/__init__.py 的 lifespan。
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def create_workers(session, config, count=1, worker_manager=None):
|
|||
|
|
"""插件入口 — 委托给 chongming_worker 运行时创建 Worker 协程"""
|
|||
|
|
from .global_var import set_global_var
|
|||
|
|
|
|||
|
|
db_path = Path(config.get("data_dir", "./data")) / "example.modelvault"
|
|||
|
|
db_path.parent.mkdir(parents=True, exist_ok=True)
|
|||
|
|
db = await modelvault.AsyncDatabase.open(str(db_path)) # type: ignore
|
|||
|
|
set_global_var("db", db)
|
|||
|
|
|
|||
|
|
return _create_workers(session, config, count, worker_manager)
|
|||
|
|
|
|||
|
|
async def cleanup(worker_item: str):
|
|||
|
|
print(f"{worker_item}关闭")
|
|||
|
|
pass
|