| 1 |
"""Parse (absolute and relative) URLs. |
| 2 |
|
| 3 |
urlparse module is based upon the following RFC specifications. |
| 4 |
|
| 5 |
RFC 3986 (STD66): "Uniform Resource Identifiers" by T. Berners-Lee, R. Fielding |
| 6 |
and L. Masinter, January 2005. |
| 7 |
|
| 8 |
RFC 2732 : "Format for Literal IPv6 Addresses in URL's by R.Hinden, B.Carpenter |
| 9 |
and L.Masinter, December 1999. |
| 10 |
|
| 11 |
RFC 2396: "Uniform Resource Identifiers (URI)": Generic Syntax by T. |
| 12 |
Berners-Lee, R. Fielding, and L. Masinter, August 1998. |
| 13 |
|
| 14 |
RFC 2368: "The mailto URL scheme", by P.Hoffman , L Masinter, J. Zwinski, July 1998. |
| 15 |
|
| 16 |
RFC 1808: "Relative Uniform Resource Locators", by R. Fielding, UC Irvine, June |
| 17 |
1995. |
| 18 |
|
| 19 |
RFC 1738: "Uniform Resource Locators (URL)" by T. Berners-Lee, L. Masinter, M. |
| 20 |
McCahill, December 1994 |
| 21 |
|
| 22 |
RFC 3986 is considered the current standard and any future changes to |
| 23 |
urlparse module should conform with it. The urlparse module is |
| 24 |
currently not entirely compliant with this RFC due to defacto |
| 25 |
scenarios for parsing, and for backward compatibility purposes, some |
| 26 |
parsing quirks from older RFCs are retained. The testcases in |
| 27 |
test_urlparse.py provides a good indicator of parsing behavior. |
| 28 |
|
| 29 |
""" |
| 30 |
|
| 31 |
import re |
| 32 |
|
| 33 |
__all__ = ["urlparse", "urlunparse", "urljoin", "urldefrag", |
| 34 |
"urlsplit", "urlunsplit", "parse_qs", "parse_qsl"] |
| 35 |
|
| 36 |
|
| 37 |
uses_relative = ['ftp', 'http', 'gopher', 'nntp', 'imap', |
| 38 |
'wais', 'file', 'https', 'shttp', 'mms', |
| 39 |
'prospero', 'rtsp', 'rtspu', '', 'sftp', |
| 40 |
'svn', 'svn+ssh'] |
| 41 |
uses_netloc = ['ftp', 'http', 'gopher', 'nntp', 'telnet', |
| 42 |
'imap', 'wais', 'file', 'mms', 'https', 'shttp', |
| 43 |
'snews', 'prospero', 'rtsp', 'rtspu', 'rsync', '', |
| 44 |
'svn', 'svn+ssh', 'sftp','nfs','git', 'git+ssh'] |
| 45 |
uses_params = ['ftp', 'hdl', 'prospero', 'http', 'imap', |
| 46 |
'https', 'shttp', 'rtsp', 'rtspu', 'sip', 'sips', |
| 47 |
'mms', '', 'sftp', 'tel'] |
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
non_hierarchical = ['gopher', 'hdl', 'mailto', 'news', |
| 52 |
'telnet', 'wais', 'imap', 'snews', 'sip', 'sips'] |
| 53 |
uses_query = ['http', 'wais', 'imap', 'https', 'shttp', 'mms', |
| 54 |
'gopher', 'rtsp', 'rtspu', 'sip', 'sips', ''] |
| 55 |
uses_fragment = ['ftp', 'hdl', 'http', 'gopher', 'news', |
| 56 |
'nntp', 'wais', 'https', 'shttp', 'snews', |
| 57 |
'file', 'prospero', ''] |
| 58 |
|
| 59 |
|
| 60 |
scheme_chars = ('abcdefghijklmnopqrstuvwxyz' |
| 61 |
'ABCDEFGHIJKLMNOPQRSTUVWXYZ' |
| 62 |
'0123456789' |
| 63 |
'+-.') |
| 64 |
|
| 65 |
MAX_CACHE_SIZE = 20 |
| 66 |
_parse_cache = {} |
| 67 |
|
| 68 |
def clear_cache(): |
| 69 |
"""Clear the parse cache.""" |
| 70 |
_parse_cache.clear() |
| 71 |
|
| 72 |
|
| 73 |
class ResultMixin(object): |
| 74 |
"""Shared methods for the parsed result objects.""" |
| 75 |
|
| 76 |
@property |
| 77 |
def username(self): |
| 78 |
netloc = self.netloc |
| 79 |
if "@" in netloc: |
| 80 |
userinfo = netloc.rsplit("@", 1)[0] |
| 81 |
if ":" in userinfo: |
| 82 |
userinfo = userinfo.split(":", 1)[0] |
| 83 |
return userinfo |
| 84 |
return None |
| 85 |
|
| 86 |
@property |
| 87 |
def password(self): |
| 88 |
netloc = self.netloc |
| 89 |
if "@" in netloc: |
| 90 |
userinfo = netloc.rsplit("@", 1)[0] |
| 91 |
if ":" in userinfo: |
| 92 |
return userinfo.split(":", 1)[1] |
| 93 |
return None |
| 94 |
|
| 95 |
@property |
| 96 |
def hostname(self): |
| 97 |
netloc = self.netloc.split('@')[-1] |
| 98 |
if '[' in netloc and ']' in netloc: |
| 99 |
return netloc.split(']')[0][1:].lower() |
| 100 |
elif ':' in netloc: |
| 101 |
return netloc.split(':')[0].lower() |
| 102 |
elif netloc == '': |
| 103 |
return None |
| 104 |
else: |
| 105 |
return netloc.lower() |
| 106 |
|
| 107 |
@property |
| 108 |
def port(self): |
| 109 |
netloc = self.netloc.split('@')[-1].split(']')[-1] |
| 110 |
if ':' in netloc: |
| 111 |
port = netloc.split(':')[1] |
| 112 |
if port: |
| 113 |
port = int(port, 10) |
| 114 |
|
| 115 |
if (0 <= port <= 65535): |
| 116 |
return port |
| 117 |
return None |
| 118 |
|
| 119 |
from collections import namedtuple |
| 120 |
|
| 121 |
class SplitResult(namedtuple('SplitResult', 'scheme netloc path query fragment'), ResultMixin): |
| 122 |
|
| 123 |
__slots__ = () |
| 124 |
|
| 125 |
def geturl(self): |
| 126 |
return urlunsplit(self) |
| 127 |
|
| 128 |
|
| 129 |
class ParseResult(namedtuple('ParseResult', 'scheme netloc path params query fragment'), ResultMixin): |
| 130 |
|
| 131 |
__slots__ = () |
| 132 |
|
| 133 |
def geturl(self): |
| 134 |
return urlunparse(self) |
| 135 |
|
| 136 |
|
| 137 |
def urlparse(url, scheme='', allow_fragments=True): |
| 138 |
"""Parse a URL into 6 components: |
| 139 |
<scheme>://<netloc>/<path>;<params>?<query>#<fragment> |
| 140 |
Return a 6-tuple: (scheme, netloc, path, params, query, fragment). |
| 141 |
Note that we don't break the components up in smaller bits |
| 142 |
(e.g. netloc is a single string) and we don't expand % escapes.""" |
| 143 |
tuple = urlsplit(url, scheme, allow_fragments) |
| 144 |
scheme, netloc, url, query, fragment = tuple |
| 145 |
if scheme in uses_params and ';' in url: |
| 146 |
url, params = _splitparams(url) |
| 147 |
else: |
| 148 |
params = '' |
| 149 |
return ParseResult(scheme, netloc, url, params, query, fragment) |
| 150 |
|
| 151 |
def _splitparams(url): |
| 152 |
if '/' in url: |
| 153 |
i = url.find(';', url.rfind('/')) |
| 154 |
if i < 0: |
| 155 |
return url, '' |
| 156 |
else: |
| 157 |
i = url.find(';') |
| 158 |
return url[:i], url[i+1:] |
| 159 |
|
| 160 |
def _splitnetloc(url, start=0): |
| 161 |
delim = len(url) |
| 162 |
for c in '/?#': |
| 163 |
wdelim = url.find(c, start) |
| 164 |
if wdelim >= 0: |
| 165 |
delim = min(delim, wdelim) |
| 166 |
return url[start:delim], url[delim:] |
| 167 |
|
| 168 |
def _checknetloc(netloc): |
| 169 |
if not netloc or not isinstance(netloc, unicode): |
| 170 |
return |
| 171 |
|
| 172 |
|
| 173 |
import unicodedata |
| 174 |
n = netloc.replace(u'@', u'') |
| 175 |
n = n.replace(u':', u'') |
| 176 |
n = n.replace(u'#', u'') |
| 177 |
n = n.replace(u'?', u'') |
| 178 |
netloc2 = unicodedata.normalize('NFKC', n) |
| 179 |
if n == netloc2: |
| 180 |
return |
| 181 |
for c in '/?#@:': |
| 182 |
if c in netloc2: |
| 183 |
raise ValueError("netloc %r contains invalid characters " |
| 184 |
"under NFKC normalization" |
| 185 |
% netloc) |
| 186 |
|
| 187 |
def urlsplit(url, scheme='', allow_fragments=True): |
| 188 |
"""Parse a URL into 5 components: |
| 189 |
<scheme>://<netloc>/<path>?<query>#<fragment> |
| 190 |
Return a 5-tuple: (scheme, netloc, path, query, fragment). |
| 191 |
Note that we don't break the components up in smaller bits |
| 192 |
(e.g. netloc is a single string) and we don't expand % escapes.""" |
| 193 |
allow_fragments = bool(allow_fragments) |
| 194 |
key = url, scheme, allow_fragments, type(url), type(scheme) |
| 195 |
cached = _parse_cache.get(key, None) |
| 196 |
if cached: |
| 197 |
return cached |
| 198 |
if len(_parse_cache) >= MAX_CACHE_SIZE: |
| 199 |
clear_cache() |
| 200 |
netloc = query = fragment = '' |
| 201 |
i = url.find(':') |
| 202 |
if i > 0: |
| 203 |
if url[:i] == 'http': |
| 204 |
scheme = url[:i].lower() |
| 205 |
url = url[i+1:] |
| 206 |
if url[:2] == '//': |
| 207 |
netloc, url = _splitnetloc(url, 2) |
| 208 |
if (('[' in netloc and ']' not in netloc) or |
| 209 |
(']' in netloc and '[' not in netloc)): |
| 210 |
raise ValueError("Invalid IPv6 URL") |
| 211 |
if allow_fragments and '#' in url: |
| 212 |
url, fragment = url.split('#', 1) |
| 213 |
if '?' in url: |
| 214 |
url, query = url.split('?', 1) |
| 215 |
_checknetloc(netloc) |
| 216 |
v = SplitResult(scheme, netloc, url, query, fragment) |
| 217 |
_parse_cache[key] = v |
| 218 |
return v |
| 219 |
for c in url[:i]: |
| 220 |
if c not in scheme_chars: |
| 221 |
break |
| 222 |
else: |
| 223 |
|
| 224 |
|
| 225 |
rest = url[i+1:] |
| 226 |
if not rest or any(c not in '0123456789' for c in rest): |
| 227 |
|
| 228 |
scheme, url = url[:i].lower(), rest |
| 229 |
|
| 230 |
if url[:2] == '//': |
| 231 |
netloc, url = _splitnetloc(url, 2) |
| 232 |
if (('[' in netloc and ']' not in netloc) or |
| 233 |
(']' in netloc and '[' not in netloc)): |
| 234 |
raise ValueError("Invalid IPv6 URL") |
| 235 |
if allow_fragments and '#' in url: |
| 236 |
url, fragment = url.split('#', 1) |
| 237 |
if '?' in url: |
| 238 |
url, query = url.split('?', 1) |
| 239 |
_checknetloc(netloc) |
| 240 |
v = SplitResult(scheme, netloc, url, query, fragment) |
| 241 |
_parse_cache[key] = v |
| 242 |
return v |
| 243 |
|
| 244 |
def urlunparse(data): |
| 245 |
"""Put a parsed URL back together again. This may result in a |
| 246 |
slightly different, but equivalent URL, if the URL that was parsed |
| 247 |
originally had redundant delimiters, e.g. a ? with an empty query |
| 248 |
(the draft states that these are equivalent).""" |
| 249 |
scheme, netloc, url, params, query, fragment = data |
| 250 |
if params: |
| 251 |
url = "%s;%s" % (url, params) |
| 252 |
return urlunsplit((scheme, netloc, url, query, fragment)) |
| 253 |
|
| 254 |
def urlunsplit(data): |
| 255 |
"""Combine the elements of a tuple as returned by urlsplit() into a |
| 256 |
complete URL as a string. The data argument can be any five-item iterable. |
| 257 |
This may result in a slightly different, but equivalent URL, if the URL that |
| 258 |
was parsed originally had unnecessary delimiters (for example, a ? with an |
| 259 |
empty query; the RFC states that these are equivalent).""" |
| 260 |
scheme, netloc, url, query, fragment = data |
| 261 |
if netloc or (scheme and scheme in uses_netloc and url[:2] != '//'): |
| 262 |
if url and url[:1] != '/': url = '/' + url |
| 263 |
url = '//' + (netloc or '') + url |
| 264 |
if scheme: |
| 265 |
url = scheme + ':' + url |
| 266 |
if query: |
| 267 |
url = url + '?' + query |
| 268 |
if fragment: |
| 269 |
url = url + '#' + fragment |
| 270 |
return url |
| 271 |
|
| 272 |
def urljoin(base, url, allow_fragments=True): |
| 273 |
"""Join a base URL and a possibly relative URL to form an absolute |
| 274 |
interpretation of the latter.""" |
| 275 |
if not base: |
| 276 |
return url |
| 277 |
if not url: |
| 278 |
return base |
| 279 |
bscheme, bnetloc, bpath, bparams, bquery, bfragment = \ |
| 280 |
urlparse(base, '', allow_fragments) |
| 281 |
scheme, netloc, path, params, query, fragment = \ |
| 282 |
urlparse(url, bscheme, allow_fragments) |
| 283 |
if scheme != bscheme or scheme not in uses_relative: |
| 284 |
return url |
| 285 |
if scheme in uses_netloc: |
| 286 |
if netloc: |
| 287 |
return urlunparse((scheme, netloc, path, |
| 288 |
params, query, fragment)) |
| 289 |
netloc = bnetloc |
| 290 |
if path[:1] == '/': |
| 291 |
return urlunparse((scheme, netloc, path, |
| 292 |
params, query, fragment)) |
| 293 |
if not path and not params: |
| 294 |
path = bpath |
| 295 |
params = bparams |
| 296 |
if not query: |
| 297 |
query = bquery |
| 298 |
return urlunparse((scheme, netloc, path, |
| 299 |
params, query, fragment)) |
| 300 |
segments = bpath.split('/')[:-1] + path.split('/') |
| 301 |
|
| 302 |
if segments[-1] == '.': |
| 303 |
segments[-1] = '' |
| 304 |
while '.' in segments: |
| 305 |
segments.remove('.') |
| 306 |
while 1: |
| 307 |
i = 1 |
| 308 |
n = len(segments) - 1 |
| 309 |
while i < n: |
| 310 |
if (segments[i] == '..' |
| 311 |
and segments[i-1] not in ('', '..')): |
| 312 |
del segments[i-1:i+1] |
| 313 |
break |
| 314 |
i = i+1 |
| 315 |
else: |
| 316 |
break |
| 317 |
if segments == ['', '..']: |
| 318 |
segments[-1] = '' |
| 319 |
elif len(segments) >= 2 and segments[-1] == '..': |
| 320 |
segments[-2:] = [''] |
| 321 |
return urlunparse((scheme, netloc, '/'.join(segments), |
| 322 |
params, query, fragment)) |
| 323 |
|
| 324 |
def urldefrag(url): |
| 325 |
"""Removes any existing fragment from URL. |
| 326 |
|
| 327 |
Returns a tuple of the defragmented URL and the fragment. If |
| 328 |
the URL contained no fragments, the second element is the |
| 329 |
empty string. |
| 330 |
""" |
| 331 |
if '#' in url: |
| 332 |
s, n, p, a, q, frag = urlparse(url) |
| 333 |
defrag = urlunparse((s, n, p, a, q, '')) |
| 334 |
return defrag, frag |
| 335 |
else: |
| 336 |
return url, '' |
| 337 |
|
| 338 |
try: |
| 339 |
unicode |
| 340 |
except NameError: |
| 341 |
def _is_unicode(x): |
| 342 |
return 0 |
| 343 |
else: |
| 344 |
def _is_unicode(x): |
| 345 |
return isinstance(x, unicode) |
| 346 |
|
| 347 |
|
| 348 |
|
| 349 |
|
| 350 |
|
| 351 |
|
| 352 |
_hexdig = '0123456789ABCDEFabcdef' |
| 353 |
_hextochr = dict((a+b, chr(int(a+b,16))) |
| 354 |
for a in _hexdig for b in _hexdig) |
| 355 |
_asciire = re.compile('([\x00-\x7f]+)') |
| 356 |
|
| 357 |
def unquote(s): |
| 358 |
"""unquote('abc%20def') -> 'abc def'.""" |
| 359 |
if _is_unicode(s): |
| 360 |
if '%' not in s: |
| 361 |
return s |
| 362 |
bits = _asciire.split(s) |
| 363 |
res = [bits[0]] |
| 364 |
append = res.append |
| 365 |
for i in range(1, len(bits), 2): |
| 366 |
append(unquote(str(bits[i])).decode('latin1')) |
| 367 |
append(bits[i + 1]) |
| 368 |
return ''.join(res) |
| 369 |
|
| 370 |
bits = s.split('%') |
| 371 |
|
| 372 |
if len(bits) == 1: |
| 373 |
return s |
| 374 |
res = [bits[0]] |
| 375 |
append = res.append |
| 376 |
for item in bits[1:]: |
| 377 |
try: |
| 378 |
append(_hextochr[item[:2]]) |
| 379 |
append(item[2:]) |
| 380 |
except KeyError: |
| 381 |
append('%') |
| 382 |
append(item) |
| 383 |
return ''.join(res) |
| 384 |
|
| 385 |
def parse_qs(qs, keep_blank_values=0, strict_parsing=0, max_num_fields=None): |
| 386 |
"""Parse a query given as a string argument. |
| 387 |
|
| 388 |
Arguments: |
| 389 |
|
| 390 |
qs: percent-encoded query string to be parsed |
| 391 |
|
| 392 |
keep_blank_values: flag indicating whether blank values in |
| 393 |
percent-encoded queries should be treated as blank strings. |
| 394 |
A true value indicates that blanks should be retained as |
| 395 |
blank strings. The default false value indicates that |
| 396 |
blank values are to be ignored and treated as if they were |
| 397 |
not included. |
| 398 |
|
| 399 |
strict_parsing: flag indicating what to do with parsing errors. |
| 400 |
If false (the default), errors are silently ignored. |
| 401 |
If true, errors raise a ValueError exception. |
| 402 |
|
| 403 |
max_num_fields: int. If set, then throws a ValueError if there |
| 404 |
are more than n fields read by parse_qsl(). |
| 405 |
""" |
| 406 |
dict = {} |
| 407 |
for name, value in parse_qsl(qs, keep_blank_values, strict_parsing, |
| 408 |
max_num_fields): |
| 409 |
if name in dict: |
| 410 |
dict[name].append(value) |
| 411 |
else: |
| 412 |
dict[name] = [value] |
| 413 |
return dict |
| 414 |
|
| 415 |
def parse_qsl(qs, keep_blank_values=0, strict_parsing=0, max_num_fields=None): |
| 416 |
"""Parse a query given as a string argument. |
| 417 |
|
| 418 |
Arguments: |
| 419 |
|
| 420 |
qs: percent-encoded query string to be parsed |
| 421 |
|
| 422 |
keep_blank_values: flag indicating whether blank values in |
| 423 |
percent-encoded queries should be treated as blank strings. A |
| 424 |
true value indicates that blanks should be retained as blank |
| 425 |
strings. The default false value indicates that blank values |
| 426 |
are to be ignored and treated as if they were not included. |
| 427 |
|
| 428 |
strict_parsing: flag indicating what to do with parsing errors. If |
| 429 |
false (the default), errors are silently ignored. If true, |
| 430 |
errors raise a ValueError exception. |
| 431 |
|
| 432 |
max_num_fields: int. If set, then throws a ValueError if there |
| 433 |
are more than n fields read by parse_qsl(). |
| 434 |
|
| 435 |
Returns a list, as G-d intended. |
| 436 |
""" |
| 437 |
|
| 438 |
|
| 439 |
|
| 440 |
if max_num_fields is not None: |
| 441 |
num_fields = 1 + qs.count('&') + qs.count(';') |
| 442 |
if max_num_fields < num_fields: |
| 443 |
raise ValueError('Max number of fields exceeded') |
| 444 |
|
| 445 |
pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')] |
| 446 |
r = [] |
| 447 |
for name_value in pairs: |
| 448 |
if not name_value and not strict_parsing: |
| 449 |
continue |
| 450 |
nv = name_value.split('=', 1) |
| 451 |
if len(nv) != 2: |
| 452 |
if strict_parsing: |
| 453 |
raise ValueError, "bad query field: %r" % (name_value,) |
| 454 |
|
| 455 |
if keep_blank_values: |
| 456 |
nv.append('') |
| 457 |
else: |
| 458 |
continue |
| 459 |
if len(nv[1]) or keep_blank_values: |
| 460 |
name = unquote(nv[0].replace('+', ' ')) |
| 461 |
value = unquote(nv[1].replace('+', ' ')) |
| 462 |
r.append((name, value)) |
| 463 |
|
| 464 |
return r |