我的一半 Flask 路由需要一个变量,例如 /<variable>/add
或 /<variable>/remove
。如何创建指向这些位置的链接?
url_for()
为要路由到的函数采用一个参数,但我无法添加参数?
原文由 Gio Borje 发布,翻译遵循 CC BY-SA 4.0 许可协议
我的一半 Flask 路由需要一个变量,例如 /<variable>/add
或 /<variable>/remove
。如何创建指向这些位置的链接?
url_for()
为要路由到的函数采用一个参数,但我无法添加参数?
原文由 Gio Borje 发布,翻译遵循 CC BY-SA 4.0 许可协议
url_for
在 Flask 中用于创建 URL 以防止在整个应用程序(包括模板)中必须更改 URL 的开销。如果没有 url_for
,如果应用程序的根 URL 发生变化,则必须在存在链接的每个页面中进行更改。
语法: url_for('name of the function of the route','parameters (if required)')
它可以用作:
@app.route('/index')
@app.route('/')
def index():
return 'you are in the index page'
现在,如果你有索引页的链接:你可以使用这个:
<a href={{ url_for('index') }}>Index</a>
你可以用它做很多事情,例如:
@app.route('/questions/<int:question_id>') #int has been used as a filter that only integer will be passed in the url otherwise it will give a 404 error
def find_question(question_id):
return ('you asked for question{0}'.format(question_id))
对于以上我们可以使用:
<a href = {{ url_for('find_question' ,question_id=1) }}>Question 1</a>
像这样你可以简单地传递参数!
原文由 Hiro 发布,翻译遵循 CC BY-SA 4.0 许可协议
2 回答5k 阅读✓ 已解决
2 回答1k 阅读✓ 已解决
4 回答936 阅读✓ 已解决
3 回答1.1k 阅读✓ 已解决
3 回答1.1k 阅读✓ 已解决
1 回答1.7k 阅读✓ 已解决
1 回答1.2k 阅读✓ 已解决
它采用变量的关键字参数:
flask-server 将具有以下功能: