http - any python tools to build a complex url with get parameters? -
i wonder if there library allows me build complex urls lot of parameters. 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 point variable url
contain following string:
http://www.example.com:80/foo/bar/example.php?foo=spaced%20parameter&quuz=42
any ideas?
you write tool yourself, example 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 = [] 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, piece of code can made more secure. example, now, spaced parameters more 1 space not handled properly. also, might want protect against missing parameters key in request input.
Comments
Post a Comment