栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如果我的方法具有多个路由注释,该如何使用url_for?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如果我的方法具有多个路由注释,该如何使用url_for?

好。它花了一些时间研究

werkzeug.routing
flask.helpers.url_for
代码,但我知道了。您只需更改
endpoint
路线的即可(换句话说,您
路线 命名

@app.route("/canonical/path/", endpoint="foo-canonical")@app.route("/alternate/path/")def foo():    return "hi!"@app.route("/wheee")def bar():    return "canonical path is %s, alternative is %s" % (url_for("foo-canonical"), url_for("foo"))

将产生

规范路径为/ canonical / path /,替代方案为/ alternate / path /

这种方法有一个缺点。Flask始终将最后定义的路由绑定到隐式定义的端点(

foo
在您的代码中)。猜猜如果您重新定义端点会发生什么?你
url_for('old_endpoint')
会全力以赴
werkzeug.routing.BuildError
。因此,我想整个问题的正确解决方案是在最后定义路径并
命名 替代项:

"""    since url_for('foo') will be used for canonical path   we don't have other options rather then defining an endpoint for   alternative path, so we can use it with url_for"""@app.route('/alternative/path', endpoint='foo-alternative')"""    we dont wanna mess with the endpoint here -    we want url_for('foo') to be pointing to the canonical path"""@app.route('/canonical/path') def foo():    pass@app.route('/wheee')def bar():    return "canonical path is %s, alternative is %s" % (url_for("foo"), url_for("foo-alternative"))


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/611249.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号