在Flask中为url_for创建动态参数

红宝石

我有一个jinja2模板,可以在不同的Flask路由中重复使用。所有这些路由都具有一个必需的参数,并且仅处理GET请求,但是某些路由可能具有额外的参数。

有没有办法在上面附加参数url_for()


就像是

url_for(my_custom_url, oid=oid, args=extra_args)

将呈现给它(取决于路由端点):

# route 'doit/<oid>' with arguments
doit/123?name=bob&age=45

# route 'other/<oid>' without arguments
other/123

我的用例是提供带有预定义查询参数的链接:

<a href=" {{ url_for('doit', oid=oid, args=extra_args }} ">A specific query</a>
<a href=" {{ url_for('other', oid=oid) }} ">A generic query</a>

我想在没有JavaScript的情况下运行此模板,因此,如果可能的话,我不想分配一个Click侦听器并使用AJAXGET对每个链接进行请求。

大卫主义

与路由参数不匹配的所有参数都将添加为查询字符串。假设extra_args是一个命令,只需解压缩它即可。

extra_args = {'hello': 'world'}
url_for('doit', oid=oid, **extra_args)
# /doit/123?hello=world
url_for('doit', oid=oid, hello='davidism')
# /doit/123?hello=davidism

然后使用以下命令在视图中访问它们request.args

@app.route('/doit/<int:oid>')
def doit(oid)
    hello = request.args.get('hello')
    ...

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章