Util function to manipulate url params

This commit is contained in:
Eliot Berriot 2018-04-06 17:57:50 +02:00
parent 8db832f03b
commit b75872866c
No known key found for this signature in database
GPG Key ID: DD6965E2476E5C27
1 changed files with 18 additions and 0 deletions

View File

@ -1,3 +1,4 @@
from urllib.parse import urlencode, parse_qs, urlsplit, urlunsplit
import os
import shutil
@ -25,3 +26,20 @@ def on_commit(f, *args, **kwargs):
return transaction.on_commit(
lambda: f(*args, **kwargs)
)
def set_query_parameter(url, **kwargs):
"""Given a URL, set or replace a query parameter and return the
modified URL.
>>> set_query_parameter('http://example.com?foo=bar&biz=baz', 'foo', 'stuff')
'http://example.com?foo=stuff&biz=baz'
"""
scheme, netloc, path, query_string, fragment = urlsplit(url)
query_params = parse_qs(query_string)
for param_name, param_value in kwargs.items():
query_params[param_name] = [param_value]
new_query_string = urlencode(query_params, doseq=True)
return urlunsplit((scheme, netloc, path, new_query_string, fragment))