Files
chongming-plugins/example/README.md
T
2026-08-14 16:04:39 +08:00

73 lines
2.4 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Example Worker 插件
演示 `@rpc_method` 装饰器与显式模型绑定的完整用法,是学习开发新插件的**入门参考**。
---
## 实现的功能
### 四则运算(GET / POST)
| 端点 | 方法 | 路径 | 说明 |
| ---- | ---------- | ---------------- | ------------------------ |
| 加法 | GET / POST | `/calc/add` | `a + b` |
| 减法 | GET | `/calc/subtract` | `a - b` |
| 乘法 | GET | `/calc/multiply` | `a * b` |
| 除法 | GET | `/calc/divide` | `a / b`(除数为 0 报错) |
### 访问计数器
| 端点 | 方法 | 路径 | 说明 |
| ---- | ---- | ------------- | ----------------- |
| 计数 | GET | `/calc/count` | 每次调用计数器 +1 |
基于内存缓存实现,用于演示 GET 端点的无参数调用模式。
---
## 调用示例
```bash
# GET 加法
curl "http://localhost:8000/api/v1/calc/add?a=3&b=4"
# {"result":7.0,"operation":"add","timestamp":1720000000.123}
# POST 加法
curl -X POST "http://localhost:8000/api/v1/calc/add" \
-H "Content-Type: application/json" \
-d '{"a": 3.5, "b": 2.5}'
# {"result":6.0,"operation":"add","timestamp":1720000000.456}
# 除法(除数为零)
curl "http://localhost:8000/api/v1/calc/divide?a=10&b=0"
# {"result":0.0,"operation":"divide","error":"Division by zero"}
# 计数器
curl "http://localhost:8000/api/v1/calc/count"
# {"count":1}
```
---
## 如何工作
1. **配置**:`config/workers/example/*.toml` — 定义每个端点的参数和响应结构
2. **模型**:`models/pydantic.py` — 由 `gen_models` 根据 TOML 自动生成
3. **路由**:`router/` 下每个文件实现一个 RPC 端点,使用 `@rpc_method` 装饰器
4. **入口**:`__init__.py` 的 `ExamplePlugin`(Plugin 基类)统一生命周期——`on_init` 初始化
数据库并发布到 global_var,`create_workers` / `cleanup` 为其 bound method
---
## 开发参考
此插件展示了以下模式:
- GET 端点的 `params` 定义与 `@rpc_method` 参数绑定
- POST 端点的 JSON body 自动解析
- `response_model` 在 TOML 中定义并在装饰器中引用
- 全局变量 (`global_var.py`) 管理共享资源
- 错误处理(如除法除零返回错误信息)
- `auth_required` 控制端点是否需要 JWT 鉴权
- `cacheable` 控制结果是否缓存