2019-04-30 18:53:44 +03:00
|
|
|
from urllib import parse
|
|
|
|
|
2017-11-06 13:46:37 +03:00
|
|
|
from django.utils.encoding import force_str
|
2015-01-16 23:30:46 +03:00
|
|
|
|
|
|
|
|
|
|
|
def replace_query_param(url, key, val):
|
|
|
|
"""
|
|
|
|
Given a URL and a key/val pair, set or replace an item in the query
|
|
|
|
parameters of the URL, and return the new URL.
|
|
|
|
"""
|
2019-04-30 18:53:44 +03:00
|
|
|
(scheme, netloc, path, query, fragment) = parse.urlsplit(force_str(url))
|
|
|
|
query_dict = parse.parse_qs(query, keep_blank_values=True)
|
2017-11-06 13:46:37 +03:00
|
|
|
query_dict[force_str(key)] = [force_str(val)]
|
2019-04-30 18:53:44 +03:00
|
|
|
query = parse.urlencode(sorted(list(query_dict.items())), doseq=True)
|
|
|
|
return parse.urlunsplit((scheme, netloc, path, query, fragment))
|
2015-01-16 23:30:46 +03:00
|
|
|
|
|
|
|
|
|
|
|
def remove_query_param(url, key):
|
|
|
|
"""
|
|
|
|
Given a URL and a key/val pair, remove an item in the query
|
|
|
|
parameters of the URL, and return the new URL.
|
|
|
|
"""
|
2019-04-30 18:53:44 +03:00
|
|
|
(scheme, netloc, path, query, fragment) = parse.urlsplit(force_str(url))
|
|
|
|
query_dict = parse.parse_qs(query, keep_blank_values=True)
|
2015-01-16 23:30:46 +03:00
|
|
|
query_dict.pop(key, None)
|
2019-04-30 18:53:44 +03:00
|
|
|
query = parse.urlencode(sorted(list(query_dict.items())), doseq=True)
|
|
|
|
return parse.urlunsplit((scheme, netloc, path, query, fragment))
|