Create dynamic arguments for url_for in Flask

我与影子孤独终老i 提交于 2019-12-27 12:26:50

问题


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.


回答1:


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

Then access them in the view with request.args:

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



回答2:


Using your example, this wound generate the URLs like you requested if you know your arguments in advance.

<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's answer would be preferred if your set of arguments isn't known until runtime and are stored in a dictionary.



来源:https://stackoverflow.com/questions/32235698/create-dynamic-arguments-for-url-for-in-flask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!