使用url_for重定向到带有查询参数的路径

cor*_*vid 18 flask python-2.7

所以,假设我有一个带有几个链接的模板,链接将是这样的:

<a class='btn btn-primary' href='/?chart=new_chart&chart=other_chart'>View Summary</a>
Run Code Online (Sandbox Code Playgroud)

但是,在我完成链接或包含资源的大多数时候,我使用了以下语法:

<script src="{{ url_for('static', filename='some_silly_js') }}"></script>
Run Code Online (Sandbox Code Playgroud)

是否可以使用查询参数执行url_for?就像是:

<a href="{{ url_for('stats', query_params={chart: [new_chart, other_chart]}) }}>View More</a>
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 28

传递给路由不支持的任何额外关键字参数url_for()将自动添加为查询参数.

对于重复的值,传入一个列表:

<a href="{{ url_for('stats', chart=[new_chart, other_chart]) }}>View More</a>
Run Code Online (Sandbox Code Playgroud)

然后烧瓶将:

  1. 找到stats端点
  2. 填写任何所需的路线参数
  3. 将任何剩余的关键字参数转换为查询字符串

演示,'stats'作为端点名称/:

>>> url_for('stats', chart=['foo', 'bar'])
'/?chart=foo&chart=bar'
Run Code Online (Sandbox Code Playgroud)