Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redirecting with url_for to a path with query params in flask

Tags:

python

flask

So let's say I have a template with a couple of links, the links will be like this:

<a class='btn btn-primary' href='/?chart=new_chart&chart=other_chart'>View Summary</a> 

However, most of the times when I have done links or included resources, I have used the following syntax:

<script src="{{ url_for('static', filename='some_silly_js') }}"></script> 

is it possible to do a url_for with query parameters? Something like:

<a href="{{ url_for('stats', query_params={chart: [new_chart, other_chart]}) }}>View More</a> 
like image 463
corvid Avatar asked Apr 17 '14 21:04

corvid


People also ask

How do you pass a parameter in a redirect Flask?

To pass arguments into redirect(url_for()) of Flask, we define the destination route to get the request parameters. Then we can call url_for with the parameters. to add the /found/<email>/<list_of_objects> route that maps to the found function. In it, we get the the URL parameters from the found function's parameters.

How do I redirect from one route to another in Flask?

Flask – Redirect & ErrorsFlask class has a redirect() function. When called, it returns a response object and redirects the user to another target location with specified status code. location parameter is the URL where response should be redirected. statuscode sent to browser's header, defaults to 302.

How do I get query params in Flask?

To access an individual known param passed in the query string, you can use request. args. get('param') . This is the "right" way to do it, as far as I know.


1 Answers

Any extra keyword parameters passed to url_for() which are not supported by the route are automatically added as query parameters.

For repeated values, pass in a list:

<a href="{{ url_for('stats', chart=[new_chart, other_chart]) }}>View More</a> 

Flask will then:

  1. find the stats endpoint
  2. fill in any required route parameters
  3. transform any remaining keyword parameters to a query string

Demo, with 'stats' being the endpoint name for /:

>>> url_for('stats', chart=['foo', 'bar']) '/?chart=foo&chart=bar' 
like image 162
Martijn Pieters Avatar answered Oct 02 '22 17:10

Martijn Pieters