Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify query parameters in current GET request for new url

I access a page with the path /mypage?a=1&b=1&c=1. I want to create a link to a similar url, with some parameters changed: /mypage?a=1&b=2&c=1, b changed from 1 to 2. I know how to get the current arguments with request.args, but the structure is immutable, so I don't know how to edit them. How do I make a new link in the Jinja template with the modified query?

like image 890
stpk Avatar asked Jun 29 '15 16:06

stpk


People also ask

How do you update parameters in a URL?

The value of a parameter can be updated with the set() method of URLSearchParams object. After setting the new value you can get the new query string with the toString() method. This query string can be set as the new value of the search property of the URL object.

How can I add or update a query string parameter?

set('PARAM_HERE', VALUE_HERE); history. pushState(null, '', url); This will preserve everything about the URL and only change or add the one query param. You can also use replaceState instead of pushState if you don't want it to create a new browser history entry.

Can we pass parameters in GET request?

get() method. Using the params property we can pass parameters to the HTTP get request. Either we can pass HttpParams or an object which contains key value pairs of parameters.

How do I pass a URL in a query string?

To pass in parameter values, simply append them to the query string at the end of the base URL. In the above example, the view parameter script name is viewParameter1.


1 Answers

Write a function that modifies the current url's query string and outputs a new url. Add the function to the template globals using your Flask app's template_global decorator so that it can be used in Jinja templates.

from flask import request
from werkzeug.urls import url_encode

@app.template_global()
def modify_query(**new_values):
    args = request.args.copy()

    for key, value in new_values.items():
        args[key] = value

    return '{}?{}'.format(request.path, url_encode(args))
<a href="{{ modify_query(b=2) }}">Link with updated "b"</a>
like image 119
davidism Avatar answered Nov 15 '22 14:11

davidism