Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 1 | """Parse (absolute and relative) URLs. |
| 2 | |
| 3 | See RFC 1808: "Relative Uniform Resource Locators", by R. Fielding, |
| 4 | UC Irvine, June 1995. |
| 5 | """ |
Guido van Rossum | 23cb2a8 | 1994-09-12 10:36:35 +0000 | [diff] [blame] | 6 | |
Skip Montanaro | 40fc160 | 2001-03-01 04:27:19 +0000 | [diff] [blame] | 7 | __all__ = ["urlparse", "urlunparse", "urljoin"] |
| 8 | |
Guido van Rossum | 23cb2a8 | 1994-09-12 10:36:35 +0000 | [diff] [blame] | 9 | # A classification of schemes ('' means apply by default) |
| 10 | uses_relative = ['ftp', 'http', 'gopher', 'nntp', 'wais', 'file', |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 11 | 'https', 'shttp', |
| 12 | 'prospero', 'rtsp', 'rtspu', ''] |
Guido van Rossum | 23cb2a8 | 1994-09-12 10:36:35 +0000 | [diff] [blame] | 13 | uses_netloc = ['ftp', 'http', 'gopher', 'nntp', 'telnet', 'wais', |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 14 | 'file', |
| 15 | 'https', 'shttp', 'snews', |
| 16 | 'prospero', 'rtsp', 'rtspu', ''] |
Guido van Rossum | b02092a | 1997-01-02 18:18:27 +0000 | [diff] [blame] | 17 | non_hierarchical = ['gopher', 'hdl', 'mailto', 'news', 'telnet', 'wais', |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 18 | 'snews', 'sip', |
| 19 | ] |
Guido van Rossum | b02092a | 1997-01-02 18:18:27 +0000 | [diff] [blame] | 20 | uses_params = ['ftp', 'hdl', 'prospero', 'http', |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 21 | 'https', 'shttp', 'rtsp', 'rtspu', 'sip', |
| 22 | ''] |
Guido van Rossum | b02092a | 1997-01-02 18:18:27 +0000 | [diff] [blame] | 23 | uses_query = ['http', 'wais', |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 24 | 'https', 'shttp', |
| 25 | 'gopher', 'rtsp', 'rtspu', 'sip', |
| 26 | ''] |
Guido van Rossum | 5feb54c | 1996-05-28 23:10:02 +0000 | [diff] [blame] | 27 | uses_fragment = ['ftp', 'hdl', 'http', 'gopher', 'news', 'nntp', 'wais', |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 28 | 'https', 'shttp', 'snews', |
| 29 | 'file', 'prospero', ''] |
Guido van Rossum | 23cb2a8 | 1994-09-12 10:36:35 +0000 | [diff] [blame] | 30 | |
| 31 | # Characters valid in scheme names |
Guido van Rossum | fad81f0 | 2000-12-19 16:48:13 +0000 | [diff] [blame] | 32 | scheme_chars = ('abcdefghijklmnopqrstuvwxyz' |
| 33 | 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' |
| 34 | '0123456789' |
| 35 | '+-.') |
Guido van Rossum | 23cb2a8 | 1994-09-12 10:36:35 +0000 | [diff] [blame] | 36 | |
Guido van Rossum | 7449540 | 1997-07-14 19:08:15 +0000 | [diff] [blame] | 37 | MAX_CACHE_SIZE = 20 |
Guido van Rossum | 3fd32ec | 1996-05-28 23:54:24 +0000 | [diff] [blame] | 38 | _parse_cache = {} |
| 39 | |
| 40 | def clear_cache(): |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 41 | """Clear the parse cache.""" |
| 42 | global _parse_cache |
| 43 | _parse_cache = {} |
Guido van Rossum | 3fd32ec | 1996-05-28 23:54:24 +0000 | [diff] [blame] | 44 | |
| 45 | |
Fred Drake | 5751a22 | 2001-11-16 02:52:57 +0000 | [diff] [blame] | 46 | def urlparse(url, scheme='', allow_fragments=1): |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 47 | """Parse a URL into 6 components: |
| 48 | <scheme>://<netloc>/<path>;<params>?<query>#<fragment> |
| 49 | Return a 6-tuple: (scheme, netloc, path, params, query, fragment). |
| 50 | Note that we don't break the components up in smaller bits |
| 51 | (e.g. netloc is a single string) and we don't expand % escapes.""" |
Fred Drake | 5751a22 | 2001-11-16 02:52:57 +0000 | [diff] [blame] | 52 | tuple = urlsplit(url, scheme, allow_fragments) |
| 53 | scheme, netloc, url, query, fragment = tuple |
| 54 | if scheme in uses_params and ';' in url: |
| 55 | url, params = _splitparams(url) |
| 56 | else: |
| 57 | params = '' |
| 58 | return scheme, netloc, url, params, query, fragment |
| 59 | |
| 60 | def _splitparams(url): |
| 61 | if '/' in url: |
| 62 | i = url.find(';', url.rfind('/')) |
| 63 | if i < 0: |
| 64 | return url, '' |
| 65 | else: |
| 66 | i = url.find(';') |
| 67 | return url[:i], url[i+1:] |
| 68 | |
| 69 | def urlsplit(url, scheme='', allow_fragments=1): |
| 70 | """Parse a URL into 5 components: |
| 71 | <scheme>://<netloc>/<path>?<query>#<fragment> |
| 72 | Return a 5-tuple: (scheme, netloc, path, query, fragment). |
| 73 | Note that we don't break the components up in smaller bits |
| 74 | (e.g. netloc is a single string) and we don't expand % escapes.""" |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 75 | key = url, scheme, allow_fragments |
| 76 | cached = _parse_cache.get(key, None) |
| 77 | if cached: |
| 78 | return cached |
| 79 | if len(_parse_cache) >= MAX_CACHE_SIZE: # avoid runaway growth |
| 80 | clear_cache() |
Fred Drake | 5751a22 | 2001-11-16 02:52:57 +0000 | [diff] [blame] | 81 | netloc = query = fragment = '' |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 82 | i = url.find(':') |
| 83 | if i > 0: |
| 84 | if url[:i] == 'http': # optimize the common case |
| 85 | scheme = url[:i].lower() |
| 86 | url = url[i+1:] |
| 87 | if url[:2] == '//': |
| 88 | i = url.find('/', 2) |
| 89 | if i < 0: |
| 90 | i = len(url) |
| 91 | netloc = url[2:i] |
| 92 | url = url[i:] |
Fred Drake | 5751a22 | 2001-11-16 02:52:57 +0000 | [diff] [blame] | 93 | if allow_fragments and '#' in url: |
| 94 | url, fragment = url.split('#', 1) |
| 95 | if '?' in url: |
| 96 | url, query = url.split('?', 1) |
| 97 | tuple = scheme, netloc, url, query, fragment |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 98 | _parse_cache[key] = tuple |
| 99 | return tuple |
| 100 | for c in url[:i]: |
| 101 | if c not in scheme_chars: |
| 102 | break |
| 103 | else: |
| 104 | scheme, url = url[:i].lower(), url[i+1:] |
| 105 | if scheme in uses_netloc: |
| 106 | if url[:2] == '//': |
| 107 | i = url.find('/', 2) |
| 108 | if i < 0: |
| 109 | i = len(url) |
| 110 | netloc, url = url[2:i], url[i:] |
Fred Drake | 5751a22 | 2001-11-16 02:52:57 +0000 | [diff] [blame] | 111 | if allow_fragments and scheme in uses_fragment and '#' in url: |
| 112 | url, fragment = url.split('#', 1) |
| 113 | if scheme in uses_query and '?' in url: |
| 114 | url, query = url.split('?', 1) |
| 115 | tuple = scheme, netloc, url, query, fragment |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 116 | _parse_cache[key] = tuple |
| 117 | return tuple |
Guido van Rossum | 23cb2a8 | 1994-09-12 10:36:35 +0000 | [diff] [blame] | 118 | |
Guido van Rossum | 23cb2a8 | 1994-09-12 10:36:35 +0000 | [diff] [blame] | 119 | def urlunparse((scheme, netloc, url, params, query, fragment)): |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 120 | """Put a parsed URL back together again. This may result in a |
| 121 | slightly different, but equivalent URL, if the URL that was parsed |
| 122 | originally had redundant delimiters, e.g. a ? with an empty query |
| 123 | (the draft states that these are equivalent).""" |
Fred Drake | 5751a22 | 2001-11-16 02:52:57 +0000 | [diff] [blame] | 124 | if params: |
| 125 | url = "%s;%s" % (url, params) |
| 126 | return urlunsplit((scheme, netloc, url, query, fragment)) |
| 127 | |
| 128 | def urlunsplit((scheme, netloc, url, query, fragment)): |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 129 | if netloc or (scheme in uses_netloc and url[:2] == '//'): |
| 130 | if url and url[:1] != '/': url = '/' + url |
| 131 | url = '//' + (netloc or '') + url |
| 132 | if scheme: |
| 133 | url = scheme + ':' + url |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 134 | if query: |
| 135 | url = url + '?' + query |
| 136 | if fragment: |
| 137 | url = url + '#' + fragment |
| 138 | return url |
Guido van Rossum | 23cb2a8 | 1994-09-12 10:36:35 +0000 | [diff] [blame] | 139 | |
Jeremy Hylton | 4722da6 | 1998-08-25 19:45:24 +0000 | [diff] [blame] | 140 | def urljoin(base, url, allow_fragments = 1): |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 141 | """Join a base URL and a possibly relative URL to form an absolute |
| 142 | interpretation of the latter.""" |
| 143 | if not base: |
| 144 | return url |
| 145 | if not url: |
| 146 | return base |
| 147 | bscheme, bnetloc, bpath, bparams, bquery, bfragment = \ |
| 148 | urlparse(base, '', allow_fragments) |
| 149 | scheme, netloc, path, params, query, fragment = \ |
| 150 | urlparse(url, bscheme, allow_fragments) |
| 151 | if scheme != bscheme or scheme not in uses_relative: |
| 152 | return url |
| 153 | if scheme in uses_netloc: |
| 154 | if netloc: |
| 155 | return urlunparse((scheme, netloc, path, |
| 156 | params, query, fragment)) |
| 157 | netloc = bnetloc |
| 158 | if path[:1] == '/': |
| 159 | return urlunparse((scheme, netloc, path, |
| 160 | params, query, fragment)) |
| 161 | if not path: |
| 162 | if not params: |
| 163 | params = bparams |
| 164 | if not query: |
| 165 | query = bquery |
| 166 | return urlunparse((scheme, netloc, bpath, |
| 167 | params, query, fragment)) |
| 168 | segments = bpath.split('/')[:-1] + path.split('/') |
| 169 | # XXX The stuff below is bogus in various ways... |
| 170 | if segments[-1] == '.': |
| 171 | segments[-1] = '' |
| 172 | while '.' in segments: |
| 173 | segments.remove('.') |
| 174 | while 1: |
| 175 | i = 1 |
| 176 | n = len(segments) - 1 |
| 177 | while i < n: |
| 178 | if (segments[i] == '..' |
| 179 | and segments[i-1] not in ('', '..')): |
| 180 | del segments[i-1:i+1] |
| 181 | break |
| 182 | i = i+1 |
| 183 | else: |
| 184 | break |
| 185 | if segments == ['', '..']: |
| 186 | segments[-1] = '' |
| 187 | elif len(segments) >= 2 and segments[-1] == '..': |
| 188 | segments[-2:] = [''] |
| 189 | return urlunparse((scheme, netloc, '/'.join(segments), |
| 190 | params, query, fragment)) |
Guido van Rossum | 23cb2a8 | 1994-09-12 10:36:35 +0000 | [diff] [blame] | 191 | |
Guido van Rossum | 3fd32ec | 1996-05-28 23:54:24 +0000 | [diff] [blame] | 192 | def urldefrag(url): |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 193 | """Removes any existing fragment from URL. |
Guido van Rossum | 3fd32ec | 1996-05-28 23:54:24 +0000 | [diff] [blame] | 194 | |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 195 | Returns a tuple of the defragmented URL and the fragment. If |
| 196 | the URL contained no fragments, the second element is the |
| 197 | empty string. |
| 198 | """ |
Fred Drake | 5751a22 | 2001-11-16 02:52:57 +0000 | [diff] [blame] | 199 | if '#' in url: |
| 200 | s, n, p, a, q, frag = urlparse(url) |
| 201 | defrag = urlunparse((s, n, p, a, q, '')) |
| 202 | return defrag, frag |
| 203 | else: |
| 204 | return url, '' |
Guido van Rossum | 3fd32ec | 1996-05-28 23:54:24 +0000 | [diff] [blame] | 205 | |
| 206 | |
Guido van Rossum | 23cb2a8 | 1994-09-12 10:36:35 +0000 | [diff] [blame] | 207 | test_input = """ |
| 208 | http://a/b/c/d |
| 209 | |
| 210 | g:h = <URL:g:h> |
| 211 | http:g = <URL:http://a/b/c/g> |
| 212 | http: = <URL:http://a/b/c/d> |
| 213 | g = <URL:http://a/b/c/g> |
| 214 | ./g = <URL:http://a/b/c/g> |
| 215 | g/ = <URL:http://a/b/c/g/> |
| 216 | /g = <URL:http://a/g> |
| 217 | //g = <URL:http://g> |
| 218 | ?y = <URL:http://a/b/c/d?y> |
| 219 | g?y = <URL:http://a/b/c/g?y> |
| 220 | g?y/./x = <URL:http://a/b/c/g?y/./x> |
| 221 | . = <URL:http://a/b/c/> |
| 222 | ./ = <URL:http://a/b/c/> |
| 223 | .. = <URL:http://a/b/> |
| 224 | ../ = <URL:http://a/b/> |
| 225 | ../g = <URL:http://a/b/g> |
| 226 | ../.. = <URL:http://a/> |
| 227 | ../../g = <URL:http://a/g> |
| 228 | ../../../g = <URL:http://a/../g> |
| 229 | ./../g = <URL:http://a/b/g> |
| 230 | ./g/. = <URL:http://a/b/c/g/> |
| 231 | /./g = <URL:http://a/./g> |
| 232 | g/./h = <URL:http://a/b/c/g/h> |
| 233 | g/../h = <URL:http://a/b/c/h> |
| 234 | http:g = <URL:http://a/b/c/g> |
| 235 | http: = <URL:http://a/b/c/d> |
Andrew M. Kuchling | 5c35520 | 1999-01-06 22:13:09 +0000 | [diff] [blame] | 236 | http:?y = <URL:http://a/b/c/d?y> |
| 237 | http:g?y = <URL:http://a/b/c/g?y> |
| 238 | http:g?y/./x = <URL:http://a/b/c/g?y/./x> |
Guido van Rossum | 23cb2a8 | 1994-09-12 10:36:35 +0000 | [diff] [blame] | 239 | """ |
Guido van Rossum | c08cc50 | 1998-12-21 18:24:09 +0000 | [diff] [blame] | 240 | # XXX The result for //g is actually http://g/; is this a problem? |
Guido van Rossum | 23cb2a8 | 1994-09-12 10:36:35 +0000 | [diff] [blame] | 241 | |
| 242 | def test(): |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 243 | import sys |
| 244 | base = '' |
| 245 | if sys.argv[1:]: |
| 246 | fn = sys.argv[1] |
| 247 | if fn == '-': |
| 248 | fp = sys.stdin |
| 249 | else: |
| 250 | fp = open(fn) |
| 251 | else: |
| 252 | import StringIO |
| 253 | fp = StringIO.StringIO(test_input) |
| 254 | while 1: |
| 255 | line = fp.readline() |
| 256 | if not line: break |
| 257 | words = line.split() |
| 258 | if not words: |
| 259 | continue |
| 260 | url = words[0] |
| 261 | parts = urlparse(url) |
| 262 | print '%-10s : %s' % (url, parts) |
| 263 | abs = urljoin(base, url) |
| 264 | if not base: |
| 265 | base = abs |
| 266 | wrapped = '<URL:%s>' % abs |
| 267 | print '%-10s = %s' % (url, wrapped) |
| 268 | if len(words) == 3 and words[1] == '=': |
| 269 | if wrapped != words[2]: |
| 270 | print 'EXPECTED', words[2], '!!!!!!!!!!' |
Guido van Rossum | 23cb2a8 | 1994-09-12 10:36:35 +0000 | [diff] [blame] | 271 | |
| 272 | if __name__ == '__main__': |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 273 | test() |