1 """Parse (absolute and relative) URLs.
3 See RFC 1808: "Relative Uniform Resource Locators", by R. Fielding,
7 __all__
= ["urlparse", "urlunparse", "urljoin", "urldefrag",
8 "urlsplit", "urlunsplit"]
10 # A classification of schemes ('' means apply by default)
11 uses_relative
= ['ftp', 'http', 'gopher', 'nntp', 'imap',
12 'wais', 'file', 'https', 'shttp', 'mms',
13 'prospero', 'rtsp', 'rtspu', '']
14 uses_netloc
= ['ftp', 'http', 'gopher', 'nntp', 'telnet',
15 'imap', 'wais', 'file', 'mms', 'https', 'shttp',
16 'snews', 'prospero', 'rtsp', 'rtspu', '']
17 non_hierarchical
= ['gopher', 'hdl', 'mailto', 'news',
18 'telnet', 'wais', 'imap', 'snews', 'sip']
19 uses_params
= ['ftp', 'hdl', 'prospero', 'http', 'imap',
20 'https', 'shttp', 'rtsp', 'rtspu', 'sip',
22 uses_query
= ['http', 'wais', 'imap', 'https', 'shttp', 'mms',
23 'gopher', 'rtsp', 'rtspu', 'sip', '']
24 uses_fragment
= ['ftp', 'hdl', 'http', 'gopher', 'news',
25 'nntp', 'wais', 'https', 'shttp', 'snews',
26 'file', 'prospero', '']
28 # Characters valid in scheme names
29 scheme_chars
= ('abcdefghijklmnopqrstuvwxyz'
30 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
38 """Clear the parse cache."""
43 def urlparse(url
, scheme
='', allow_fragments
=1):
44 """Parse a URL into 6 components:
45 <scheme>://<netloc>/<path>;<params>?<query>#<fragment>
46 Return a 6-tuple: (scheme, netloc, path, params, query, fragment).
47 Note that we don't break the components up in smaller bits
48 (e.g. netloc is a single string) and we don't expand % escapes."""
49 tuple = urlsplit(url
, scheme
, allow_fragments
)
50 scheme
, netloc
, url
, query
, fragment
= tuple
51 if scheme
in uses_params
and ';' in url
:
52 url
, params
= _splitparams(url
)
55 return scheme
, netloc
, url
, params
, query
, fragment
57 def _splitparams(url
):
59 i
= url
.find(';', url
.rfind('/'))
64 return url
[:i
], url
[i
+1:]
66 def urlsplit(url
, scheme
='', allow_fragments
=1):
67 """Parse a URL into 5 components:
68 <scheme>://<netloc>/<path>?<query>#<fragment>
69 Return a 5-tuple: (scheme, netloc, path, query, fragment).
70 Note that we don't break the components up in smaller bits
71 (e.g. netloc is a single string) and we don't expand % escapes."""
72 key
= url
, scheme
, allow_fragments
73 cached
= _parse_cache
.get(key
, None)
76 if len(_parse_cache
) >= MAX_CACHE_SIZE
: # avoid runaway growth
78 netloc
= query
= fragment
= ''
81 if url
[:i
] == 'http': # optimize the common case
82 scheme
= url
[:i
].lower()
92 if allow_fragments
and '#' in url
:
93 url
, fragment
= url
.split('#', 1)
95 url
, query
= url
.split('?', 1)
96 tuple = scheme
, netloc
, url
, query
, fragment
97 _parse_cache
[key
] = tuple
100 if c
not in scheme_chars
:
103 scheme
, url
= url
[:i
].lower(), url
[i
+1:]
104 if scheme
in uses_netloc
:
109 netloc
, url
= url
[2:i
], url
[i
:]
110 if allow_fragments
and scheme
in uses_fragment
and '#' in url
:
111 url
, fragment
= url
.split('#', 1)
112 if scheme
in uses_query
and '?' in url
:
113 url
, query
= url
.split('?', 1)
114 tuple = scheme
, netloc
, url
, query
, fragment
115 _parse_cache
[key
] = tuple
118 def urlunparse((scheme
, netloc
, url
, params
, query
, fragment
)):
119 """Put a parsed URL back together again. This may result in a
120 slightly different, but equivalent URL, if the URL that was parsed
121 originally had redundant delimiters, e.g. a ? with an empty query
122 (the draft states that these are equivalent)."""
124 url
= "%s;%s" % (url
, params
)
125 return urlunsplit((scheme
, netloc
, url
, query
, fragment
))
127 def urlunsplit((scheme
, netloc
, url
, query
, fragment
)):
128 if netloc
or (scheme
and scheme
in uses_netloc
and url
[:2] != '//'):
129 if url
and url
[:1] != '/': url
= '/' + url
130 url
= '//' + (netloc
or '') + url
132 url
= scheme
+ ':' + url
134 url
= url
+ '?' + query
136 url
= url
+ '#' + fragment
139 def urljoin(base
, url
, allow_fragments
= 1):
140 """Join a base URL and a possibly relative URL to form an absolute
141 interpretation of the latter."""
146 bscheme
, bnetloc
, bpath
, bparams
, bquery
, bfragment
= \
147 urlparse(base
, '', allow_fragments
)
148 scheme
, netloc
, path
, params
, query
, fragment
= \
149 urlparse(url
, bscheme
, allow_fragments
)
150 if scheme
!= bscheme
or scheme
not in uses_relative
:
152 if scheme
in uses_netloc
:
154 return urlunparse((scheme
, netloc
, path
,
155 params
, query
, fragment
))
158 return urlunparse((scheme
, netloc
, path
,
159 params
, query
, fragment
))
165 return urlunparse((scheme
, netloc
, bpath
,
166 params
, query
, fragment
))
167 segments
= bpath
.split('/')[:-1] + path
.split('/')
168 # XXX The stuff below is bogus in various ways...
169 if segments
[-1] == '.':
171 while '.' in segments
:
175 n
= len(segments
) - 1
177 if (segments
[i
] == '..'
178 and segments
[i
-1] not in ('', '..')):
179 del segments
[i
-1:i
+1]
184 if segments
== ['', '..']:
186 elif len(segments
) >= 2 and segments
[-1] == '..':
188 return urlunparse((scheme
, netloc
, '/'.join(segments
),
189 params
, query
, fragment
))
192 """Removes any existing fragment from URL.
194 Returns a tuple of the defragmented URL and the fragment. If
195 the URL contained no fragments, the second element is the
199 s
, n
, p
, a
, q
, frag
= urlparse(url
)
200 defrag
= urlunparse((s
, n
, p
, a
, q
, ''))
210 http:g = <URL:http://a/b/c/g>
211 http: = <URL:http://a/b/c/d>
212 g = <URL:http://a/b/c/g>
213 ./g = <URL:http://a/b/c/g>
214 g/ = <URL:http://a/b/c/g/>
215 /g = <URL:http://a/g>
217 ?y = <URL:http://a/b/c/d?y>
218 g?y = <URL:http://a/b/c/g?y>
219 g?y/./x = <URL:http://a/b/c/g?y/./x>
220 . = <URL:http://a/b/c/>
221 ./ = <URL:http://a/b/c/>
222 .. = <URL:http://a/b/>
223 ../ = <URL:http://a/b/>
224 ../g = <URL:http://a/b/g>
225 ../.. = <URL:http://a/>
226 ../../g = <URL:http://a/g>
227 ../../../g = <URL:http://a/../g>
228 ./../g = <URL:http://a/b/g>
229 ./g/. = <URL:http://a/b/c/g/>
230 /./g = <URL:http://a/./g>
231 g/./h = <URL:http://a/b/c/g/h>
232 g/../h = <URL:http://a/b/c/h>
233 http:g = <URL:http://a/b/c/g>
234 http: = <URL:http://a/b/c/d>
235 http:?y = <URL:http://a/b/c/d?y>
236 http:g?y = <URL:http://a/b/c/g?y>
237 http:g?y/./x = <URL:http://a/b/c/g?y/./x>
251 fp
= StringIO
.StringIO(test_input
)
259 parts
= urlparse(url
)
260 print '%-10s : %s' % (url
, parts
)
261 abs = urljoin(base
, url
)
264 wrapped
= '<URL:%s>' % abs
265 print '%-10s = %s' % (url
, wrapped
)
266 if len(words
) == 3 and words
[1] == '=':
267 if wrapped
!= words
[2]:
268 print 'EXPECTED', words
[2], '!!!!!!!!!!'
270 if __name__
== '__main__':