| 1 |
from urllib import parse |
| 2 |
|
| 3 |
from django.utils.encoding import force_str |
| 4 |
|
| 5 |
|
| 6 |
def replace_query_param(url, key, val): |
| 7 |
""" |
| 8 |
Given a URL and a key/val pair, set or replace an item in the query |
| 9 |
parameters of the URL, and return the new URL. |
| 10 |
""" |
| 11 |
(scheme, netloc, path, query, fragment) = parse.urlsplit(force_str(url)) |
| 12 |
query_dict = parse.parse_qs(query, keep_blank_values=True) |
| 13 |
query_dict[force_str(key)] = [force_str(val)] |
| 14 |
query = parse.urlencode(sorted(query_dict.items()), doseq=True) |
| 15 |
return parse.urlunsplit((scheme, netloc, path, query, fragment)) |
| 16 |
|
| 17 |
|
| 18 |
def remove_query_param(url, key): |
| 19 |
""" |
| 20 |
Given a URL and a key/val pair, remove an item in the query |
| 21 |
parameters of the URL, and return the new URL. |
| 22 |
""" |
| 23 |
(scheme, netloc, path, query, fragment) = parse.urlsplit(force_str(url)) |
| 24 |
query_dict = parse.parse_qs(query, keep_blank_values=True) |
| 25 |
query_dict.pop(key, None) |
| 26 |
query = parse.urlencode(sorted(query_dict.items()), doseq=True) |
| 27 |
return parse.urlunsplit((scheme, netloc, path, query, fragment)) |