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

Gio*_*rje 157 python flask

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

url_for() 为函数路由到一个参数,但我不能添加参数?

Fog*_*ird 238

它接受变量的关键字参数:

url_for('add', variable=foo)
Run Code Online (Sandbox Code Playgroud)

  • 意思是函数是`def add(variable)`? (10认同)
  • @endolith,是的.**传递给`url_for`的kwargs将作为Flask中变量规则路由的函数参数传递 (4认同)
  • 为了更清楚,如果你有 `@app.route("/&lt;a&gt;/&lt;b&gt;")` 和 `def function(a,b): ...` 作为它的函数,那么你应该使用`url_for` 并指定其关键字参数,如下所示: `url_for('function', a='somevalue', b='anothervalue')` (4认同)
  • 但是问题是,如果它是Python中的变量,那么'foo'如何超出范围。那你怎么解决呢? (2认同)

小智 95

url_forFlask中用于创建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'
Run Code Online (Sandbox Code Playgroud)

现在,如果你有索引页面的链接:你可以使用这个:

<a href={{ url_for('index') }}>Index</a>
Run Code Online (Sandbox Code Playgroud)

你可以用它做很多东西,例如:

@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))
Run Code Online (Sandbox Code Playgroud)

对于上面我们可以使用:

<a href = {{ url_for('find_question' ,question_id=1) }}>Question 1</a>
Run Code Online (Sandbox Code Playgroud)

像这样你可以简单地传递参数!

  • @आनंद 如果您使用变量: `{{ url_for('find_question' ,question_id=question.id) }}` 而不是 `{{ url_for('find_question' ,question_id={{question.id}}) }}` (7认同)

小智 34

请参阅Flask API文档flask.url_for()

下面是将js或css链接到模板的其他示例片段.

<script src="{{ url_for('static', filename='jquery.min.js') }}"></script>

<link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">
Run Code Online (Sandbox Code Playgroud)


Muh*_*eed 10

模板:

传递函数名和参数。

<a href="{{ url_for('get_blog_post',id = blog.id)}}">{{blog.title}}</a>
Run Code Online (Sandbox Code Playgroud)

视图、功能

@app.route('/blog/post/<string:id>',methods=['GET'])
def get_blog_post(id):
    return id
Run Code Online (Sandbox Code Playgroud)