rublex rublex - 1 year ago 126
Python Question

Create dynamic arguments for url_for in Flask

I have a jinja2 template which I reuse for different Flask routes. All of these routes have a single required parameter and handle only

requests, but some routes may have extra arguments.

Is there a way to append extra arguments onto

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

# route 'other/<oid>' without arguments

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
request for each link if that is possible.

Answer Source

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:

def doit(oid)
    hello = request.args.get('hello')