Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to do url join in python using multiple parameters

Tags:

python

I am having a simple doubt.. I am trying to join three parts of a string using urljoin..

   host = "http://foo.com:port"
   ver = "/v1"
   exten = "/path"

Rather than doing host+ver+exten, I want to use urljoin to generate url But urljoin is giving http://foo.com:poort/v1 ( if i try urljoin(host,ver,exten) )

like image 757
frazman Avatar asked Jul 17 '14 22:07

frazman


2 Answers

The way urljoin works is by combining a base URL and another URL. You could try joining the relative paths together with simple string combinations, and then use urljoin to join the host and the combined relative path.

Like:

rel = ver + exten
url = urljoin(host, rel)

Sadly if you want to combine multiple URL paths, you will have to use another library. If you're using a non-Windows machine, you could use the os.path module to join them together just like you would combine a local file path.

like image 147
Philip Massey Avatar answered Sep 28 '22 23:09

Philip Massey


Here's one way to do it on linux(python 2.x):

import urlparse
import os
def url_join(host, version, *additional_path):
    return urlparse.urljoin(host, os.path.join(version, *additional_path))

and then call this function like:

>> url_join("http://example.com:port", "v1", "path1", "path2", "path3")
>> 'http://example.com:port/v1/path1/path2/path3
like image 41
AnukuL Avatar answered Sep 28 '22 22:09

AnukuL