在Flask中使用url_for重定向时添加查询参数
假设我有一个模板,上面有几个链接,这些链接大概是这样的:
<a class='btn btn-primary' href='/?chart=new_chart&chart=other_chart'>View Summary</a>
不过,通常情况下,当我做链接或者包含资源的时候,我用的语法是这样的:
<script src="{{ url_for('static', filename='some_silly_js') }}"></script>
那么,能不能用带查询参数的url_for呢?像这样:
<a href="{{ url_for('stats', query_params={chart: [new_chart, other_chart]}) }}>View More</a>
2 个回答
2
根据文档的说明:
Variable arguments that are unknown to the target endpoint are appended to the generated URL as query arguments.
我试过这个,结果和文档上说的一样有效。
redirect(url_for('face_id_detail', faceid=faceid, name=faceidtag))
注意:faceid是这个方法里的一个参数,而name并不在方法的参数中,所以它会被加到查询字符串里。
方法face_id_detail
的定义是:
@app.route('/faceids/<faceid>')
def face_id_detail(faceid):
# the method code
57
如果你在调用 url_for()
的时候,传入了一些额外的关键字参数,而这些参数在路由中并没有被支持,那么这些参数会自动变成查询参数。
如果你有重复的值,可以把它们放在一个列表里:
<a href="{{ url_for('stats', chart=[new_chart, other_chart]) }}>View More</a>
Flask 会这样做:
- 找到
stats
这个端点 - 填入任何需要的路由参数
- 把剩下的关键字参数转换成查询字符串
下面是一个示例,其中 'stats'
是 /
的端点名称:
>>> url_for('stats', chart=['foo', 'bar'])
'/?chart=foo&chart=bar'