小编典典

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

flask

我的Flask路线中有一半需要使用变量say /<variable>/add/<variable>/remove。如何创建到这些位置的链接?

url_for() 需要一个参数传递给函数,但是我不能添加参数?


阅读 912

收藏
2020-04-05

共2个答案

小编典典

它使用关键字参数作为变量:

url_for('add', variable=foo)
2020-04-05
小编典典

url_forFlask中的ins用于创建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>

这样,你只需传递参数即可!

2020-04-05