This commit was manufactured by cvs2svn to create tag 'r241c1'.
[python/dscho.git] / Lib / urlparse.py
blob7fd1633ab95f7587c9bf5e5cbd48b48070a693d1
1 """Parse (absolute and relative) URLs.
3 See RFC 1808: "Relative Uniform Resource Locators", by R. Fielding,
4 UC Irvine, June 1995.
5 """
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',
21 'mms', '']
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'
31 '0123456789'
32 '+-.')
34 MAX_CACHE_SIZE = 20
35 _parse_cache = {}
37 def clear_cache():
38 """Clear the parse cache."""
39 global _parse_cache
40 _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)
53 else:
54 params = ''
55 return scheme, netloc, url, params, query, fragment
57 def _splitparams(url):
58 if '/' in url:
59 i = url.find(';', url.rfind('/'))
60 if i < 0:
61 return url, ''
62 else:
63 i = url.find(';')
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)
69 if delim >= 0:
70 break
71 else:
72 delim = len(url)
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)
83 if cached:
84 return cached
85 if len(_parse_cache) >= MAX_CACHE_SIZE: # avoid runaway growth
86 clear_cache()
87 netloc = query = fragment = ''
88 i = url.find(':')
89 if i > 0:
90 if url[:i] == 'http': # optimize the common case
91 scheme = url[:i].lower()
92 url = url[i+1:]
93 if url[:2] == '//':
94 netloc, url = _splitnetloc(url, 2)
95 if allow_fragments and '#' in url:
96 url, fragment = url.split('#', 1)
97 if '?' in url:
98 url, query = url.split('?', 1)
99 tuple = scheme, netloc, url, query, fragment
100 _parse_cache[key] = tuple
101 return tuple
102 for c in url[:i]:
103 if c not in scheme_chars:
104 break
105 else:
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
115 return 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)."""
122 if params:
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
130 if scheme:
131 url = scheme + ':' + url
132 if query:
133 url = url + '?' + query
134 if fragment:
135 url = url + '#' + fragment
136 return url
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."""
141 if not base:
142 return url
143 if not url:
144 return base
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:
150 return url
151 if scheme in uses_netloc:
152 if netloc:
153 return urlunparse((scheme, netloc, path,
154 params, query, fragment))
155 netloc = bnetloc
156 if path[:1] == '/':
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] == '.':
165 segments[-1] = ''
166 while '.' in segments:
167 segments.remove('.')
168 while 1:
169 i = 1
170 n = len(segments) - 1
171 while i < n:
172 if (segments[i] == '..'
173 and segments[i-1] not in ('', '..')):
174 del segments[i-1:i+1]
175 break
176 i = i+1
177 else:
178 break
179 if segments == ['', '..']:
180 segments[-1] = ''
181 elif len(segments) >= 2 and segments[-1] == '..':
182 segments[-2:] = ['']
183 return urlunparse((scheme, netloc, '/'.join(segments),
184 params, query, fragment))
186 def urldefrag(url):
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
191 empty string.
193 if '#' in url:
194 s, n, p, a, q, frag = urlparse(url)
195 defrag = urlunparse((s, n, p, a, q, ''))
196 return defrag, frag
197 else:
198 return url, ''
201 test_input = """
202 http://a/b/c/d
204 g:h = <URL:g:h>
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>
211 //g = <URL:http://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>
235 def test():
236 import sys
237 base = ''
238 if sys.argv[1:]:
239 fn = sys.argv[1]
240 if fn == '-':
241 fp = sys.stdin
242 else:
243 fp = open(fn)
244 else:
245 import StringIO
246 fp = StringIO.StringIO(test_input)
247 while 1:
248 line = fp.readline()
249 if not line: break
250 words = line.split()
251 if not words:
252 continue
253 url = words[0]
254 parts = urlparse(url)
255 print '%-10s : %s' % (url, parts)
256 abs = urljoin(base, url)
257 if not base:
258 base = abs
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__':
266 test()