本文介绍了在Flask中为url_for创建动态参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个jinja2模板,可以用于不同的Flask路由。所有这些路由都有一个必需的参数,只能处理 GET 请求,但有些路由可能有额外的参数。



有没有办法在 url_for()上添加额外的参数?






类似于

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


#route'doit /< oid>'带参数
doit / 123?name = bob&age = 45

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

我的用例是提供预定义查询参数:

 < a href ={{url_for('doit',oid = oid,args = extra_args}} >特定查询< / a> 
< a href ={{url_for('other',oid = oid)}}>一般查询< / a>

我想运行这个临时文件迟到没有JavaScript,所以我不希望分配一个点击监听器,并使用AJAX做每个链接的 GET 请求,如果可能的话。

解决方案

任何不匹配路由参数的参数将被添加为查询字符串。假设 extra_args 是一个字典,只是解压缩。

  extra_args = { 'hello':'world'} 
url_for('doit',oid = oid,** extra_args)
#/ doit / 123?hello = world $ b $ 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')
...


I have a jinja2 template which I reuse for different Flask routes. All of these routes have a single required parameter and handle only GET requests, but some routes may have extra arguments.

Is there a way to append extra arguments onto url_for()?


Something like

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

which will render to (depending on the route endpoint):

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

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

My use case would be to provide links with predefined query arguments:

<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>

I would like to run this template without JavaScript, so I would not like to assign a click listener and use AJAX to do a GET request for each link if that is possible.

解决方案

Any arguments that don't match route parameters will be added as the query string. Assuming extra_args is a dict, just unpack it.

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

The access them in the view with request.args:

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

这篇关于在Flask中为url_for创建动态参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 17:29