How to add custom parameters to an URL query string with Python?
Question: I need to add custom parameters to an URL query string using Python

Example: This is the URL that the browser is fetching (GET):

    
    
    /scr.cgi?q=1&ln=0
    

then some python commands are executed, and as a result I need to set
following URL in the browser:

    
    
    /scr.cgi?q=1&ln=0&SOMESTRING=1
    

Is there some standard approach?


Answer: You can use
[`urlsplit()`](http://docs.python.org/library/urlparse.html#urlparse.urlsplit)
and
[`urlunsplit()`](http://docs.python.org/library/urlparse.html#urlparse.urlunsplit)
to break apart and rebuild a URL, then use
[`urlencode()`](http://docs.python.org/library/urllib.html#urllib.urlencode)
on the parsed query string:

    
    
    from urllib import urlencode
    from urlparse import parse_qs, urlsplit, urlunsplit
    
    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))
    

Use it as follows:

    
    
    >>> set_query_parameter("/scr.cgi?q=1&ln=0", "SOMESTRING", 1)
    '/scr.cgi?q=1&ln=0&SOMESTRING=1'
    

