【问题标题】:Create dynamic arguments for url_for in Flask在 Flask 中为 url_for 创建动态参数
【发布时间】:2015-11-21 00:41:08
【问题描述】:

我有一个 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 的情况下运行此模板,因此我不想分配一个点击侦听器并使用 AJAX 为每个链接执行 GET 请求(如果可能的话)。

【问题讨论】:

    标签: python flask jinja2


    【解决方案1】:

    任何与路由参数不匹配的参数都将被添加为查询字符串。假设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')
        ...
    

    【讨论】:

      【解决方案2】:

      使用你的例子,如果你事先知道你的论点,这个伤口会生成你请求的 URL。

      <a href=" {{ url_for('doit', oid=oid, name='bob', age=45 }} ">A specific query</a>
      
      <a href=" {{ url_for('other', oid=oid) }} ">A generic query</a>
      

      如果您的参数集直到运行时才知道并且存储在字典中,那么@davidism 的答案将是首选。

      【讨论】:

        猜你喜欢
        • 2011-11-20
        • 1970-01-01
        • 2022-07-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多