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

如何在Flask模板中为Flask-RESTX的Resource正确使用url_for?

Flask-RESTX中模板使用url_for的正确方法

方法1:使用自动生成的Endpoint

Flask-RESTX会为每个Resource自动生成唯一的endpoint,格式为{命名空间名称}.{资源类名}。对照你的代码:

  • 命名空间ns_detect的名称是detect(定义时的第一个参数)
  • 资源类为DetectRecording

模板中直接调用url_for并传入这个组合字符串即可:

<button value="{{ url_for('detect.DetectRecording') }}">1</button>

方法2:手动指定Endpoint(更清晰)

如果觉得自动生成的endpoint不够直观,可以在路由装饰器里手动指定endpoint参数:

@ns_detect.route('/detect/recording', endpoint='recording')
class DetectRecording(Resource):
    def post(self):
        return {"status": "ok"}

之后模板里使用指定的名称:

<button value="{{ url_for('detect.recording') }}">1</button>

错误写法原因说明

  • url_for('ns_detect.DetectRecording'):模板中不存在ns_detect变量,必须用命名空间的字符串名称detect而非后端变量名
  • Api.url_for('DetectRecording'):模板中未引入Api对象,且该方法需要结合资源类或命名空间使用,远不如Flask原生url_for便捷

内容的提问来源于stack exchange,提问作者x y

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 14:30:16