Files
chongming-plugins/example/__init__.py
T

50 lines
1.8 KiB
Python
Raw Normal View History

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