Voici un exemple d'utilisation de urlparse
pour générer des URL. Cela permet d'ajouter le chemin d'accès à l'URL sans se soucier de la vérification des barres obliques.
import urllib
def build_url(base_url, path, args_dict):
# Returns a list in the structure of urlparse.ParseResult
url_parts = list(urllib.parse.urlparse(base_url))
url_parts[2] = path
url_parts[4] = urllib.parse.urlencode(args_dict)
return urllib.parse.urlunparse(url_parts)
>>> args = {'arg1': 'value1', 'arg2': 'value2'}
>>> # works with double slash scenario
>>> build_url('http://www.example.com/', '/somepage/index.html', args)
http://www.example.com/somepage/index.html?arg1=value1&arg2=value2
# works without slash
>>> build_url('http://www.example.com', 'somepage/index.html', args)
http://www.example.com/somepage/index.html?arg1=value1&arg2=value2