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', 'wais', 'file',
13 'prospero', 'rtsp', 'rtspu', '']
14 uses_netloc
= ['ftp', 'http', 'gopher', 'nntp', 'telnet', 'wais',
16 'https', 'shttp', 'snews',
17 'prospero', 'rtsp', 'rtspu', '']
18 non_hierarchical
= ['gopher', 'hdl', 'mailto', 'news', 'telnet', 'wais',
21 uses_params
= ['ftp', 'hdl', 'prospero', 'http',
22 'https', 'shttp', 'rtsp', 'rtspu', 'sip',
24 uses_query
= ['http', 'wais',
26 'gopher', 'rtsp', 'rtspu', 'sip',
28 uses_fragment
= ['ftp', 'hdl', 'http', 'gopher', 'news', 'nntp', 'wais',
29 'https', 'shttp', 'snews',
30 'file', 'prospero', '']
32 # Characters valid in scheme names
33 scheme_chars
= ('abcdefghijklmnopqrstuvwxyz'
34 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
42 """Clear the parse cache."""
47 def urlparse(url
, scheme
='', allow_fragments
=1):
48 """Parse a URL into 6 components:
49 <scheme>://<netloc>/<path>;<params>?<query>#<fragment>
50 Return a 6-tuple: (scheme, netloc, path, params, query, fragment).
51 Note that we don't break the components up in smaller bits
52 (e.g. netloc is a single string) and we don't expand % escapes."""
53 tuple = urlsplit(url
, scheme
, allow_fragments
)
54 scheme
, netloc
, url
, query
, fragment
= tuple
55 if scheme
in uses_params
and ';' in url
:
56 url
, params
= _splitparams(url
)
59 return scheme
, netloc
, url
, params
, query
, fragment
61 def _splitparams(url
):
63 i
= url
.find(';', url
.rfind('/'))
68 return url
[:i
], url
[i
+1:]
70 def urlsplit(url
, scheme
='', allow_fragments
=1):
71 """Parse a URL into 5 components:
72 <scheme>://<netloc>/<path>?<query>#<fragment>
73 Return a 5-tuple: (scheme, netloc, path, query, fragment).
74 Note that we don't break the components up in smaller bits
75 (e.g. netloc is a single string) and we don't expand % escapes."""
76 key
= url
, scheme
, allow_fragments
77 cached
= _parse_cache
.get(key
, None)
80 if len(_parse_cache
) >= MAX_CACHE_SIZE
: # avoid runaway growth
82 netloc
= query
= fragment
= ''
85 if url
[:i
] == 'http': # optimize the common case
86 scheme
= url
[:i
].lower()
96 if allow_fragments
and '#' in url
:
97 url
, fragment
= url
.split('#', 1)
99 url
, query
= url
.split('?', 1)
100 tuple = scheme
, netloc
, url
, query
, fragment
101 _parse_cache
[key
] = tuple
104 if c
not in scheme_chars
:
107 scheme
, url
= url
[:i
].lower(), url
[i
+1:]
108 if scheme
in uses_netloc
:
113 netloc
, url
= url
[2:i
], url
[i
:]
114 if allow_fragments
and scheme
in uses_fragment
and '#' in url
:
115 url
, fragment
= url
.split('#', 1)
116 if scheme
in uses_query
and '?' in url
:
117 url
, query
= url
.split('?', 1)
118 tuple = scheme
, netloc
, url
, query
, fragment
119 _parse_cache
[key
] = tuple
122 def urlunparse((scheme
, netloc
, url
, params
, query
, fragment
)):
123 """Put a parsed URL back together again. This may result in a
124 slightly different, but equivalent URL, if the URL that was parsed
125 originally had redundant delimiters, e.g. a ? with an empty query
126 (the draft states that these are equivalent)."""
128 url
= "%s;%s" % (url
, params
)
129 return urlunsplit((scheme
, netloc
, url
, query
, fragment
))
131 def urlunsplit((scheme
, netloc
, url
, query
, fragment
)):
132 if netloc
or (scheme
and scheme
in uses_netloc
and url
[:2] != '//'):
133 if url
and url
[:1] != '/': url
= '/' + url
134 url
= '//' + (netloc
or '') + url
136 url
= scheme
+ ':' + url
138 url
= url
+ '?' + query
140 url
= url
+ '#' + fragment
143 def urljoin(base
, url
, allow_fragments
= 1):
144 """Join a base URL and a possibly relative URL to form an absolute
145 interpretation of the latter."""
150 bscheme
, bnetloc
, bpath
, bparams
, bquery
, bfragment
= \
151 urlparse(base
, '', allow_fragments
)
152 scheme
, netloc
, path
, params
, query
, fragment
= \
153 urlparse(url
, bscheme
, allow_fragments
)
154 if scheme
!= bscheme
or scheme
not in uses_relative
:
156 if scheme
in uses_netloc
:
158 return urlunparse((scheme
, netloc
, path
,
159 params
, query
, fragment
))
162 return urlunparse((scheme
, netloc
, path
,
163 params
, query
, fragment
))
169 return urlunparse((scheme
, netloc
, bpath
,
170 params
, query
, fragment
))
171 segments
= bpath
.split('/')[:-1] + path
.split('/')
172 # XXX The stuff below is bogus in various ways...
173 if segments
[-1] == '.':
175 while '.' in segments
:
179 n
= len(segments
) - 1
181 if (segments
[i
] == '..'
182 and segments
[i
-1] not in ('', '..')):
183 del segments
[i
-1:i
+1]
188 if segments
== ['', '..']:
190 elif len(segments
) >= 2 and segments
[-1] == '..':
192 return urlunparse((scheme
, netloc
, '/'.join(segments
),
193 params
, query
, fragment
))
196 """Removes any existing fragment from URL.
198 Returns a tuple of the defragmented URL and the fragment. If
199 the URL contained no fragments, the second element is the
203 s
, n
, p
, a
, q
, frag
= urlparse(url
)
204 defrag
= urlunparse((s
, n
, p
, a
, q
, ''))
214 http:g = <URL:http://a/b/c/g>
215 http: = <URL:http://a/b/c/d>
216 g = <URL:http://a/b/c/g>
217 ./g = <URL:http://a/b/c/g>
218 g/ = <URL:http://a/b/c/g/>
219 /g = <URL:http://a/g>
221 ?y = <URL:http://a/b/c/d?y>
222 g?y = <URL:http://a/b/c/g?y>
223 g?y/./x = <URL:http://a/b/c/g?y/./x>
224 . = <URL:http://a/b/c/>
225 ./ = <URL:http://a/b/c/>
226 .. = <URL:http://a/b/>
227 ../ = <URL:http://a/b/>
228 ../g = <URL:http://a/b/g>
229 ../.. = <URL:http://a/>
230 ../../g = <URL:http://a/g>
231 ../../../g = <URL:http://a/../g>
232 ./../g = <URL:http://a/b/g>
233 ./g/. = <URL:http://a/b/c/g/>
234 /./g = <URL:http://a/./g>
235 g/./h = <URL:http://a/b/c/g/h>
236 g/../h = <URL:http://a/b/c/h>
237 http:g = <URL:http://a/b/c/g>
238 http: = <URL:http://a/b/c/d>
239 http:?y = <URL:http://a/b/c/d?y>
240 http:g?y = <URL:http://a/b/c/g?y>
241 http:g?y/./x = <URL:http://a/b/c/g?y/./x>
243 # XXX The result for //g is actually http://g/; is this a problem?
256 fp
= StringIO
.StringIO(test_input
)
264 parts
= urlparse(url
)
265 print '%-10s : %s' % (url
, parts
)
266 abs = urljoin(base
, url
)
269 wrapped
= '<URL:%s>' % abs
270 print '%-10s = %s' % (url
, wrapped
)
271 if len(words
) == 3 and words
[1] == '=':
272 if wrapped
!= words
[2]:
273 print 'EXPECTED', words
[2], '!!!!!!!!!!'
275 if __name__
== '__main__':