Absolute to relative URL?

Max M maxm at mxm.dk
Thu Apr 4 04:01:25 EST 2002


Thomas Guettler wrote:


> Is there already a function in the standard python modules
> which returns the a relative url given two absolute urls?
> 
> Example:
> 
> relative_url("http://foo/a/b/c", "http://foo/a/d")
>  --> return: "../d"

I hope you mean that the result should be "../../d" ??

A function that generates a relative path given two absolute urls?

Not that I am aware of, but this problem was more fun than what I really 
should be working on today :-/, so here is an attempt:

regards Max M

-----------------------------------------------------

from urlparse import urlparse, urljoin


def relativePath(url1,url2):
     "Returns relative path from url1 to url1"
     # get just path parts
     u1Parts = urlparse(url1)[2].split('/')[1:]
     u2Parts = urlparse(url2)[2].split('/')[1:]
     u1Len = len(u1Parts)
     u2Len = len(u2Parts)

##    # uncomment if simillar paths should return '.'
##    if u1Parts == u2Parts:
##        return '.' # that was easy

     diffStart = 0 # from where do the paths differ?
     for i in range(min(u1Len, u2Len)):
         if u1Parts[i] == u2Parts[i]:
             diffStart += 1

     result = []
     nDirsUp = len(u1Parts[diffStart:])
     result += ['..']*nDirsUp + u2Parts[diffStart:]
     return '/'.join(result)



url1 = "http://foo/a/b/c"
url2 = "http://foo/a/b/c"
print "Excpect: ''"
print repr(relativePath(url1,url2))
print ""

url1 = "http://foo/a/b/c"
url2 = "http://foo/a/d"
print "Excpect: '../../d'"
print repr(relativePath(url1,url2))
print ""

url1 = "http://foo/a/b/c"
url2 = "http://foo/a/b"
print "Excpect: '..'"
print repr(relativePath(url1,url2))
print ""

url1 = "http://foo/a/d"
url2 = "http://foo/a/b/c"
print "Excpect: '../b/c'"
print repr(relativePath(url1,url2))
print ""

url1 = "http://foo/a/b"
url2 = "http://foo/a/b/c"
print "Excpect: 'c'"
print repr(relativePath(url1,url2))
print ""


-------------------------------

Excpect: ''
''

Excpect: '../../d'
'../../d'

Excpect: '..'
'..'

Excpect: '../b/c'
'../b/c'

Excpect: 'c'
'c'




More information about the Python-list mailing list