any python tools to build a complex url with get parameters?

I wonder if there is some library that allows me to build complex urls with a lot of parameters. Something like the following:

request = {
  'protocol': "http",
  'hostname': "www.example.com",
  'port': "80",
  'page': "/foo/bar/example.php",
  'parameters': {
    'foo': "spaced parameter",
    'quuz': 42
  }
}

url = urlbuilder.build(request)

At this point the variable url will contain the following string:

http://www.example.com:80/foo/bar/example.php?foo=spaced%20parameter&quuz=42

any ideas?

Answers


You could write the tool yourself, for example like this:

class UrlBuilder(object):
    def build(self, request):
        url = [ request['protocol'],
                '://',
                request['hostname'],
                ':',
                request['port'],
                request['page'],
                ]
        pars = request['parameters']
        if len(pars):
            url.append('?')
        parstr = []
        for key,val in pars.iteritems():
            val = str(val)
            val = val.replace(' ', '%20')
            parstr.append( '{key}={val}'.format(key=key, val=val) )
        url.append( '&'.join(parstr) ) 
        return ''.join(url)

request = {
  'protocol': "http",
  'hostname': "www.example.com",
  'port': "80",
  'page': "/foo/bar/example.php",
  'parameters': {
    'foo': "spaced parameter",
    'quuz': 42
  }
}

urlbuilder = UrlBuilder()
url = urlbuilder.build(request)
print url

Output:

http://www.example.com:80/foo/bar/example.php?foo=spaced%20parameter&quuz=42

Of course, this piece of code can be made more secure. For example, for now, spaced parameters with more than one space are not handled properly. Also, you might want to protect against a missing parameters key in the request input.


Need Your Help

SVG Scaling Issue in IE9

html css svg internet-explorer-9 image-resizing

Having issues using small svg in IE9. It get's chopped off on the right/is not centered:

To Split into fixed sequences smoothly by group values of flags

algorithm shell unix data-structures split

I want to split as even as possible, no more than one byte difference between the sizes of the output files by altering the amount files but having some minimum number and maximum number of files. ...