Skip to content

Instantly share code, notes, and snippets.

@huihut
Created August 28, 2018 15:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save huihut/50d1a21a4f469110999789f0dbdab866 to your computer and use it in GitHub Desktop.
Save huihut/50d1a21a4f469110999789f0dbdab866 to your computer and use it in GitHub Desktop.
set web url query parameter
def set_query_parameter(url, param_name, param_value):
"""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)
query_params[param_name] = [param_value]
new_query_string = urlencode(query_params, doseq=True)
return urlunsplit((scheme, netloc, path, new_query_string, fragment))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment