重构第3批:CLI 瘦化 + 新增 FastAPI Server
CLI 瘦化(commands/ 全部 10 个命令文件): - 移除内联的参数校验和编排逻辑,改为调用对应 service 函数 - 统一错误处理:捕获 EkbError,rich 红字输出并 Exit(1) - auth.py:调用 auth_service,不再直接操作 config 模块 新增 server/ 目录(FastAPI HTTP Server): - __init__.py:create_app() 工厂,注册三个路由组,统一 EkbError 异常处理 - deps.py:ClientDep 类型别名,FastAPI 依赖注入 EkbClient - auth_router.py:/auth/* 5 个端点,对应 ekb auth 命令组 - agent_router.py:/agents/* 7 个端点,含高阶 /dedup-rules 接口 - rule_router.py:/rules/* 4 个端点,对应 ekb agent rule-* 命令
This commit is contained in:
1 parent
475ce518f9
commit
db378b9140
15 files changed
+467
-215
No files matched your search
@@ -0,0 +1,52 @@
|
||||
"""FastAPI 应用工厂
|
||||
|
||||
create_app() 创建并返回完整配置的 FastAPI 实例:
|
||||
- 注册 auth / agent / rule 三个路由组
|
||||
- 统一 EkbError 异常处理(转 HTTP 状态码 + JSON 响应)
|
||||
"""
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from ekb_cli.errors import EkbError
|
||||
|
||||
|
||||
def create_app() -> FastAPI:
|
||||
"""创建 FastAPI 应用实例"""
|
||||
app = FastAPI(
|
||||
title="ekb-cli API Server",
|
||||
description=(
|
||||
"快报(ekuaibao)命令行工具的 HTTP 中转站。\n\n"
|
||||
"与 `ekb` CLI 共享同一套 service 层逻辑,接口和命令一一对应。\n\n"
|
||||
"认证信息从 `~/.config/ekb-cli/config.json` 读取,"
|
||||
"启动前请确保已执行 `ekb auth add`。"
|
||||
),
|
||||
version="0.1.0",
|
||||
)
|
||||
|
||||
# ── 注册路由 ──────────────────────────────────────────────
|
||||
from ekb_cli.server.auth_router import router as auth_router
|
||||
from ekb_cli.server.agent_router import router as agent_router
|
||||
from ekb_cli.server.rule_router import router as rule_router
|
||||
|
||||
app.include_router(auth_router, prefix="/auth", tags=["auth"])
|
||||
app.include_router(agent_router, prefix="/agents", tags=["agent"])
|
||||
app.include_router(rule_router, prefix="/rules", tags=["rule"])
|
||||
|
||||
# ── 统一异常处理:EkbError → HTTP JSON ──────────────────
|
||||
# code → HTTP status 的映射表
|
||||
_STATUS_MAP = {401: 401, 404: 404, 409: 409, 422: 422}
|
||||
|
||||
@app.exception_handler(EkbError)
|
||||
async def ekb_error_handler(request: Request, exc: EkbError) -> JSONResponse:
|
||||
status = _STATUS_MAP.get(exc.code, 500)
|
||||
return JSONResponse(
|
||||
status_code=status,
|
||||
content={"success": False, "error": exc.message, "code": exc.code},
|
||||
)
|
||||
|
||||
@app.get("/", include_in_schema=False)
|
||||
async def root():
|
||||
return {"service": "ekb-cli API Server", "docs": "/docs"}
|
||||
|
||||
return app
|
||||
@@ -0,0 +1,87 @@
|
||||
"""Server:Agent 路由
|
||||
|
||||
对应 CLI 命令:
|
||||
ekb agent list → GET /agents
|
||||
ekb agent get <id> → GET /agents/{agent_id}
|
||||
ekb agent create → POST /agents
|
||||
ekb agent copy <id> → POST /agents/{agent_id}/copy
|
||||
ekb agent update <id> → PATCH /agents/{agent_id}
|
||||
ekb agent delete <id> → DELETE /agents/{agent_id}
|
||||
|
||||
高阶接口(CLI 暂无对应命令):
|
||||
GET /agents/dedup-rules → 所有 Agent 关联规则去重列表
|
||||
"""
|
||||
|
||||
from fastapi import APIRouter
|
||||
|
||||
from ekb_cli.server.deps import ClientDep
|
||||
from ekb_cli.services import (
|
||||
list_agents,
|
||||
get_agent,
|
||||
create_agent,
|
||||
copy_agent,
|
||||
update_agent,
|
||||
delete_agent,
|
||||
get_dedup_rules_across_agents,
|
||||
AgentCreateInput,
|
||||
AgentUpdateInput,
|
||||
)
|
||||
from ekb_cli.api.schemas import AgentCreateRequest, AgentUpdateRequest
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("", summary="列出所有 Agent")
|
||||
def route_list_agents(client: ClientDep):
|
||||
page = list_agents(client)
|
||||
return {"total": page.totalItems, "items": [item.model_dump() for item in page.items]}
|
||||
|
||||
|
||||
@router.get("/dedup-rules", summary="获取所有 Agent 关联的去重规则")
|
||||
def route_dedup_rules(client: ClientDep):
|
||||
"""遍历所有 Agent,汇总其关联规则并去重(按首次出现顺序)"""
|
||||
rules = get_dedup_rules_across_agents(client)
|
||||
return {"total": len(rules), "items": [r.model_dump() for r in rules]}
|
||||
|
||||
|
||||
@router.get("/{agent_id}", summary="获取 Agent 详情")
|
||||
def route_get_agent(agent_id: str, client: ClientDep):
|
||||
return get_agent(client, agent_id).model_dump()
|
||||
|
||||
|
||||
@router.post("", summary="新建 Agent")
|
||||
def route_create_agent(body: AgentCreateRequest, client: ClientDep):
|
||||
inp = AgentCreateInput(
|
||||
name=body.name,
|
||||
description=body.description,
|
||||
mode=body.mode,
|
||||
sampling_rate=body.sampling_rate,
|
||||
agree_terms=body.agree_terms,
|
||||
reject_terms=body.reject_terms,
|
||||
exempt_terms=body.exempt_terms,
|
||||
review_terms=body.review_terms,
|
||||
rule_ids=body.rule_ids,
|
||||
icon=body.icon,
|
||||
)
|
||||
return create_agent(client, inp).model_dump()
|
||||
|
||||
|
||||
@router.post("/{agent_id}/copy", summary="复制 Agent")
|
||||
def route_copy_agent(agent_id: str, client: ClientDep):
|
||||
src, new = copy_agent(client, agent_id)
|
||||
return {"source": src.model_dump(), "copy": new.model_dump()}
|
||||
|
||||
|
||||
@router.patch("/{agent_id}", summary="更新 Agent(patch 式)")
|
||||
def route_update_agent(agent_id: str, body: AgentUpdateRequest, client: ClientDep):
|
||||
inp = AgentUpdateInput(
|
||||
agent_id=agent_id,
|
||||
**body.model_dump(exclude_unset=True),
|
||||
)
|
||||
return update_agent(client, inp).model_dump()
|
||||
|
||||
|
||||
@router.delete("/{agent_id}", summary="删除 Agent")
|
||||
def route_delete_agent(agent_id: str, client: ClientDep):
|
||||
detail = delete_agent(client, agent_id)
|
||||
return {"success": True, "deleted": detail.model_dump()}
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Server:Auth 路由
|
||||
|
||||
对应 CLI 命令:
|
||||
ekb auth list → GET /auth/corps
|
||||
ekb auth add → POST /auth/corps
|
||||
ekb auth use → PUT /auth/corps/{corp_id}/use
|
||||
ekb auth remove → DELETE /auth/corps/{corp_id}
|
||||
ekb auth whoami → GET /auth/whoami
|
||||
|
||||
注意:auth 接口不需要 EkbClient(操作本地配置文件),
|
||||
因此不注入 ClientDep。
|
||||
"""
|
||||
|
||||
from fastapi import APIRouter
|
||||
|
||||
from ekb_cli.services import auth_service
|
||||
from ekb_cli.api.schemas import CorpAddRequest, CorpInfoResponse
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/corps", response_model=list[CorpInfoResponse], summary="列出所有已配置的企业")
|
||||
def list_corps():
|
||||
corps = auth_service.list_corps()
|
||||
return [CorpInfoResponse(corp_id=c.corp_id, name=c.name, is_current=c.is_current) for c in corps]
|
||||
|
||||
|
||||
@router.post("/corps", response_model=CorpInfoResponse, summary="添加企业认证")
|
||||
def add_corp(body: CorpAddRequest):
|
||||
corp = auth_service.add_corp(
|
||||
corp_id=body.corp_id,
|
||||
name=body.name,
|
||||
access_token=body.access_token,
|
||||
staff_id=body.staff_id,
|
||||
)
|
||||
return CorpInfoResponse(corp_id=corp.corp_id, name=corp.name, is_current=corp.is_current)
|
||||
|
||||
|
||||
@router.put("/corps/{corp_id}/use", response_model=CorpInfoResponse, summary="切换当前企业")
|
||||
def use_corp(corp_id: str):
|
||||
corp = auth_service.use_corp(corp_id)
|
||||
return CorpInfoResponse(corp_id=corp.corp_id, name=corp.name, is_current=corp.is_current)
|
||||
|
||||
|
||||
@router.delete("/corps/{corp_id}", summary="删除企业认证")
|
||||
def remove_corp(corp_id: str):
|
||||
auth_service.remove_corp(corp_id)
|
||||
return {"success": True, "corp_id": corp_id}
|
||||
|
||||
|
||||
@router.get("/whoami", response_model=CorpInfoResponse, summary="查看当前企业")
|
||||
def whoami():
|
||||
corp = auth_service.whoami()
|
||||
return CorpInfoResponse(corp_id=corp.corp_id, name=corp.name, is_current=corp.is_current)
|
||||
@@ -0,0 +1,28 @@
|
||||
"""FastAPI 依赖注入:获取已认证的 EkbClient
|
||||
|
||||
用法:
|
||||
from ekb_cli.server.deps import ClientDep
|
||||
|
||||
@router.get("/foo")
|
||||
def my_route(client: ClientDep):
|
||||
...
|
||||
"""
|
||||
|
||||
from typing import Annotated, Generator
|
||||
|
||||
from fastapi import Depends
|
||||
|
||||
from ekb_cli.api import EkbClient, get_client
|
||||
|
||||
|
||||
def _get_ekb_client() -> Generator[EkbClient, None, None]:
|
||||
"""FastAPI 依赖:获取快报 HTTP 客户端,请求结束后自动关闭连接"""
|
||||
client = get_client() # 未登录时抛出 NotLoggedInError → 被全局 handler 捕获
|
||||
try:
|
||||
yield client
|
||||
finally:
|
||||
client.close()
|
||||
|
||||
|
||||
# 类型别名,路由函数用 `client: ClientDep` 即可,简洁且支持类型推断
|
||||
ClientDep = Annotated[EkbClient, Depends(_get_ekb_client)]
|
||||
@@ -0,0 +1,57 @@
|
||||
"""Server:Rule 路由
|
||||
|
||||
对应 CLI 命令:
|
||||
ekb agent rules → GET /rules
|
||||
ekb agent rule-get <ref> → GET /rules/{rule_ref}
|
||||
ekb agent rule-create → POST /rules
|
||||
(暂无 CLI rule-update) → PATCH /rules/{rule_ref}
|
||||
"""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Query
|
||||
|
||||
from ekb_cli.server.deps import ClientDep
|
||||
from ekb_cli.services import list_rules, get_rule, create_rule, update_rule
|
||||
from ekb_cli.api.schemas import RuleCreateRequest, RuleUpdateRequest
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("", summary="列出所有审核规则")
|
||||
def route_list_rules(
|
||||
client: ClientDep,
|
||||
level: Optional[str] = Query(None, description="按风险等级筛选:严重 / 一般"),
|
||||
):
|
||||
page, items = list_rules(client, level=level)
|
||||
return {
|
||||
"total": page.totalItems,
|
||||
"filtered": len(items),
|
||||
"items": [r.model_dump() for r in items],
|
||||
}
|
||||
|
||||
|
||||
@router.get("/{rule_ref}", summary="获取单条规则详情(支持 ID 或编码)")
|
||||
def route_get_rule(rule_ref: str, client: ClientDep):
|
||||
"""
|
||||
rule_ref 支持:
|
||||
- 完整 ID(长字符串)
|
||||
- 编码数字,如 "1" / "0001" / "#0001"
|
||||
"""
|
||||
return get_rule(client, rule_ref).model_dump()
|
||||
|
||||
|
||||
@router.post("", summary="新建审核规则")
|
||||
def route_create_rule(body: RuleCreateRequest, client: ClientDep):
|
||||
return create_rule(client, body.purpose, body.description, body.level).model_dump()
|
||||
|
||||
|
||||
@router.patch("/{rule_ref}", summary="更新审核规则(patch 式)")
|
||||
def route_update_rule(rule_ref: str, body: RuleUpdateRequest, client: ClientDep):
|
||||
return update_rule(
|
||||
client,
|
||||
rule_ref=rule_ref,
|
||||
purpose=body.purpose,
|
||||
description=body.description,
|
||||
level=body.level,
|
||||
).model_dump()
|
||||
Reference in new issue
Block a user