blob: e5de53ae8a0cbf62bf580afeebd99406706dc2eb [file] [log] [blame]
Guido van Rossume7b146f2000-02-04 15:28:42 +00001"""Parse (absolute and relative) URLs.
2
3See RFC 1808: "Relative Uniform Resource Locators", by R. Fielding,
4UC Irvine, June 1995.
5"""
Guido van Rossum23cb2a81994-09-12 10:36:35 +00006
Fred Drakef606e8d2002-10-16 21:21:39 +00007__all__ = ["urlparse", "urlunparse", "urljoin", "urldefrag",
8 "urlsplit", "urlunsplit"]
Skip Montanaro40fc1602001-03-01 04:27:19 +00009
Guido van Rossum23cb2a81994-09-12 10:36:35 +000010# A classification of schemes ('' means apply by default)
Raymond Hettinger156c49a2004-05-07 05:50:35 +000011uses_relative = ['ftp', 'http', 'gopher', 'nntp', 'imap',
Georg Brandl89f35ac2006-01-20 17:24:23 +000012 'wais', 'file', 'https', 'shttp', 'mms',
13 'prospero', 'rtsp', 'rtspu', '', 'sftp']
Raymond Hettinger156c49a2004-05-07 05:50:35 +000014uses_netloc = ['ftp', 'http', 'gopher', 'nntp', 'telnet',
Georg Brandl89f35ac2006-01-20 17:24:23 +000015 'imap', 'wais', 'file', 'mms', 'https', 'shttp',
16 'snews', 'prospero', 'rtsp', 'rtspu', 'rsync', '',
17 'svn', 'svn+ssh', 'sftp']
Raymond Hettinger156c49a2004-05-07 05:50:35 +000018non_hierarchical = ['gopher', 'hdl', 'mailto', 'news',
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000019 'telnet', 'wais', 'imap', 'snews', 'sip', 'sips']
Raymond Hettinger156c49a2004-05-07 05:50:35 +000020uses_params = ['ftp', 'hdl', 'prospero', 'http', 'imap',
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000021 'https', 'shttp', 'rtsp', 'rtspu', 'sip', 'sips',
Georg Brandl89f35ac2006-01-20 17:24:23 +000022 'mms', '', 'sftp']
Raymond Hettinger156c49a2004-05-07 05:50:35 +000023uses_query = ['http', 'wais', 'imap', 'https', 'shttp', 'mms',
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000024 'gopher', 'rtsp', 'rtspu', 'sip', 'sips', '']
Raymond Hettinger156c49a2004-05-07 05:50:35 +000025uses_fragment = ['ftp', 'hdl', 'http', 'gopher', 'news',
Georg Brandl89f35ac2006-01-20 17:24:23 +000026 'nntp', 'wais', 'https', 'shttp', 'snews',
27 'file', 'prospero', '']
Guido van Rossum23cb2a81994-09-12 10:36:35 +000028
29# Characters valid in scheme names
Guido van Rossumfad81f02000-12-19 16:48:13 +000030scheme_chars = ('abcdefghijklmnopqrstuvwxyz'
31 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
32 '0123456789'
33 '+-.')
Guido van Rossum23cb2a81994-09-12 10:36:35 +000034
Guido van Rossum74495401997-07-14 19:08:15 +000035MAX_CACHE_SIZE = 20
Guido van Rossum3fd32ec1996-05-28 23:54:24 +000036_parse_cache = {}
37
38def clear_cache():
Tim Peterse1190062001-01-15 03:34:38 +000039 """Clear the parse cache."""
40 global _parse_cache
41 _parse_cache = {}
Guido van Rossum3fd32ec1996-05-28 23:54:24 +000042
43
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000044class BaseResult(tuple):
45 """Base class for the parsed result objects.
46
47 This provides the attributes shared by the two derived result
48 objects as read-only properties. The derived classes are
49 responsible for checking the right number of arguments were
50 supplied to the constructor.
51
52 """
53
54 __slots__ = ()
55
56 # Attributes that access the basic components of the URL:
57
58 @property
59 def scheme(self):
60 return self[0]
61
62 @property
63 def netloc(self):
64 return self[1]
65
66 @property
67 def path(self):
68 return self[2]
69
70 @property
71 def query(self):
72 return self[-2]
73
74 @property
75 def fragment(self):
76 return self[-1]
77
78 # Additional attributes that provide access to parsed-out portions
79 # of the netloc:
80
81 @property
82 def username(self):
83 netloc = self.netloc
84 if "@" in netloc:
85 userinfo = netloc.split("@", 1)[0]
86 if ":" in userinfo:
87 userinfo = userinfo.split(":", 1)[0]
88 return userinfo
89 return None
90
91 @property
92 def password(self):
93 netloc = self.netloc
94 if "@" in netloc:
95 userinfo = netloc.split("@", 1)[0]
96 if ":" in userinfo:
97 return userinfo.split(":", 1)[1]
98 return None
99
100 @property
101 def hostname(self):
102 netloc = self.netloc
103 if "@" in netloc:
104 netloc = netloc.split("@", 1)[1]
105 if ":" in netloc:
106 netloc = netloc.split(":", 1)[0]
107 return netloc.lower() or None
108
109 @property
110 def port(self):
111 netloc = self.netloc
112 if "@" in netloc:
113 netloc = netloc.split("@", 1)[1]
114 if ":" in netloc:
115 port = netloc.split(":", 1)[1]
116 return int(port, 10)
117 return None
118
119
120class SplitResult(BaseResult):
121
122 __slots__ = ()
123
124 def __new__(cls, scheme, netloc, path, query, fragment):
125 return BaseResult.__new__(
126 cls, (scheme, netloc, path, query, fragment))
127
128 def geturl(self):
129 return urlunsplit(self)
130
131
132class ParseResult(BaseResult):
133
134 __slots__ = ()
135
136 def __new__(cls, scheme, netloc, path, params, query, fragment):
137 return BaseResult.__new__(
138 cls, (scheme, netloc, path, params, query, fragment))
139
140 @property
141 def params(self):
142 return self[3]
143
144 def geturl(self):
145 return urlunparse(self)
146
147
148def urlparse(url, scheme='', allow_fragments=True):
Tim Peterse1190062001-01-15 03:34:38 +0000149 """Parse a URL into 6 components:
150 <scheme>://<netloc>/<path>;<params>?<query>#<fragment>
151 Return a 6-tuple: (scheme, netloc, path, params, query, fragment).
152 Note that we don't break the components up in smaller bits
153 (e.g. netloc is a single string) and we don't expand % escapes."""
Fred Drake5751a222001-11-16 02:52:57 +0000154 tuple = urlsplit(url, scheme, allow_fragments)
155 scheme, netloc, url, query, fragment = tuple
156 if scheme in uses_params and ';' in url:
157 url, params = _splitparams(url)
158 else:
159 params = ''
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000160 return ParseResult(scheme, netloc, url, params, query, fragment)
Fred Drake5751a222001-11-16 02:52:57 +0000161
162def _splitparams(url):
163 if '/' in url:
164 i = url.find(';', url.rfind('/'))
165 if i < 0:
166 return url, ''
167 else:
168 i = url.find(';')
169 return url[:i], url[i+1:]
170
Johannes Gijsbers41e4faa2005-01-09 15:29:10 +0000171def _splitnetloc(url, start=0):
172 for c in '/?#': # the order is important!
173 delim = url.find(c, start)
174 if delim >= 0:
175 break
176 else:
177 delim = len(url)
178 return url[start:delim], url[delim:]
179
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000180def urlsplit(url, scheme='', allow_fragments=True):
Fred Drake5751a222001-11-16 02:52:57 +0000181 """Parse a URL into 5 components:
182 <scheme>://<netloc>/<path>?<query>#<fragment>
183 Return a 5-tuple: (scheme, netloc, path, query, fragment).
184 Note that we don't break the components up in smaller bits
185 (e.g. netloc is a single string) and we don't expand % escapes."""
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000186 allow_fragments = bool(allow_fragments)
Tim Peterse1190062001-01-15 03:34:38 +0000187 key = url, scheme, allow_fragments
188 cached = _parse_cache.get(key, None)
189 if cached:
190 return cached
191 if len(_parse_cache) >= MAX_CACHE_SIZE: # avoid runaway growth
192 clear_cache()
Fred Drake5751a222001-11-16 02:52:57 +0000193 netloc = query = fragment = ''
Tim Peterse1190062001-01-15 03:34:38 +0000194 i = url.find(':')
195 if i > 0:
196 if url[:i] == 'http': # optimize the common case
197 scheme = url[:i].lower()
198 url = url[i+1:]
199 if url[:2] == '//':
Johannes Gijsbers41e4faa2005-01-09 15:29:10 +0000200 netloc, url = _splitnetloc(url, 2)
Fred Drake5751a222001-11-16 02:52:57 +0000201 if allow_fragments and '#' in url:
202 url, fragment = url.split('#', 1)
203 if '?' in url:
204 url, query = url.split('?', 1)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000205 v = SplitResult(scheme, netloc, url, query, fragment)
206 _parse_cache[key] = v
207 return v
Tim Peterse1190062001-01-15 03:34:38 +0000208 for c in url[:i]:
209 if c not in scheme_chars:
210 break
211 else:
212 scheme, url = url[:i].lower(), url[i+1:]
Johannes Gijsbers41e4faa2005-01-09 15:29:10 +0000213 if scheme in uses_netloc and url[:2] == '//':
214 netloc, url = _splitnetloc(url, 2)
Fred Drake5751a222001-11-16 02:52:57 +0000215 if allow_fragments and scheme in uses_fragment and '#' in url:
216 url, fragment = url.split('#', 1)
217 if scheme in uses_query and '?' in url:
218 url, query = url.split('?', 1)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000219 v = SplitResult(scheme, netloc, url, query, fragment)
220 _parse_cache[key] = v
221 return v
Guido van Rossum23cb2a81994-09-12 10:36:35 +0000222
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000223def urlunparse(components):
Tim Peterse1190062001-01-15 03:34:38 +0000224 """Put a parsed URL back together again. This may result in a
225 slightly different, but equivalent URL, if the URL that was parsed
226 originally had redundant delimiters, e.g. a ? with an empty query
227 (the draft states that these are equivalent)."""
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000228 scheme, netloc, url, params, query, fragment = components
Fred Drake5751a222001-11-16 02:52:57 +0000229 if params:
230 url = "%s;%s" % (url, params)
231 return urlunsplit((scheme, netloc, url, query, fragment))
232
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000233def urlunsplit(components):
234 scheme, netloc, url, query, fragment = components
Guido van Rossumbbc05682002-10-14 19:59:54 +0000235 if netloc or (scheme and scheme in uses_netloc and url[:2] != '//'):
Tim Peterse1190062001-01-15 03:34:38 +0000236 if url and url[:1] != '/': url = '/' + url
237 url = '//' + (netloc or '') + url
238 if scheme:
239 url = scheme + ':' + url
Tim Peterse1190062001-01-15 03:34:38 +0000240 if query:
241 url = url + '?' + query
242 if fragment:
243 url = url + '#' + fragment
244 return url
Guido van Rossum23cb2a81994-09-12 10:36:35 +0000245
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000246def urljoin(base, url, allow_fragments=True):
Tim Peterse1190062001-01-15 03:34:38 +0000247 """Join a base URL and a possibly relative URL to form an absolute
248 interpretation of the latter."""
249 if not base:
250 return url
251 if not url:
252 return base
253 bscheme, bnetloc, bpath, bparams, bquery, bfragment = \
254 urlparse(base, '', allow_fragments)
255 scheme, netloc, path, params, query, fragment = \
256 urlparse(url, bscheme, allow_fragments)
257 if scheme != bscheme or scheme not in uses_relative:
258 return url
259 if scheme in uses_netloc:
260 if netloc:
261 return urlunparse((scheme, netloc, path,
262 params, query, fragment))
263 netloc = bnetloc
264 if path[:1] == '/':
265 return urlunparse((scheme, netloc, path,
266 params, query, fragment))
Brett Cannon8da2a522003-10-12 04:29:10 +0000267 if not (path or params or query):
Tim Peterse1190062001-01-15 03:34:38 +0000268 return urlunparse((scheme, netloc, bpath,
Brett Cannon8da2a522003-10-12 04:29:10 +0000269 bparams, bquery, fragment))
Tim Peterse1190062001-01-15 03:34:38 +0000270 segments = bpath.split('/')[:-1] + path.split('/')
271 # XXX The stuff below is bogus in various ways...
272 if segments[-1] == '.':
273 segments[-1] = ''
274 while '.' in segments:
275 segments.remove('.')
276 while 1:
277 i = 1
278 n = len(segments) - 1
279 while i < n:
280 if (segments[i] == '..'
281 and segments[i-1] not in ('', '..')):
282 del segments[i-1:i+1]
283 break
284 i = i+1
285 else:
286 break
287 if segments == ['', '..']:
288 segments[-1] = ''
289 elif len(segments) >= 2 and segments[-1] == '..':
290 segments[-2:] = ['']
291 return urlunparse((scheme, netloc, '/'.join(segments),
292 params, query, fragment))
Guido van Rossum23cb2a81994-09-12 10:36:35 +0000293
Guido van Rossum3fd32ec1996-05-28 23:54:24 +0000294def urldefrag(url):
Tim Peterse1190062001-01-15 03:34:38 +0000295 """Removes any existing fragment from URL.
Guido van Rossum3fd32ec1996-05-28 23:54:24 +0000296
Tim Peterse1190062001-01-15 03:34:38 +0000297 Returns a tuple of the defragmented URL and the fragment. If
298 the URL contained no fragments, the second element is the
299 empty string.
300 """
Fred Drake5751a222001-11-16 02:52:57 +0000301 if '#' in url:
302 s, n, p, a, q, frag = urlparse(url)
303 defrag = urlunparse((s, n, p, a, q, ''))
304 return defrag, frag
305 else:
306 return url, ''
Guido van Rossum3fd32ec1996-05-28 23:54:24 +0000307
308
Guido van Rossum23cb2a81994-09-12 10:36:35 +0000309test_input = """
310 http://a/b/c/d
311
312 g:h = <URL:g:h>
313 http:g = <URL:http://a/b/c/g>
314 http: = <URL:http://a/b/c/d>
315 g = <URL:http://a/b/c/g>
316 ./g = <URL:http://a/b/c/g>
317 g/ = <URL:http://a/b/c/g/>
318 /g = <URL:http://a/g>
319 //g = <URL:http://g>
320 ?y = <URL:http://a/b/c/d?y>
321 g?y = <URL:http://a/b/c/g?y>
322 g?y/./x = <URL:http://a/b/c/g?y/./x>
323 . = <URL:http://a/b/c/>
324 ./ = <URL:http://a/b/c/>
325 .. = <URL:http://a/b/>
326 ../ = <URL:http://a/b/>
327 ../g = <URL:http://a/b/g>
328 ../.. = <URL:http://a/>
329 ../../g = <URL:http://a/g>
330 ../../../g = <URL:http://a/../g>
331 ./../g = <URL:http://a/b/g>
332 ./g/. = <URL:http://a/b/c/g/>
333 /./g = <URL:http://a/./g>
334 g/./h = <URL:http://a/b/c/g/h>
335 g/../h = <URL:http://a/b/c/h>
336 http:g = <URL:http://a/b/c/g>
337 http: = <URL:http://a/b/c/d>
Andrew M. Kuchling5c355201999-01-06 22:13:09 +0000338 http:?y = <URL:http://a/b/c/d?y>
339 http:g?y = <URL:http://a/b/c/g?y>
340 http:g?y/./x = <URL:http://a/b/c/g?y/./x>
Guido van Rossum23cb2a81994-09-12 10:36:35 +0000341"""
Guido van Rossum23cb2a81994-09-12 10:36:35 +0000342
343def test():
Tim Peterse1190062001-01-15 03:34:38 +0000344 import sys
345 base = ''
346 if sys.argv[1:]:
347 fn = sys.argv[1]
348 if fn == '-':
349 fp = sys.stdin
350 else:
351 fp = open(fn)
352 else:
Guido van Rossum68937b42007-05-18 00:51:22 +0000353 from io import StringIO
Raymond Hettingera6172712004-12-31 19:15:26 +0000354 fp = StringIO(test_input)
Tim Peterse1190062001-01-15 03:34:38 +0000355 while 1:
356 line = fp.readline()
357 if not line: break
358 words = line.split()
359 if not words:
360 continue
361 url = words[0]
362 parts = urlparse(url)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000363 print('%-10s : %s' % (url, parts))
Tim Peterse1190062001-01-15 03:34:38 +0000364 abs = urljoin(base, url)
365 if not base:
366 base = abs
367 wrapped = '<URL:%s>' % abs
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000368 print('%-10s = %s' % (url, wrapped))
Tim Peterse1190062001-01-15 03:34:38 +0000369 if len(words) == 3 and words[1] == '=':
370 if wrapped != words[2]:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000371 print('EXPECTED', words[2], '!!!!!!!!!!')
Guido van Rossum23cb2a81994-09-12 10:36:35 +0000372
373if __name__ == '__main__':
Tim Peterse1190062001-01-15 03:34:38 +0000374 test()