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', 'rsync', '']
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 _splitnetloc(url
, start
=0):
67 for c
in '/?#': # the order is important!
68 delim
= url
.find(c
, start
)
73 return url
[start
:delim
], url
[delim
:]
75 def urlsplit(url
, scheme
='', allow_fragments
=1):
76 """Parse a URL into 5 components:
77 <scheme>://<netloc>/<path>?<query>#<fragment>
78 Return a 5-tuple: (scheme, netloc, path, query, fragment).
79 Note that we don't break the components up in smaller bits
80 (e.g. netloc is a single string) and we don't expand % escapes."""
81 key
= url
, scheme
, allow_fragments
82 cached
= _parse_cache
.get(key
, None)
85 if len(_parse_cache
) >= MAX_CACHE_SIZE
: # avoid runaway growth
87 netloc
= query
= fragment
= ''
90 if url
[:i
] == 'http': # optimize the common case
91 scheme
= url
[:i
].lower()
94 netloc
, url
= _splitnetloc(url
, 2)
95 if allow_fragments
and '#' in url
:
96 url
, fragment
= url
.split('#', 1)
98 url
, query
= url
.split('?', 1)
99 tuple = scheme
, netloc
, url
, query
, fragment
100 _parse_cache
[key
] = tuple
103 if c
not in scheme_chars
:
106 scheme
, url
= url
[:i
].lower(), url
[i
+1:]
107 if scheme
in uses_netloc
and url
[:2] == '//':
108 netloc
, url
= _splitnetloc(url
, 2)
109 if allow_fragments
and scheme
in uses_fragment
and '#' in url
:
110 url
, fragment
= url
.split('#', 1)
111 if scheme
in uses_query
and '?' in url
:
112 url
, query
= url
.split('?', 1)
113 tuple = scheme
, netloc
, url
, query
, fragment
114 _parse_cache
[key
] = tuple
117 def urlunparse((scheme
, netloc
, url
, params
, query
, fragment
)):
118 """Put a parsed URL back together again. This may result in a
119 slightly different, but equivalent URL, if the URL that was parsed
120 originally had redundant delimiters, e.g. a ? with an empty query
121 (the draft states that these are equivalent)."""
123 url
= "%s;%s" % (url
, params
)
124 return urlunsplit((scheme
, netloc
, url
, query
, fragment
))
126 def urlunsplit((scheme
, netloc
, url
, query
, fragment
)):
127 if netloc
or (scheme
and scheme
in uses_netloc
and url
[:2] != '//'):
128 if url
and url
[:1] != '/': url
= '/' + url
129 url
= '//' + (netloc
or '') + url
131 url
= scheme
+ ':' + url
133 url
= url
+ '?' + query
135 url
= url
+ '#' + fragment
138 def urljoin(base
, url
, allow_fragments
= 1):
139 """Join a base URL and a possibly relative URL to form an absolute
140 interpretation of the latter."""
145 bscheme
, bnetloc
, bpath
, bparams
, bquery
, bfragment
= \
146 urlparse(base
, '', allow_fragments
)
147 scheme
, netloc
, path
, params
, query
, fragment
= \
148 urlparse(url
, bscheme
, allow_fragments
)
149 if scheme
!= bscheme
or scheme
not in uses_relative
:
151 if scheme
in uses_netloc
:
153 return urlunparse((scheme
, netloc
, path
,
154 params
, query
, fragment
))
157 return urlunparse((scheme
, netloc
, path
,
158 params
, query
, fragment
))
159 if not (path
or params
or query
):
160 return urlunparse((scheme
, netloc
, bpath
,
161 bparams
, bquery
, fragment
))
162 segments
= bpath
.split('/')[:-1] + path
.split('/')
163 # XXX The stuff below is bogus in various ways...
164 if segments
[-1] == '.':
166 while '.' in segments
:
170 n
= len(segments
) - 1
172 if (segments
[i
] == '..'
173 and segments
[i
-1] not in ('', '..')):
174 del segments
[i
-1:i
+1]
179 if segments
== ['', '..']:
181 elif len(segments
) >= 2 and segments
[-1] == '..':
183 return urlunparse((scheme
, netloc
, '/'.join(segments
),
184 params
, query
, fragment
))
187 """Removes any existing fragment from URL.
189 Returns a tuple of the defragmented URL and the fragment. If
190 the URL contained no fragments, the second element is the
194 s
, n
, p
, a
, q
, frag
= urlparse(url
)
195 defrag
= urlunparse((s
, n
, p
, a
, q
, ''))
205 http:g = <URL:http://a/b/c/g>
206 http: = <URL:http://a/b/c/d>
207 g = <URL:http://a/b/c/g>
208 ./g = <URL:http://a/b/c/g>
209 g/ = <URL:http://a/b/c/g/>
210 /g = <URL:http://a/g>
212 ?y = <URL:http://a/b/c/d?y>
213 g?y = <URL:http://a/b/c/g?y>
214 g?y/./x = <URL:http://a/b/c/g?y/./x>
215 . = <URL:http://a/b/c/>
216 ./ = <URL:http://a/b/c/>
217 .. = <URL:http://a/b/>
218 ../ = <URL:http://a/b/>
219 ../g = <URL:http://a/b/g>
220 ../.. = <URL:http://a/>
221 ../../g = <URL:http://a/g>
222 ../../../g = <URL:http://a/../g>
223 ./../g = <URL:http://a/b/g>
224 ./g/. = <URL:http://a/b/c/g/>
225 /./g = <URL:http://a/./g>
226 g/./h = <URL:http://a/b/c/g/h>
227 g/../h = <URL:http://a/b/c/h>
228 http:g = <URL:http://a/b/c/g>
229 http: = <URL:http://a/b/c/d>
230 http:?y = <URL:http://a/b/c/d?y>
231 http:g?y = <URL:http://a/b/c/g?y>
232 http:g?y/./x = <URL:http://a/b/c/g?y/./x>
246 fp
= StringIO
.StringIO(test_input
)
254 parts
= urlparse(url
)
255 print '%-10s : %s' % (url
, parts
)
256 abs = urljoin(base
, url
)
259 wrapped
= '<URL:%s>' % abs
260 print '%-10s = %s' % (url
, wrapped
)
261 if len(words
) == 3 and words
[1] == '=':
262 if wrapped
!= words
[2]:
263 print 'EXPECTED', words
[2], '!!!!!!!!!!'
265 if __name__
== '__main__':