50 lines
1.8 KiB
Python
50 lines
1.8 KiB
Python
"""
|
|
Example Worker 插件 — 演示 @rpc_method + Plugin 基类统一生命周期
|
|
|
|
本插件展示如何使用 chongming_worker 框架定义 RPC 端点,以及如何
|
|
基于 Plugin 基类编写风格统一的插件初始化 / 清理。
|
|
|
|
核心工作流:
|
|
1. 编写 config/workers/example/*.toml 配置文件
|
|
2. 执行 uv run gen_models 生成 Pydantic 模型
|
|
3. 在 router/*.py 中用 @rpc_method 定义业务函数
|
|
4. 在 __init__.py 中用 Plugin 基类统一管理生命周期
|
|
|
|
关键约定:
|
|
- 模型命名: <Operation><Method>{Request|Response}
|
|
(如 AddGetRequest, AddGetResponse 由 gen_models 自动生成)
|
|
- 装饰器 subject 中的操作名 → 模型前缀(驼峰)
|
|
example.add → Add, example.subtract → Subtract
|
|
"""
|
|
import logging
|
|
|
|
from chongming_worker.plugin import Plugin
|
|
|
|
from .router import * # noqa: F401,F403 触发 @rpc_method 注册
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class ExamplePlugin(Plugin):
|
|
"""Example 插件 — 统一生命周期。"""
|
|
|
|
type = "example"
|
|
db_name = "example.db" # 自动在 data_dir 下建 SQLite 库
|
|
auto_bind = True # 首次初始化时自动 auto_bind_models("example")
|
|
|
|
async def on_init(self):
|
|
"""首次 create_workers 时调用一次:初始化资源。"""
|
|
# 数据库已由基类自动初始化(self.db),写入全局变量供 router 使用
|
|
self.set_var("db", self.db)
|
|
logger.info("[example] 初始化完成")
|
|
|
|
async def on_cleanup(self):
|
|
"""cleanup 时调用:关闭自定义客户端等(数据库由基类处理)。"""
|
|
logger.info("[example] 清理完成")
|
|
|
|
|
|
# 暴露给 app lifespan 的模块级入口(bound method,签名与旧写法完全一致)
|
|
plugin = ExamplePlugin()
|
|
create_workers = plugin.create_workers
|
|
cleanup = plugin.cleanup
|