如何在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
相关产品推荐
相关产品推荐

