Skip to content

Router — 路由组件

BaseRouter 为插件提供基于 FastAPI 的 HTTP 路由能力。

类属性

属性类型默认值说明
namestr""路由名称
descriptionstr""描述
custom_route_path`strNone`None
cors_origins`list[str]None`None
dependencieslist[str][]组件级依赖

必须实现

register_endpoints() -> None

在该方法内通过 self.app 注册接口。

其他方法

方法说明
get_route_path() -> str返回挂载路径(自定义路径或默认 /router/{name}
get_app() -> FastAPI返回内部 FastAPI 应用实例
startup() / shutdown()路由挂载/卸载钩子,可重写以初始化或清理资源
get_openapi_schema() -> dict获取 OpenAPI schema
get_signature() -> str | None类方法,返回 "plugin_name:router:name"

示例

python
from fastapi import HTTPException
from pydantic import BaseModel

from src.core.components.base.router import BaseRouter


class WebhookPayload(BaseModel):
    event: str
    data: dict


class WebhookRouter(BaseRouter):
    name = "webhook"
    description = "Webhook 接收"
    custom_route_path = "/api/webhook"
    cors_origins = ["*"]

    def register_endpoints(self) -> None:
        @self.app.post("/github")
        async def github_webhook(payload: WebhookPayload):
            if payload.event not in {"push", "pull_request"}:
                raise HTTPException(status_code=400, detail="不支持的事件")
            return {"ok": True, "event": payload.event}

        @self.app.get("/health")
        async def health():
            return {"status": "ok"}

默认挂载路径示例:/router/webhook

贡献者

The avatar of contributor named as minecraft1024a minecraft1024a
The avatar of contributor named as micraft1024a micraft1024a

页面历史

Released under the GPL-3.0 License.