You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用@hug.extend_api()时CLI路由失效,HTTP路由正常求助

解决Hug中@hug.extend_api()无法扩展CLI路由的问题

我明白你遇到的问题了——用@hug.extend_api()扩展HTTP路由一切正常,但CLI路由就是不显示在命令列表里。这是因为Hug的extend_api机制默认只处理HTTP路由,并没有自动把子模块中的CLI命令同步到主API的CLI注册表中。

问题分析

你的代码结构中,子模块apitest/api.py里的@hug.cli()装饰器会把root函数注册到该子模块的API CLI命令中,但主脚本run.py通过@hug.extend_api()扩展时,只会合并HTTP路由规则,不会同步CLI命令。当你执行hug -f run.py -c something时,Hug只会扫描主脚本中直接注册的CLI命令,所以看不到root命令。

解决方案

这里有几种可行的方法来修复这个问题:

方法1:显式导入并注册CLI命令

直接在主脚本中导入子模块的CLI函数,然后重新注册到主API的CLI中:

修改run.py:

import hug
from apitest import api
from apitest.api import root  # 导入子模块的CLI函数

# 保持HTTP路由的扩展
@hug.extend_api()
def apis():
    return [api]

# 显式将root函数注册到主CLI
hug.cli()(root)

现在执行hug -f run.py -c root,就能正常调用这个CLI命令了。

方法2:手动合并子API的CLI命令

通过Hug的API对象,手动将子API中的CLI命令合并到主API中:

修改run.py:

import hug
from apitest import api

# 初始化主API并扩展HTTP路由
main_api = hug.API(__name__)
main_api.extend(api)

# 遍历子API的CLI命令,添加到主API中
for cmd_name, cli_command in api.cli_commands.items():
    main_api.cli_commands[cmd_name] = cli_command

这种方式更适合子模块中有多个CLI命令的场景,一次性全部合并。

方法3:调整子模块的CLI导出方式

在子模块中提前导出CLI命令,主模块导入后直接使用:

修改apitest/api.py:

import hug

def root():
    return 'hello'

# 注册HTTP路由
hug.get('/')(root)
# 导出CLI命令对象
root_cli = hug.cli()(root)

修改run.py:

import hug
from apitest import api
from apitest.api import root

@hug.extend_api()
def apis():
    return [api]

# 注册CLI命令
hug.cli()(root)

验证效果

修改完成后,执行hug -f run.py -c(不带命令名),就能看到root命令出现在列表里了,执行hug -f run.py -c root也会正常返回结果。

内容的提问来源于stack exchange,提问作者Eduardo Marinho

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:22:39