urls.py 1.0 KB

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