使用 url_for() 在 Flask 中创建动态 URL

新手上路,请多包涵

我的一半 Flask 路由需要一个变量,例如 /<variable>/add/<variable>/remove 。如何创建指向这些位置的链接?

url_for() 为要路由到的函数采用一个参数,但我无法添加参数?

原文由 Gio Borje 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 312
2 个回答

它采用变量的关键字参数:

 url_for('add', variable=foo)
url_for('remove', variable=foo)

flask-server 将具有以下功能:

 @app.route('/<variable>/add', methods=['GET', 'POST'])
def add(variable):

@app.route('/<variable>/remove', methods=['GET', 'POST'])
def remove(variable):

原文由 FogleBird 发布,翻译遵循 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 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题