Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 1 | """Open an arbitrary URL. |
| 2 | |
| 3 | See the following document for more info on URLs: |
| 4 | "Names and Addresses, URIs, URLs, URNs, URCs", at |
| 5 | http://www.w3.org/pub/WWW/Addressing/Overview.html |
| 6 | |
| 7 | See also the HTTP spec (from which the error codes are derived): |
| 8 | "HTTP - Hypertext Transfer Protocol", at |
| 9 | http://www.w3.org/pub/WWW/Protocols/ |
| 10 | |
| 11 | Related standards and specs: |
| 12 | - RFC1808: the "relative URL" spec. (authoritative status) |
| 13 | - RFC1738 - the "URL standard". (authoritative status) |
| 14 | - RFC1630 - the "URI spec". (informational status) |
| 15 | |
| 16 | The object returned by URLopener().open(file) will differ per |
| 17 | protocol. All you know is that is has methods read(), readline(), |
| 18 | readlines(), fileno(), close() and info(). The read*(), fileno() |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 19 | and close() methods work like those of open files. |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 20 | The info() method returns a mimetools.Message object which can be |
| 21 | used to query various info about the object, if available. |
| 22 | (mimetools.Message objects are queried with the getheader() method.) |
| 23 | """ |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 24 | |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 25 | import string |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 26 | import socket |
Jack Jansen | dc3e3f6 | 1995-12-15 13:22:13 +0000 | [diff] [blame] | 27 | import os |
Guido van Rossum | f0713d3 | 2001-08-09 17:43:35 +0000 | [diff] [blame] | 28 | import time |
Guido van Rossum | 3c8484e | 1996-11-20 22:02:24 +0000 | [diff] [blame] | 29 | import sys |
Brett Cannon | 69200fa | 2004-03-23 21:26:39 +0000 | [diff] [blame] | 30 | from urlparse import urljoin as basejoin |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 31 | |
Skip Montanaro | 40fc160 | 2001-03-01 04:27:19 +0000 | [diff] [blame] | 32 | __all__ = ["urlopen", "URLopener", "FancyURLopener", "urlretrieve", |
| 33 | "urlcleanup", "quote", "quote_plus", "unquote", "unquote_plus", |
Skip Montanaro | 44d5e0c | 2001-03-13 19:47:16 +0000 | [diff] [blame] | 34 | "urlencode", "url2pathname", "pathname2url", "splittag", |
| 35 | "localhost", "thishost", "ftperrors", "basejoin", "unwrap", |
| 36 | "splittype", "splithost", "splituser", "splitpasswd", "splitport", |
| 37 | "splitnport", "splitquery", "splitattr", "splitvalue", |
| 38 | "splitgophertype", "getproxies"] |
Skip Montanaro | 40fc160 | 2001-03-01 04:27:19 +0000 | [diff] [blame] | 39 | |
Brett Cannon | 69200fa | 2004-03-23 21:26:39 +0000 | [diff] [blame] | 40 | __version__ = '1.16' # XXX This version is not always updated :-( |
Guido van Rossum | f668d17 | 1997-06-06 21:11:11 +0000 | [diff] [blame] | 41 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 42 | MAXFTPCACHE = 10 # Trim the ftp cache beyond this size |
Guido van Rossum | 6cb15a0 | 1995-06-22 19:00:13 +0000 | [diff] [blame] | 43 | |
Jack Jansen | dc3e3f6 | 1995-12-15 13:22:13 +0000 | [diff] [blame] | 44 | # Helper for non-unix systems |
| 45 | if os.name == 'mac': |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 46 | from macurl2path import url2pathname, pathname2url |
Guido van Rossum | 7e7ca0b | 1998-03-26 21:01:39 +0000 | [diff] [blame] | 47 | elif os.name == 'nt': |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 48 | from nturl2path import url2pathname, pathname2url |
Guido van Rossum | d74fb6b | 2001-03-02 06:43:49 +0000 | [diff] [blame] | 49 | elif os.name == 'riscos': |
| 50 | from rourl2path import url2pathname, pathname2url |
Jack Jansen | dc3e3f6 | 1995-12-15 13:22:13 +0000 | [diff] [blame] | 51 | else: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 52 | def url2pathname(pathname): |
Guido van Rossum | 367ac80 | 1999-03-12 14:31:10 +0000 | [diff] [blame] | 53 | return unquote(pathname) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 54 | def pathname2url(pathname): |
Guido van Rossum | 367ac80 | 1999-03-12 14:31:10 +0000 | [diff] [blame] | 55 | return quote(pathname) |
Guido van Rossum | 33add0a | 1998-12-18 15:25:22 +0000 | [diff] [blame] | 56 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 57 | # This really consists of two pieces: |
| 58 | # (1) a class which handles opening of all sorts of URLs |
| 59 | # (plus assorted utilities etc.) |
| 60 | # (2) a set of functions for parsing URLs |
| 61 | # XXX Should these be separated out into different modules? |
| 62 | |
| 63 | |
| 64 | # Shortcut for basic usage |
| 65 | _urlopener = None |
Fred Drake | df6eca7 | 2002-04-04 20:41:34 +0000 | [diff] [blame] | 66 | def urlopen(url, data=None, proxies=None): |
Skip Montanaro | 79f1c17 | 2000-08-22 03:00:52 +0000 | [diff] [blame] | 67 | """urlopen(url [, data]) -> open file-like object""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 68 | global _urlopener |
Fred Drake | df6eca7 | 2002-04-04 20:41:34 +0000 | [diff] [blame] | 69 | if proxies is not None: |
| 70 | opener = FancyURLopener(proxies=proxies) |
| 71 | elif not _urlopener: |
| 72 | opener = FancyURLopener() |
| 73 | _urlopener = opener |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 74 | else: |
Fred Drake | df6eca7 | 2002-04-04 20:41:34 +0000 | [diff] [blame] | 75 | opener = _urlopener |
| 76 | if data is None: |
| 77 | return opener.open(url) |
| 78 | else: |
| 79 | return opener.open(url, data) |
Fred Drake | 316a793 | 2000-08-24 01:01:26 +0000 | [diff] [blame] | 80 | def urlretrieve(url, filename=None, reporthook=None, data=None): |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 81 | global _urlopener |
| 82 | if not _urlopener: |
| 83 | _urlopener = FancyURLopener() |
Fred Drake | 316a793 | 2000-08-24 01:01:26 +0000 | [diff] [blame] | 84 | return _urlopener.retrieve(url, filename, reporthook, data) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 85 | def urlcleanup(): |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 86 | if _urlopener: |
| 87 | _urlopener.cleanup() |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 88 | |
| 89 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 90 | ftpcache = {} |
| 91 | class URLopener: |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 92 | """Class to open URLs. |
| 93 | This is a class rather than just a subroutine because we may need |
| 94 | more than one set of global protocol-specific options. |
| 95 | Note -- this is a base class for those who don't want the |
| 96 | automatic handling of errors type 302 (relocated) and 401 |
| 97 | (authorization needed).""" |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 98 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 99 | __tempfiles = None |
Guido van Rossum | 29e7781 | 1996-11-27 19:39:58 +0000 | [diff] [blame] | 100 | |
Guido van Rossum | ba31138 | 2000-08-24 16:18:04 +0000 | [diff] [blame] | 101 | version = "Python-urllib/%s" % __version__ |
| 102 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 103 | # Constructor |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 104 | def __init__(self, proxies=None, **x509): |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 105 | if proxies is None: |
| 106 | proxies = getproxies() |
| 107 | assert hasattr(proxies, 'has_key'), "proxies must be a mapping" |
| 108 | self.proxies = proxies |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 109 | self.key_file = x509.get('key_file') |
| 110 | self.cert_file = x509.get('cert_file') |
Guido van Rossum | ba31138 | 2000-08-24 16:18:04 +0000 | [diff] [blame] | 111 | self.addheaders = [('User-agent', self.version)] |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 112 | self.__tempfiles = [] |
| 113 | self.__unlink = os.unlink # See cleanup() |
| 114 | self.tempcache = None |
| 115 | # Undocumented feature: if you assign {} to tempcache, |
| 116 | # it is used to cache files retrieved with |
| 117 | # self.retrieve(). This is not enabled by default |
| 118 | # since it does not work for changing documents (and I |
| 119 | # haven't got the logic to check expiration headers |
| 120 | # yet). |
| 121 | self.ftpcache = ftpcache |
| 122 | # Undocumented feature: you can use a different |
| 123 | # ftp cache by assigning to the .ftpcache member; |
| 124 | # in case you want logically independent URL openers |
| 125 | # XXX This is not threadsafe. Bah. |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 126 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 127 | def __del__(self): |
| 128 | self.close() |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 129 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 130 | def close(self): |
| 131 | self.cleanup() |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 132 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 133 | def cleanup(self): |
| 134 | # This code sometimes runs when the rest of this module |
| 135 | # has already been deleted, so it can't use any globals |
| 136 | # or import anything. |
| 137 | if self.__tempfiles: |
| 138 | for file in self.__tempfiles: |
| 139 | try: |
| 140 | self.__unlink(file) |
Martin v. Löwis | 58682b7 | 2001-08-11 15:02:57 +0000 | [diff] [blame] | 141 | except OSError: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 142 | pass |
| 143 | del self.__tempfiles[:] |
| 144 | if self.tempcache: |
| 145 | self.tempcache.clear() |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 146 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 147 | def addheader(self, *args): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 148 | """Add a header to be used by the HTTP interface only |
| 149 | e.g. u.addheader('Accept', 'sound/basic')""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 150 | self.addheaders.append(args) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 151 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 152 | # External interface |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 153 | def open(self, fullurl, data=None): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 154 | """Use URLopener().open(file) instead of open(file, 'r').""" |
Martin v. Löwis | 1d99433 | 2000-12-03 18:30:10 +0000 | [diff] [blame] | 155 | fullurl = unwrap(toBytes(fullurl)) |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 156 | if self.tempcache and fullurl in self.tempcache: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 157 | filename, headers = self.tempcache[fullurl] |
| 158 | fp = open(filename, 'rb') |
| 159 | return addinfourl(fp, headers, fullurl) |
Martin v. Löwis | 1d99433 | 2000-12-03 18:30:10 +0000 | [diff] [blame] | 160 | urltype, url = splittype(fullurl) |
| 161 | if not urltype: |
| 162 | urltype = 'file' |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 163 | if urltype in self.proxies: |
Martin v. Löwis | 1d99433 | 2000-12-03 18:30:10 +0000 | [diff] [blame] | 164 | proxy = self.proxies[urltype] |
| 165 | urltype, proxyhost = splittype(proxy) |
Jeremy Hylton | d52755f | 2000-10-02 23:04:02 +0000 | [diff] [blame] | 166 | host, selector = splithost(proxyhost) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 167 | url = (host, fullurl) # Signal special case to open_*() |
Jeremy Hylton | d52755f | 2000-10-02 23:04:02 +0000 | [diff] [blame] | 168 | else: |
| 169 | proxy = None |
Martin v. Löwis | 1d99433 | 2000-12-03 18:30:10 +0000 | [diff] [blame] | 170 | name = 'open_' + urltype |
| 171 | self.type = urltype |
Brett Cannon | aaeffaf | 2004-03-23 23:50:17 +0000 | [diff] [blame] | 172 | name = name.replace('-', '_') |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 173 | if not hasattr(self, name): |
Jeremy Hylton | d52755f | 2000-10-02 23:04:02 +0000 | [diff] [blame] | 174 | if proxy: |
| 175 | return self.open_unknown_proxy(proxy, fullurl, data) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 176 | else: |
| 177 | return self.open_unknown(fullurl, data) |
| 178 | try: |
| 179 | if data is None: |
| 180 | return getattr(self, name)(url) |
| 181 | else: |
| 182 | return getattr(self, name)(url, data) |
| 183 | except socket.error, msg: |
| 184 | raise IOError, ('socket error', msg), sys.exc_info()[2] |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 185 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 186 | def open_unknown(self, fullurl, data=None): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 187 | """Overridable interface to open unknown URL type.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 188 | type, url = splittype(fullurl) |
| 189 | raise IOError, ('url error', 'unknown url type', type) |
Guido van Rossum | ca44540 | 1995-08-29 19:19:12 +0000 | [diff] [blame] | 190 | |
Jeremy Hylton | d52755f | 2000-10-02 23:04:02 +0000 | [diff] [blame] | 191 | def open_unknown_proxy(self, proxy, fullurl, data=None): |
| 192 | """Overridable interface to open unknown URL type.""" |
| 193 | type, url = splittype(fullurl) |
| 194 | raise IOError, ('url error', 'invalid proxy for %s' % type, proxy) |
| 195 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 196 | # External interface |
Sjoerd Mullender | d7b86f0 | 2000-08-25 11:23:36 +0000 | [diff] [blame] | 197 | def retrieve(self, url, filename=None, reporthook=None, data=None): |
Brett Cannon | 7d618c7 | 2003-04-24 02:43:20 +0000 | [diff] [blame] | 198 | """retrieve(url) returns (filename, headers) for a local object |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 199 | or (tempfilename, headers) for a remote object.""" |
Martin v. Löwis | 1d99433 | 2000-12-03 18:30:10 +0000 | [diff] [blame] | 200 | url = unwrap(toBytes(url)) |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 201 | if self.tempcache and url in self.tempcache: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 202 | return self.tempcache[url] |
| 203 | type, url1 = splittype(url) |
Raymond Hettinger | 10ff706 | 2002-06-02 03:04:52 +0000 | [diff] [blame] | 204 | if filename is None and (not type or type == 'file'): |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 205 | try: |
| 206 | fp = self.open_local_file(url1) |
| 207 | hdrs = fp.info() |
| 208 | del fp |
| 209 | return url2pathname(splithost(url1)[1]), hdrs |
| 210 | except IOError, msg: |
| 211 | pass |
Fred Drake | 316a793 | 2000-08-24 01:01:26 +0000 | [diff] [blame] | 212 | fp = self.open(url, data) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 213 | headers = fp.info() |
Guido van Rossum | 3b0a329 | 2002-08-09 16:38:32 +0000 | [diff] [blame] | 214 | if filename: |
| 215 | tfp = open(filename, 'wb') |
| 216 | else: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 217 | import tempfile |
| 218 | garbage, path = splittype(url) |
| 219 | garbage, path = splithost(path or "") |
| 220 | path, garbage = splitquery(path or "") |
| 221 | path, garbage = splitattr(path or "") |
| 222 | suffix = os.path.splitext(path)[1] |
Guido van Rossum | 3b0a329 | 2002-08-09 16:38:32 +0000 | [diff] [blame] | 223 | (fd, filename) = tempfile.mkstemp(suffix) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 224 | self.__tempfiles.append(filename) |
Jeremy Hylton | 3bd6fde | 2002-10-11 14:36:24 +0000 | [diff] [blame] | 225 | tfp = os.fdopen(fd, 'wb') |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 226 | result = filename, headers |
| 227 | if self.tempcache is not None: |
| 228 | self.tempcache[url] = result |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 229 | bs = 1024*8 |
| 230 | size = -1 |
| 231 | blocknum = 1 |
| 232 | if reporthook: |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 233 | if "content-length" in headers: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 234 | size = int(headers["Content-Length"]) |
| 235 | reporthook(0, bs, size) |
| 236 | block = fp.read(bs) |
| 237 | if reporthook: |
| 238 | reporthook(1, bs, size) |
| 239 | while block: |
| 240 | tfp.write(block) |
| 241 | block = fp.read(bs) |
| 242 | blocknum = blocknum + 1 |
| 243 | if reporthook: |
| 244 | reporthook(blocknum, bs, size) |
| 245 | fp.close() |
| 246 | tfp.close() |
| 247 | del fp |
| 248 | del tfp |
| 249 | return result |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 250 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 251 | # Each method named open_<type> knows how to open that type of URL |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 252 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 253 | def open_http(self, url, data=None): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 254 | """Use HTTP protocol.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 255 | import httplib |
| 256 | user_passwd = None |
Walter Dörwald | 65230a2 | 2002-06-03 15:58:32 +0000 | [diff] [blame] | 257 | if isinstance(url, str): |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 258 | host, selector = splithost(url) |
| 259 | if host: |
| 260 | user_passwd, host = splituser(host) |
| 261 | host = unquote(host) |
| 262 | realhost = host |
| 263 | else: |
| 264 | host, selector = url |
| 265 | urltype, rest = splittype(selector) |
| 266 | url = rest |
| 267 | user_passwd = None |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 268 | if urltype.lower() != 'http': |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 269 | realhost = None |
| 270 | else: |
| 271 | realhost, rest = splithost(rest) |
| 272 | if realhost: |
| 273 | user_passwd, realhost = splituser(realhost) |
| 274 | if user_passwd: |
| 275 | selector = "%s://%s%s" % (urltype, realhost, rest) |
Tim Peters | 55c12d4 | 2001-08-09 18:04:14 +0000 | [diff] [blame] | 276 | if proxy_bypass(realhost): |
| 277 | host = realhost |
| 278 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 279 | #print "proxy via http:", host, selector |
| 280 | if not host: raise IOError, ('http error', 'no host given') |
| 281 | if user_passwd: |
| 282 | import base64 |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 283 | auth = base64.encodestring(user_passwd).strip() |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 284 | else: |
| 285 | auth = None |
| 286 | h = httplib.HTTP(host) |
| 287 | if data is not None: |
| 288 | h.putrequest('POST', selector) |
| 289 | h.putheader('Content-type', 'application/x-www-form-urlencoded') |
| 290 | h.putheader('Content-length', '%d' % len(data)) |
| 291 | else: |
| 292 | h.putrequest('GET', selector) |
| 293 | if auth: h.putheader('Authorization', 'Basic %s' % auth) |
| 294 | if realhost: h.putheader('Host', realhost) |
Guido van Rossum | 68468eb | 2003-02-27 20:14:51 +0000 | [diff] [blame] | 295 | for args in self.addheaders: h.putheader(*args) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 296 | h.endheaders() |
| 297 | if data is not None: |
Fred Drake | ec3dfde | 2001-07-04 05:18:29 +0000 | [diff] [blame] | 298 | h.send(data) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 299 | errcode, errmsg, headers = h.getreply() |
| 300 | fp = h.getfile() |
| 301 | if errcode == 200: |
| 302 | return addinfourl(fp, headers, "http:" + url) |
| 303 | else: |
| 304 | if data is None: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 305 | return self.http_error(url, fp, errcode, errmsg, headers) |
Guido van Rossum | 29aab75 | 1999-03-09 19:31:21 +0000 | [diff] [blame] | 306 | else: |
| 307 | return self.http_error(url, fp, errcode, errmsg, headers, data) |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 308 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 309 | def http_error(self, url, fp, errcode, errmsg, headers, data=None): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 310 | """Handle http errors. |
| 311 | Derived class can override this, or provide specific handlers |
| 312 | named http_error_DDD where DDD is the 3-digit error code.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 313 | # First check if there's a specific handler for this error |
| 314 | name = 'http_error_%d' % errcode |
| 315 | if hasattr(self, name): |
| 316 | method = getattr(self, name) |
| 317 | if data is None: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 318 | result = method(url, fp, errcode, errmsg, headers) |
Jeremy Hylton | b30f52a | 1999-02-25 16:14:58 +0000 | [diff] [blame] | 319 | else: |
| 320 | result = method(url, fp, errcode, errmsg, headers, data) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 321 | if result: return result |
Jeremy Hylton | b30f52a | 1999-02-25 16:14:58 +0000 | [diff] [blame] | 322 | return self.http_error_default(url, fp, errcode, errmsg, headers) |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 323 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 324 | def http_error_default(self, url, fp, errcode, errmsg, headers): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 325 | """Default error handler: close the connection and raise IOError.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 326 | void = fp.read() |
| 327 | fp.close() |
| 328 | raise IOError, ('http error', errcode, errmsg, headers) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 329 | |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 330 | if hasattr(socket, "ssl"): |
Andrew M. Kuchling | 141e989 | 2000-04-23 02:53:11 +0000 | [diff] [blame] | 331 | def open_https(self, url, data=None): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 332 | """Use HTTPS protocol.""" |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 333 | import httplib |
Fred Drake | 567ca8e | 2000-08-21 21:42:42 +0000 | [diff] [blame] | 334 | user_passwd = None |
Walter Dörwald | 65230a2 | 2002-06-03 15:58:32 +0000 | [diff] [blame] | 335 | if isinstance(url, str): |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 336 | host, selector = splithost(url) |
Fred Drake | 567ca8e | 2000-08-21 21:42:42 +0000 | [diff] [blame] | 337 | if host: |
| 338 | user_passwd, host = splituser(host) |
| 339 | host = unquote(host) |
| 340 | realhost = host |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 341 | else: |
| 342 | host, selector = url |
| 343 | urltype, rest = splittype(selector) |
Fred Drake | 567ca8e | 2000-08-21 21:42:42 +0000 | [diff] [blame] | 344 | url = rest |
| 345 | user_passwd = None |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 346 | if urltype.lower() != 'https': |
Fred Drake | 567ca8e | 2000-08-21 21:42:42 +0000 | [diff] [blame] | 347 | realhost = None |
| 348 | else: |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 349 | realhost, rest = splithost(rest) |
Fred Drake | 567ca8e | 2000-08-21 21:42:42 +0000 | [diff] [blame] | 350 | if realhost: |
| 351 | user_passwd, realhost = splituser(realhost) |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 352 | if user_passwd: |
| 353 | selector = "%s://%s%s" % (urltype, realhost, rest) |
Andrew M. Kuchling | 7ad4792 | 2000-06-10 01:41:48 +0000 | [diff] [blame] | 354 | #print "proxy via https:", host, selector |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 355 | if not host: raise IOError, ('https error', 'no host given') |
| 356 | if user_passwd: |
| 357 | import base64 |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 358 | auth = base64.encodestring(user_passwd).strip() |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 359 | else: |
| 360 | auth = None |
| 361 | h = httplib.HTTPS(host, 0, |
| 362 | key_file=self.key_file, |
| 363 | cert_file=self.cert_file) |
Andrew M. Kuchling | 141e989 | 2000-04-23 02:53:11 +0000 | [diff] [blame] | 364 | if data is not None: |
| 365 | h.putrequest('POST', selector) |
| 366 | h.putheader('Content-type', |
| 367 | 'application/x-www-form-urlencoded') |
| 368 | h.putheader('Content-length', '%d' % len(data)) |
| 369 | else: |
| 370 | h.putrequest('GET', selector) |
Andrew M. Kuchling | ff638ea | 2003-08-29 18:12:23 +0000 | [diff] [blame] | 371 | if auth: h.putheader('Authorization', 'Basic %s' % auth) |
Fred Drake | 567ca8e | 2000-08-21 21:42:42 +0000 | [diff] [blame] | 372 | if realhost: h.putheader('Host', realhost) |
Guido van Rossum | 68468eb | 2003-02-27 20:14:51 +0000 | [diff] [blame] | 373 | for args in self.addheaders: h.putheader(*args) |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 374 | h.endheaders() |
Andrew M. Kuchling | 43c5af0 | 2000-04-24 14:17:06 +0000 | [diff] [blame] | 375 | if data is not None: |
Fred Drake | ec3dfde | 2001-07-04 05:18:29 +0000 | [diff] [blame] | 376 | h.send(data) |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 377 | errcode, errmsg, headers = h.getreply() |
| 378 | fp = h.getfile() |
| 379 | if errcode == 200: |
Guido van Rossum | b931bf3 | 2001-12-08 17:09:07 +0000 | [diff] [blame] | 380 | return addinfourl(fp, headers, "https:" + url) |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 381 | else: |
Fred Drake | 567ca8e | 2000-08-21 21:42:42 +0000 | [diff] [blame] | 382 | if data is None: |
| 383 | return self.http_error(url, fp, errcode, errmsg, headers) |
| 384 | else: |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 385 | return self.http_error(url, fp, errcode, errmsg, headers, |
| 386 | data) |
Fred Drake | 567ca8e | 2000-08-21 21:42:42 +0000 | [diff] [blame] | 387 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 388 | def open_gopher(self, url): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 389 | """Use Gopher protocol.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 390 | import gopherlib |
| 391 | host, selector = splithost(url) |
| 392 | if not host: raise IOError, ('gopher error', 'no host given') |
| 393 | host = unquote(host) |
| 394 | type, selector = splitgophertype(selector) |
| 395 | selector, query = splitquery(selector) |
| 396 | selector = unquote(selector) |
| 397 | if query: |
| 398 | query = unquote(query) |
| 399 | fp = gopherlib.send_query(selector, query, host) |
| 400 | else: |
| 401 | fp = gopherlib.send_selector(selector, host) |
| 402 | return addinfourl(fp, noheaders(), "gopher:" + url) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 403 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 404 | def open_file(self, url): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 405 | """Use local file or FTP depending on form of URL.""" |
Jack Jansen | 4ef1103 | 2002-09-12 20:14:04 +0000 | [diff] [blame] | 406 | if url[:2] == '//' and url[2:3] != '/' and url[2:12].lower() != 'localhost/': |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 407 | return self.open_ftp(url) |
| 408 | else: |
| 409 | return self.open_local_file(url) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 410 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 411 | def open_local_file(self, url): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 412 | """Use local file.""" |
Jeremy Hylton | 6d8c1aa | 2001-08-27 20:16:53 +0000 | [diff] [blame] | 413 | import mimetypes, mimetools, rfc822, StringIO |
Guido van Rossum | f0713d3 | 2001-08-09 17:43:35 +0000 | [diff] [blame] | 414 | host, file = splithost(url) |
| 415 | localname = url2pathname(file) |
Guido van Rossum | a2da305 | 2002-04-15 00:25:01 +0000 | [diff] [blame] | 416 | try: |
| 417 | stats = os.stat(localname) |
| 418 | except OSError, e: |
| 419 | raise IOError(e.errno, e.strerror, e.filename) |
Walter Dörwald | 92b48b7 | 2002-03-22 17:30:38 +0000 | [diff] [blame] | 420 | size = stats.st_size |
| 421 | modified = rfc822.formatdate(stats.st_mtime) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 422 | mtype = mimetypes.guess_type(url)[0] |
| 423 | headers = mimetools.Message(StringIO.StringIO( |
Guido van Rossum | f0713d3 | 2001-08-09 17:43:35 +0000 | [diff] [blame] | 424 | 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' % |
| 425 | (mtype or 'text/plain', size, modified))) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 426 | if not host: |
Guido van Rossum | 336a201 | 1999-06-24 15:27:36 +0000 | [diff] [blame] | 427 | urlfile = file |
| 428 | if file[:1] == '/': |
| 429 | urlfile = 'file://' + file |
Guido van Rossum | f0713d3 | 2001-08-09 17:43:35 +0000 | [diff] [blame] | 430 | return addinfourl(open(localname, 'rb'), |
Guido van Rossum | 336a201 | 1999-06-24 15:27:36 +0000 | [diff] [blame] | 431 | headers, urlfile) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 432 | host, port = splitport(host) |
| 433 | if not port \ |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 434 | and socket.gethostbyname(host) in (localhost(), thishost()): |
Guido van Rossum | 336a201 | 1999-06-24 15:27:36 +0000 | [diff] [blame] | 435 | urlfile = file |
| 436 | if file[:1] == '/': |
| 437 | urlfile = 'file://' + file |
Guido van Rossum | f0713d3 | 2001-08-09 17:43:35 +0000 | [diff] [blame] | 438 | return addinfourl(open(localname, 'rb'), |
Guido van Rossum | 336a201 | 1999-06-24 15:27:36 +0000 | [diff] [blame] | 439 | headers, urlfile) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 440 | raise IOError, ('local file error', 'not on local host') |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 441 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 442 | def open_ftp(self, url): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 443 | """Use FTP protocol.""" |
Guido van Rossum | 88e0b5b | 2001-08-23 13:38:15 +0000 | [diff] [blame] | 444 | import mimetypes, mimetools, StringIO |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 445 | host, path = splithost(url) |
| 446 | if not host: raise IOError, ('ftp error', 'no host given') |
| 447 | host, port = splitport(host) |
| 448 | user, host = splituser(host) |
| 449 | if user: user, passwd = splitpasswd(user) |
| 450 | else: passwd = None |
| 451 | host = unquote(host) |
| 452 | user = unquote(user or '') |
| 453 | passwd = unquote(passwd or '') |
| 454 | host = socket.gethostbyname(host) |
| 455 | if not port: |
| 456 | import ftplib |
| 457 | port = ftplib.FTP_PORT |
| 458 | else: |
| 459 | port = int(port) |
| 460 | path, attrs = splitattr(path) |
| 461 | path = unquote(path) |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 462 | dirs = path.split('/') |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 463 | dirs, file = dirs[:-1], dirs[-1] |
| 464 | if dirs and not dirs[0]: dirs = dirs[1:] |
Guido van Rossum | 5e006a3 | 1999-08-18 17:40:33 +0000 | [diff] [blame] | 465 | if dirs and not dirs[0]: dirs[0] = '/' |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 466 | key = user, host, port, '/'.join(dirs) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 467 | # XXX thread unsafe! |
| 468 | if len(self.ftpcache) > MAXFTPCACHE: |
| 469 | # Prune the cache, rather arbitrarily |
| 470 | for k in self.ftpcache.keys(): |
| 471 | if k != key: |
| 472 | v = self.ftpcache[k] |
| 473 | del self.ftpcache[k] |
| 474 | v.close() |
| 475 | try: |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 476 | if not key in self.ftpcache: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 477 | self.ftpcache[key] = \ |
| 478 | ftpwrapper(user, passwd, host, port, dirs) |
| 479 | if not file: type = 'D' |
| 480 | else: type = 'I' |
| 481 | for attr in attrs: |
| 482 | attr, value = splitvalue(attr) |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 483 | if attr.lower() == 'type' and \ |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 484 | value in ('a', 'A', 'i', 'I', 'd', 'D'): |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 485 | type = value.upper() |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 486 | (fp, retrlen) = self.ftpcache[key].retrfile(file, type) |
Guido van Rossum | 88e0b5b | 2001-08-23 13:38:15 +0000 | [diff] [blame] | 487 | mtype = mimetypes.guess_type("ftp:" + url)[0] |
| 488 | headers = "" |
| 489 | if mtype: |
| 490 | headers += "Content-Type: %s\n" % mtype |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 491 | if retrlen is not None and retrlen >= 0: |
Guido van Rossum | 88e0b5b | 2001-08-23 13:38:15 +0000 | [diff] [blame] | 492 | headers += "Content-Length: %d\n" % retrlen |
| 493 | headers = mimetools.Message(StringIO.StringIO(headers)) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 494 | return addinfourl(fp, headers, "ftp:" + url) |
| 495 | except ftperrors(), msg: |
| 496 | raise IOError, ('ftp error', msg), sys.exc_info()[2] |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 497 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 498 | def open_data(self, url, data=None): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 499 | """Use "data" URL.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 500 | # ignore POSTed data |
| 501 | # |
| 502 | # syntax of data URLs: |
| 503 | # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data |
| 504 | # mediatype := [ type "/" subtype ] *( ";" parameter ) |
| 505 | # data := *urlchar |
| 506 | # parameter := attribute "=" value |
Neal Norwitz | aad1849 | 2002-03-26 16:25:01 +0000 | [diff] [blame] | 507 | import StringIO, mimetools |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 508 | try: |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 509 | [type, data] = url.split(',', 1) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 510 | except ValueError: |
| 511 | raise IOError, ('data error', 'bad data URL') |
| 512 | if not type: |
| 513 | type = 'text/plain;charset=US-ASCII' |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 514 | semi = type.rfind(';') |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 515 | if semi >= 0 and '=' not in type[semi:]: |
| 516 | encoding = type[semi+1:] |
| 517 | type = type[:semi] |
| 518 | else: |
| 519 | encoding = '' |
| 520 | msg = [] |
| 521 | msg.append('Date: %s'%time.strftime('%a, %d %b %Y %T GMT', |
| 522 | time.gmtime(time.time()))) |
| 523 | msg.append('Content-type: %s' % type) |
| 524 | if encoding == 'base64': |
| 525 | import base64 |
| 526 | data = base64.decodestring(data) |
| 527 | else: |
| 528 | data = unquote(data) |
| 529 | msg.append('Content-length: %d' % len(data)) |
| 530 | msg.append('') |
| 531 | msg.append(data) |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 532 | msg = '\n'.join(msg) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 533 | f = StringIO.StringIO(msg) |
| 534 | headers = mimetools.Message(f, 0) |
| 535 | f.fileno = None # needed for addinfourl |
| 536 | return addinfourl(f, headers, url) |
Guido van Rossum | 6d4d1c2 | 1998-03-12 14:32:55 +0000 | [diff] [blame] | 537 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 538 | |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 539 | class FancyURLopener(URLopener): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 540 | """Derived class with handlers for errors we can handle (perhaps).""" |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 541 | |
Neal Norwitz | 60e04cd | 2002-06-11 13:38:51 +0000 | [diff] [blame] | 542 | def __init__(self, *args, **kwargs): |
Guido van Rossum | 68468eb | 2003-02-27 20:14:51 +0000 | [diff] [blame] | 543 | URLopener.__init__(self, *args, **kwargs) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 544 | self.auth_cache = {} |
Skip Montanaro | c3e11d6 | 2001-02-15 16:56:36 +0000 | [diff] [blame] | 545 | self.tries = 0 |
| 546 | self.maxtries = 10 |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 547 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 548 | def http_error_default(self, url, fp, errcode, errmsg, headers): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 549 | """Default error handling -- don't raise an exception.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 550 | return addinfourl(fp, headers, "http:" + url) |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 551 | |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 552 | def http_error_302(self, url, fp, errcode, errmsg, headers, data=None): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 553 | """Error 302 -- relocated (temporarily).""" |
Skip Montanaro | c3e11d6 | 2001-02-15 16:56:36 +0000 | [diff] [blame] | 554 | self.tries += 1 |
| 555 | if self.maxtries and self.tries >= self.maxtries: |
| 556 | if hasattr(self, "http_error_500"): |
| 557 | meth = self.http_error_500 |
| 558 | else: |
| 559 | meth = self.http_error_default |
| 560 | self.tries = 0 |
| 561 | return meth(url, fp, 500, |
| 562 | "Internal Server Error: Redirect Recursion", headers) |
| 563 | result = self.redirect_internal(url, fp, errcode, errmsg, headers, |
| 564 | data) |
| 565 | self.tries = 0 |
| 566 | return result |
| 567 | |
| 568 | def redirect_internal(self, url, fp, errcode, errmsg, headers, data): |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 569 | if 'location' in headers: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 570 | newurl = headers['location'] |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 571 | elif 'uri' in headers: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 572 | newurl = headers['uri'] |
| 573 | else: |
| 574 | return |
| 575 | void = fp.read() |
| 576 | fp.close() |
Guido van Rossum | 3527f59 | 1999-03-29 20:23:41 +0000 | [diff] [blame] | 577 | # In case the server sent a relative URL, join with original: |
Moshe Zadka | 5d87d47 | 2001-04-09 14:54:21 +0000 | [diff] [blame] | 578 | newurl = basejoin(self.type + ":" + url, newurl) |
Guido van Rossum | fa19f7c | 2003-05-16 01:46:51 +0000 | [diff] [blame] | 579 | return self.open(newurl) |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 580 | |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 581 | def http_error_301(self, url, fp, errcode, errmsg, headers, data=None): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 582 | """Error 301 -- also relocated (permanently).""" |
| 583 | return self.http_error_302(url, fp, errcode, errmsg, headers, data) |
Guido van Rossum | e6ad891 | 1996-09-10 17:02:56 +0000 | [diff] [blame] | 584 | |
Raymond Hettinger | 024aaa1 | 2003-04-24 15:32:12 +0000 | [diff] [blame] | 585 | def http_error_303(self, url, fp, errcode, errmsg, headers, data=None): |
| 586 | """Error 303 -- also relocated (essentially identical to 302).""" |
| 587 | return self.http_error_302(url, fp, errcode, errmsg, headers, data) |
| 588 | |
Guido van Rossum | fa19f7c | 2003-05-16 01:46:51 +0000 | [diff] [blame] | 589 | def http_error_307(self, url, fp, errcode, errmsg, headers, data=None): |
| 590 | """Error 307 -- relocated, but turn POST into error.""" |
| 591 | if data is None: |
| 592 | return self.http_error_302(url, fp, errcode, errmsg, headers, data) |
| 593 | else: |
| 594 | return self.http_error_default(url, fp, errcode, errmsg, headers) |
| 595 | |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 596 | def http_error_401(self, url, fp, errcode, errmsg, headers, data=None): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 597 | """Error 401 -- authentication required. |
| 598 | See this URL for a description of the basic authentication scheme: |
| 599 | http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt""" |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 600 | if not 'www-authenticate' in headers: |
Tim Peters | 85ba673 | 2001-02-28 08:26:44 +0000 | [diff] [blame] | 601 | URLopener.http_error_default(self, url, fp, |
Fred Drake | c680ae8 | 2001-10-13 18:37:07 +0000 | [diff] [blame] | 602 | errcode, errmsg, headers) |
Moshe Zadka | e99bd17 | 2001-02-27 06:27:04 +0000 | [diff] [blame] | 603 | stuff = headers['www-authenticate'] |
| 604 | import re |
| 605 | match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff) |
| 606 | if not match: |
Tim Peters | 85ba673 | 2001-02-28 08:26:44 +0000 | [diff] [blame] | 607 | URLopener.http_error_default(self, url, fp, |
Moshe Zadka | e99bd17 | 2001-02-27 06:27:04 +0000 | [diff] [blame] | 608 | errcode, errmsg, headers) |
| 609 | scheme, realm = match.groups() |
| 610 | if scheme.lower() != 'basic': |
Tim Peters | 85ba673 | 2001-02-28 08:26:44 +0000 | [diff] [blame] | 611 | URLopener.http_error_default(self, url, fp, |
Moshe Zadka | e99bd17 | 2001-02-27 06:27:04 +0000 | [diff] [blame] | 612 | errcode, errmsg, headers) |
| 613 | name = 'retry_' + self.type + '_basic_auth' |
| 614 | if data is None: |
| 615 | return getattr(self,name)(url, realm) |
| 616 | else: |
| 617 | return getattr(self,name)(url, realm, data) |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 618 | |
Guido van Rossum | 3c8baed | 2000-02-01 23:36:55 +0000 | [diff] [blame] | 619 | def retry_http_basic_auth(self, url, realm, data=None): |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 620 | host, selector = splithost(url) |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 621 | i = host.find('@') + 1 |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 622 | host = host[i:] |
| 623 | user, passwd = self.get_user_passwd(host, realm, i) |
| 624 | if not (user or passwd): return None |
Guido van Rossum | afc4f04 | 2001-01-15 18:31:13 +0000 | [diff] [blame] | 625 | host = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + host |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 626 | newurl = 'http://' + host + selector |
Guido van Rossum | 3c8baed | 2000-02-01 23:36:55 +0000 | [diff] [blame] | 627 | if data is None: |
| 628 | return self.open(newurl) |
| 629 | else: |
| 630 | return self.open(newurl, data) |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 631 | |
Guido van Rossum | 3c8baed | 2000-02-01 23:36:55 +0000 | [diff] [blame] | 632 | def retry_https_basic_auth(self, url, realm, data=None): |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 633 | host, selector = splithost(url) |
| 634 | i = host.find('@') + 1 |
| 635 | host = host[i:] |
| 636 | user, passwd = self.get_user_passwd(host, realm, i) |
| 637 | if not (user or passwd): return None |
Guido van Rossum | afc4f04 | 2001-01-15 18:31:13 +0000 | [diff] [blame] | 638 | host = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + host |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 639 | newurl = '//' + host + selector |
Guido van Rossum | afc4f04 | 2001-01-15 18:31:13 +0000 | [diff] [blame] | 640 | return self.open_https(newurl, data) |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 641 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 642 | def get_user_passwd(self, host, realm, clear_cache = 0): |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 643 | key = realm + '@' + host.lower() |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 644 | if key in self.auth_cache: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 645 | if clear_cache: |
| 646 | del self.auth_cache[key] |
| 647 | else: |
| 648 | return self.auth_cache[key] |
| 649 | user, passwd = self.prompt_user_passwd(host, realm) |
| 650 | if user or passwd: self.auth_cache[key] = (user, passwd) |
| 651 | return user, passwd |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 652 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 653 | def prompt_user_passwd(self, host, realm): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 654 | """Override this in a GUI environment!""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 655 | import getpass |
| 656 | try: |
| 657 | user = raw_input("Enter username for %s at %s: " % (realm, |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 658 | host)) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 659 | passwd = getpass.getpass("Enter password for %s in %s at %s: " % |
| 660 | (user, realm, host)) |
| 661 | return user, passwd |
| 662 | except KeyboardInterrupt: |
| 663 | print |
| 664 | return None, None |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 665 | |
| 666 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 667 | # Utility functions |
| 668 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 669 | _localhost = None |
| 670 | def localhost(): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 671 | """Return the IP address of the magic hostname 'localhost'.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 672 | global _localhost |
Raymond Hettinger | 10ff706 | 2002-06-02 03:04:52 +0000 | [diff] [blame] | 673 | if _localhost is None: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 674 | _localhost = socket.gethostbyname('localhost') |
| 675 | return _localhost |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 676 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 677 | _thishost = None |
| 678 | def thishost(): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 679 | """Return the IP address of the current host.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 680 | global _thishost |
Raymond Hettinger | 10ff706 | 2002-06-02 03:04:52 +0000 | [diff] [blame] | 681 | if _thishost is None: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 682 | _thishost = socket.gethostbyname(socket.gethostname()) |
| 683 | return _thishost |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 684 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 685 | _ftperrors = None |
| 686 | def ftperrors(): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 687 | """Return the set of errors raised by the FTP class.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 688 | global _ftperrors |
Raymond Hettinger | 10ff706 | 2002-06-02 03:04:52 +0000 | [diff] [blame] | 689 | if _ftperrors is None: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 690 | import ftplib |
| 691 | _ftperrors = ftplib.all_errors |
| 692 | return _ftperrors |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 693 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 694 | _noheaders = None |
| 695 | def noheaders(): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 696 | """Return an empty mimetools.Message object.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 697 | global _noheaders |
Raymond Hettinger | 10ff706 | 2002-06-02 03:04:52 +0000 | [diff] [blame] | 698 | if _noheaders is None: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 699 | import mimetools |
| 700 | import StringIO |
| 701 | _noheaders = mimetools.Message(StringIO.StringIO(), 0) |
| 702 | _noheaders.fp.close() # Recycle file descriptor |
| 703 | return _noheaders |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 704 | |
| 705 | |
| 706 | # Utility classes |
| 707 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 708 | class ftpwrapper: |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 709 | """Class used by open_ftp() for cache of open FTP connections.""" |
| 710 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 711 | def __init__(self, user, passwd, host, port, dirs): |
| 712 | self.user = user |
| 713 | self.passwd = passwd |
| 714 | self.host = host |
| 715 | self.port = port |
| 716 | self.dirs = dirs |
| 717 | self.init() |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 718 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 719 | def init(self): |
| 720 | import ftplib |
| 721 | self.busy = 0 |
| 722 | self.ftp = ftplib.FTP() |
| 723 | self.ftp.connect(self.host, self.port) |
| 724 | self.ftp.login(self.user, self.passwd) |
| 725 | for dir in self.dirs: |
| 726 | self.ftp.cwd(dir) |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 727 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 728 | def retrfile(self, file, type): |
| 729 | import ftplib |
| 730 | self.endtransfer() |
| 731 | if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1 |
| 732 | else: cmd = 'TYPE ' + type; isdir = 0 |
| 733 | try: |
| 734 | self.ftp.voidcmd(cmd) |
| 735 | except ftplib.all_errors: |
| 736 | self.init() |
| 737 | self.ftp.voidcmd(cmd) |
| 738 | conn = None |
| 739 | if file and not isdir: |
| 740 | # Use nlst to see if the file exists at all |
| 741 | try: |
| 742 | self.ftp.nlst(file) |
| 743 | except ftplib.error_perm, reason: |
| 744 | raise IOError, ('ftp error', reason), sys.exc_info()[2] |
| 745 | # Restore the transfer mode! |
| 746 | self.ftp.voidcmd(cmd) |
| 747 | # Try to retrieve as a file |
| 748 | try: |
| 749 | cmd = 'RETR ' + file |
| 750 | conn = self.ftp.ntransfercmd(cmd) |
| 751 | except ftplib.error_perm, reason: |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 752 | if str(reason)[:3] != '550': |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 753 | raise IOError, ('ftp error', reason), sys.exc_info()[2] |
| 754 | if not conn: |
| 755 | # Set transfer mode to ASCII! |
| 756 | self.ftp.voidcmd('TYPE A') |
| 757 | # Try a directory listing |
| 758 | if file: cmd = 'LIST ' + file |
| 759 | else: cmd = 'LIST' |
| 760 | conn = self.ftp.ntransfercmd(cmd) |
| 761 | self.busy = 1 |
| 762 | # Pass back both a suitably decorated object and a retrieval length |
| 763 | return (addclosehook(conn[0].makefile('rb'), |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 764 | self.endtransfer), conn[1]) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 765 | def endtransfer(self): |
| 766 | if not self.busy: |
| 767 | return |
| 768 | self.busy = 0 |
| 769 | try: |
| 770 | self.ftp.voidresp() |
| 771 | except ftperrors(): |
| 772 | pass |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 773 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 774 | def close(self): |
| 775 | self.endtransfer() |
| 776 | try: |
| 777 | self.ftp.close() |
| 778 | except ftperrors(): |
| 779 | pass |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 780 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 781 | class addbase: |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 782 | """Base class for addinfo and addclosehook.""" |
| 783 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 784 | def __init__(self, fp): |
| 785 | self.fp = fp |
| 786 | self.read = self.fp.read |
| 787 | self.readline = self.fp.readline |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 788 | if hasattr(self.fp, "readlines"): self.readlines = self.fp.readlines |
| 789 | if hasattr(self.fp, "fileno"): self.fileno = self.fp.fileno |
Raymond Hettinger | 42182eb | 2003-03-09 05:33:33 +0000 | [diff] [blame] | 790 | if hasattr(self.fp, "__iter__"): |
| 791 | self.__iter__ = self.fp.__iter__ |
| 792 | if hasattr(self.fp, "next"): |
| 793 | self.next = self.fp.next |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 794 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 795 | def __repr__(self): |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 796 | return '<%s at %r whose fp = %r>' % (self.__class__.__name__, |
| 797 | id(self), self.fp) |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 798 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 799 | def close(self): |
| 800 | self.read = None |
| 801 | self.readline = None |
| 802 | self.readlines = None |
| 803 | self.fileno = None |
| 804 | if self.fp: self.fp.close() |
| 805 | self.fp = None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 806 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 807 | class addclosehook(addbase): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 808 | """Class to add a close hook to an open file.""" |
| 809 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 810 | def __init__(self, fp, closehook, *hookargs): |
| 811 | addbase.__init__(self, fp) |
| 812 | self.closehook = closehook |
| 813 | self.hookargs = hookargs |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 814 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 815 | def close(self): |
Guido van Rossum | c580dae | 2000-05-24 13:21:46 +0000 | [diff] [blame] | 816 | addbase.close(self) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 817 | if self.closehook: |
Guido van Rossum | 68468eb | 2003-02-27 20:14:51 +0000 | [diff] [blame] | 818 | self.closehook(*self.hookargs) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 819 | self.closehook = None |
| 820 | self.hookargs = None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 821 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 822 | class addinfo(addbase): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 823 | """class to add an info() method to an open file.""" |
| 824 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 825 | def __init__(self, fp, headers): |
| 826 | addbase.__init__(self, fp) |
| 827 | self.headers = headers |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 828 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 829 | def info(self): |
| 830 | return self.headers |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 831 | |
Guido van Rossum | e6ad891 | 1996-09-10 17:02:56 +0000 | [diff] [blame] | 832 | class addinfourl(addbase): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 833 | """class to add info() and geturl() methods to an open file.""" |
| 834 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 835 | def __init__(self, fp, headers, url): |
| 836 | addbase.__init__(self, fp) |
| 837 | self.headers = headers |
| 838 | self.url = url |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 839 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 840 | def info(self): |
| 841 | return self.headers |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 842 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 843 | def geturl(self): |
| 844 | return self.url |
Guido van Rossum | e6ad891 | 1996-09-10 17:02:56 +0000 | [diff] [blame] | 845 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 846 | |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 847 | # Utilities to parse URLs (most of these return None for missing parts): |
Sjoerd Mullender | e0371b8 | 1995-11-10 10:36:07 +0000 | [diff] [blame] | 848 | # unwrap('<URL:type://host/path>') --> 'type://host/path' |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 849 | # splittype('type:opaquestring') --> 'type', 'opaquestring' |
| 850 | # splithost('//host[:port]/path') --> 'host[:port]', '/path' |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 851 | # splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]' |
| 852 | # splitpasswd('user:passwd') -> 'user', 'passwd' |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 853 | # splitport('host:port') --> 'host', 'port' |
| 854 | # splitquery('/path?query') --> '/path', 'query' |
| 855 | # splittag('/path#tag') --> '/path', 'tag' |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 856 | # splitattr('/path;attr1=value1;attr2=value2;...') -> |
| 857 | # '/path', ['attr1=value1', 'attr2=value2', ...] |
| 858 | # splitvalue('attr=value') --> 'attr', 'value' |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 859 | # splitgophertype('/Xselector') --> 'X', 'selector' |
| 860 | # unquote('abc%20def') -> 'abc def' |
| 861 | # quote('abc def') -> 'abc%20def') |
| 862 | |
Walter Dörwald | 65230a2 | 2002-06-03 15:58:32 +0000 | [diff] [blame] | 863 | try: |
| 864 | unicode |
| 865 | except NameError: |
Guido van Rossum | 4b46c0a | 2002-05-24 17:58:05 +0000 | [diff] [blame] | 866 | def _is_unicode(x): |
| 867 | return 0 |
Walter Dörwald | 65230a2 | 2002-06-03 15:58:32 +0000 | [diff] [blame] | 868 | else: |
| 869 | def _is_unicode(x): |
| 870 | return isinstance(x, unicode) |
Guido van Rossum | 4b46c0a | 2002-05-24 17:58:05 +0000 | [diff] [blame] | 871 | |
Martin v. Löwis | 1d99433 | 2000-12-03 18:30:10 +0000 | [diff] [blame] | 872 | def toBytes(url): |
| 873 | """toBytes(u"URL") --> 'URL'.""" |
| 874 | # Most URL schemes require ASCII. If that changes, the conversion |
| 875 | # can be relaxed |
Guido van Rossum | 4b46c0a | 2002-05-24 17:58:05 +0000 | [diff] [blame] | 876 | if _is_unicode(url): |
Martin v. Löwis | 1d99433 | 2000-12-03 18:30:10 +0000 | [diff] [blame] | 877 | try: |
| 878 | url = url.encode("ASCII") |
| 879 | except UnicodeError: |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 880 | raise UnicodeError("URL " + repr(url) + |
| 881 | " contains non-ASCII characters") |
Martin v. Löwis | 1d99433 | 2000-12-03 18:30:10 +0000 | [diff] [blame] | 882 | return url |
| 883 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 884 | def unwrap(url): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 885 | """unwrap('<URL:type://host/path>') --> 'type://host/path'.""" |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 886 | url = url.strip() |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 887 | if url[:1] == '<' and url[-1:] == '>': |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 888 | url = url[1:-1].strip() |
| 889 | if url[:4] == 'URL:': url = url[4:].strip() |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 890 | return url |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 891 | |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 892 | _typeprog = None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 893 | def splittype(url): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 894 | """splittype('type:opaquestring') --> 'type', 'opaquestring'.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 895 | global _typeprog |
| 896 | if _typeprog is None: |
| 897 | import re |
| 898 | _typeprog = re.compile('^([^/:]+):') |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 899 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 900 | match = _typeprog.match(url) |
| 901 | if match: |
| 902 | scheme = match.group(1) |
Fred Drake | 9e94afd | 2000-07-01 07:03:30 +0000 | [diff] [blame] | 903 | return scheme.lower(), url[len(scheme) + 1:] |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 904 | return None, url |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 905 | |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 906 | _hostprog = None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 907 | def splithost(url): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 908 | """splithost('//host[:port]/path') --> 'host[:port]', '/path'.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 909 | global _hostprog |
| 910 | if _hostprog is None: |
| 911 | import re |
Guido van Rossum | 3427c1f | 1999-07-01 23:20:56 +0000 | [diff] [blame] | 912 | _hostprog = re.compile('^//([^/]*)(.*)$') |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 913 | |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 914 | match = _hostprog.match(url) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 915 | if match: return match.group(1, 2) |
| 916 | return None, url |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 917 | |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 918 | _userprog = None |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 919 | def splituser(host): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 920 | """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 921 | global _userprog |
| 922 | if _userprog is None: |
| 923 | import re |
Raymond Hettinger | f2e45dd | 2002-08-18 20:08:56 +0000 | [diff] [blame] | 924 | _userprog = re.compile('^(.*)@(.*)$') |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 925 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 926 | match = _userprog.match(host) |
Fred Drake | 567ca8e | 2000-08-21 21:42:42 +0000 | [diff] [blame] | 927 | if match: return map(unquote, match.group(1, 2)) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 928 | return None, host |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 929 | |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 930 | _passwdprog = None |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 931 | def splitpasswd(user): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 932 | """splitpasswd('user:passwd') -> 'user', 'passwd'.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 933 | global _passwdprog |
| 934 | if _passwdprog is None: |
| 935 | import re |
| 936 | _passwdprog = re.compile('^([^:]*):(.*)$') |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 937 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 938 | match = _passwdprog.match(user) |
| 939 | if match: return match.group(1, 2) |
| 940 | return user, None |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 941 | |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 942 | # splittag('/path#tag') --> '/path', 'tag' |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 943 | _portprog = None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 944 | def splitport(host): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 945 | """splitport('host:port') --> 'host', 'port'.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 946 | global _portprog |
| 947 | if _portprog is None: |
| 948 | import re |
| 949 | _portprog = re.compile('^(.*):([0-9]+)$') |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 950 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 951 | match = _portprog.match(host) |
| 952 | if match: return match.group(1, 2) |
| 953 | return host, None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 954 | |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 955 | _nportprog = None |
Guido van Rossum | 53725a2 | 1996-06-13 19:12:35 +0000 | [diff] [blame] | 956 | def splitnport(host, defport=-1): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 957 | """Split host and port, returning numeric port. |
| 958 | Return given default port if no ':' found; defaults to -1. |
| 959 | Return numerical port if a valid number are found after ':'. |
| 960 | Return None if ':' but not a valid number.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 961 | global _nportprog |
| 962 | if _nportprog is None: |
| 963 | import re |
| 964 | _nportprog = re.compile('^(.*):(.*)$') |
Guido van Rossum | 7e7ca0b | 1998-03-26 21:01:39 +0000 | [diff] [blame] | 965 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 966 | match = _nportprog.match(host) |
| 967 | if match: |
| 968 | host, port = match.group(1, 2) |
| 969 | try: |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 970 | if not port: raise ValueError, "no digits" |
| 971 | nport = int(port) |
| 972 | except ValueError: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 973 | nport = None |
| 974 | return host, nport |
| 975 | return host, defport |
Guido van Rossum | 53725a2 | 1996-06-13 19:12:35 +0000 | [diff] [blame] | 976 | |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 977 | _queryprog = None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 978 | def splitquery(url): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 979 | """splitquery('/path?query') --> '/path', 'query'.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 980 | global _queryprog |
| 981 | if _queryprog is None: |
| 982 | import re |
| 983 | _queryprog = re.compile('^(.*)\?([^?]*)$') |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 984 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 985 | match = _queryprog.match(url) |
| 986 | if match: return match.group(1, 2) |
| 987 | return url, None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 988 | |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 989 | _tagprog = None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 990 | def splittag(url): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 991 | """splittag('/path#tag') --> '/path', 'tag'.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 992 | global _tagprog |
| 993 | if _tagprog is None: |
| 994 | import re |
| 995 | _tagprog = re.compile('^(.*)#([^#]*)$') |
Guido van Rossum | 7e7ca0b | 1998-03-26 21:01:39 +0000 | [diff] [blame] | 996 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 997 | match = _tagprog.match(url) |
| 998 | if match: return match.group(1, 2) |
| 999 | return url, None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1000 | |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 1001 | def splitattr(url): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 1002 | """splitattr('/path;attr1=value1;attr2=value2;...') -> |
| 1003 | '/path', ['attr1=value1', 'attr2=value2', ...].""" |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 1004 | words = url.split(';') |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1005 | return words[0], words[1:] |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 1006 | |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 1007 | _valueprog = None |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 1008 | def splitvalue(attr): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 1009 | """splitvalue('attr=value') --> 'attr', 'value'.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1010 | global _valueprog |
| 1011 | if _valueprog is None: |
| 1012 | import re |
| 1013 | _valueprog = re.compile('^([^=]*)=(.*)$') |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 1014 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1015 | match = _valueprog.match(attr) |
| 1016 | if match: return match.group(1, 2) |
| 1017 | return attr, None |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 1018 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1019 | def splitgophertype(selector): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 1020 | """splitgophertype('/Xselector') --> 'X', 'selector'.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1021 | if selector[:1] == '/' and selector[1:2]: |
| 1022 | return selector[1], selector[2:] |
| 1023 | return None, selector |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1024 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1025 | def unquote(s): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 1026 | """unquote('abc%20def') -> 'abc def'.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1027 | mychr = chr |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 1028 | myatoi = int |
| 1029 | list = s.split('%') |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1030 | res = [list[0]] |
| 1031 | myappend = res.append |
| 1032 | del list[0] |
| 1033 | for item in list: |
| 1034 | if item[1:2]: |
| 1035 | try: |
| 1036 | myappend(mychr(myatoi(item[:2], 16)) |
| 1037 | + item[2:]) |
Martin v. Löwis | 58682b7 | 2001-08-11 15:02:57 +0000 | [diff] [blame] | 1038 | except ValueError: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1039 | myappend('%' + item) |
| 1040 | else: |
| 1041 | myappend('%' + item) |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 1042 | return "".join(res) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1043 | |
Guido van Rossum | 0564e12 | 1996-12-13 14:47:36 +0000 | [diff] [blame] | 1044 | def unquote_plus(s): |
Skip Montanaro | 79f1c17 | 2000-08-22 03:00:52 +0000 | [diff] [blame] | 1045 | """unquote('%7e/abc+def') -> '~/abc def'""" |
Brett Cannon | aaeffaf | 2004-03-23 23:50:17 +0000 | [diff] [blame] | 1046 | s = s.replace('+', ' ') |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1047 | return unquote(s) |
Guido van Rossum | 0564e12 | 1996-12-13 14:47:36 +0000 | [diff] [blame] | 1048 | |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 1049 | always_safe = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ' |
Jeremy Hylton | 6102e29 | 2000-08-31 15:48:10 +0000 | [diff] [blame] | 1050 | 'abcdefghijklmnopqrstuvwxyz' |
Jeremy Hylton | 7ae51bf | 2000-09-14 16:59:07 +0000 | [diff] [blame] | 1051 | '0123456789' '_.-') |
| 1052 | |
| 1053 | _fast_safe_test = always_safe + '/' |
| 1054 | _fast_safe = None |
| 1055 | |
| 1056 | def _fast_quote(s): |
| 1057 | global _fast_safe |
| 1058 | if _fast_safe is None: |
| 1059 | _fast_safe = {} |
| 1060 | for c in _fast_safe_test: |
| 1061 | _fast_safe[c] = c |
| 1062 | res = list(s) |
| 1063 | for i in range(len(res)): |
| 1064 | c = res[i] |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 1065 | if not c in _fast_safe: |
Guido van Rossum | e27a7b8 | 2001-01-19 03:28:15 +0000 | [diff] [blame] | 1066 | res[i] = '%%%02X' % ord(c) |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 1067 | return ''.join(res) |
Jeremy Hylton | 7ae51bf | 2000-09-14 16:59:07 +0000 | [diff] [blame] | 1068 | |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 1069 | def quote(s, safe = '/'): |
Jeremy Hylton | 7ae51bf | 2000-09-14 16:59:07 +0000 | [diff] [blame] | 1070 | """quote('abc def') -> 'abc%20def' |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 1071 | |
Jeremy Hylton | 7ae51bf | 2000-09-14 16:59:07 +0000 | [diff] [blame] | 1072 | Each part of a URL, e.g. the path info, the query, etc., has a |
| 1073 | different set of reserved characters that must be quoted. |
| 1074 | |
| 1075 | RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists |
| 1076 | the following reserved characters. |
| 1077 | |
| 1078 | reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | |
| 1079 | "$" | "," |
| 1080 | |
| 1081 | Each of these characters is reserved in some component of a URL, |
| 1082 | but not necessarily in all of them. |
| 1083 | |
| 1084 | By default, the quote function is intended for quoting the path |
| 1085 | section of a URL. Thus, it will not encode '/'. This character |
| 1086 | is reserved, but in typical usage the quote function is being |
| 1087 | called on a path where the existing slash characters are used as |
| 1088 | reserved characters. |
| 1089 | """ |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1090 | safe = always_safe + safe |
Jeremy Hylton | 7ae51bf | 2000-09-14 16:59:07 +0000 | [diff] [blame] | 1091 | if _fast_safe_test == safe: |
| 1092 | return _fast_quote(s) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1093 | res = list(s) |
| 1094 | for i in range(len(res)): |
| 1095 | c = res[i] |
| 1096 | if c not in safe: |
Guido van Rossum | e27a7b8 | 2001-01-19 03:28:15 +0000 | [diff] [blame] | 1097 | res[i] = '%%%02X' % ord(c) |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 1098 | return ''.join(res) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1099 | |
Jeremy Hylton | 7ae51bf | 2000-09-14 16:59:07 +0000 | [diff] [blame] | 1100 | def quote_plus(s, safe = ''): |
| 1101 | """Quote the query fragment of a URL; replacing ' ' with '+'""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1102 | if ' ' in s: |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 1103 | l = s.split(' ') |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1104 | for i in range(len(l)): |
| 1105 | l[i] = quote(l[i], safe) |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 1106 | return '+'.join(l) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1107 | else: |
| 1108 | return quote(s, safe) |
Guido van Rossum | 0564e12 | 1996-12-13 14:47:36 +0000 | [diff] [blame] | 1109 | |
Skip Montanaro | 14f1ad4 | 2001-01-28 21:11:12 +0000 | [diff] [blame] | 1110 | def urlencode(query,doseq=0): |
| 1111 | """Encode a sequence of two-element tuples or dictionary into a URL query string. |
Skip Montanaro | a5d23a1 | 2001-01-20 15:56:39 +0000 | [diff] [blame] | 1112 | |
Skip Montanaro | 14f1ad4 | 2001-01-28 21:11:12 +0000 | [diff] [blame] | 1113 | If any values in the query arg are sequences and doseq is true, each |
Skip Montanaro | a5d23a1 | 2001-01-20 15:56:39 +0000 | [diff] [blame] | 1114 | sequence element is converted to a separate parameter. |
Skip Montanaro | 14f1ad4 | 2001-01-28 21:11:12 +0000 | [diff] [blame] | 1115 | |
| 1116 | If the query arg is a sequence of two-element tuples, the order of the |
| 1117 | parameters in the output will match the order of parameters in the |
| 1118 | input. |
Skip Montanaro | a5d23a1 | 2001-01-20 15:56:39 +0000 | [diff] [blame] | 1119 | """ |
Tim Peters | 658cba6 | 2001-02-09 20:06:00 +0000 | [diff] [blame] | 1120 | |
Skip Montanaro | 14f1ad4 | 2001-01-28 21:11:12 +0000 | [diff] [blame] | 1121 | if hasattr(query,"items"): |
| 1122 | # mapping objects |
| 1123 | query = query.items() |
| 1124 | else: |
| 1125 | # it's a bother at times that strings and string-like objects are |
| 1126 | # sequences... |
| 1127 | try: |
| 1128 | # non-sequence items should not work with len() |
Skip Montanaro | 14f1ad4 | 2001-01-28 21:11:12 +0000 | [diff] [blame] | 1129 | # non-empty strings will fail this |
Walter Dörwald | 65230a2 | 2002-06-03 15:58:32 +0000 | [diff] [blame] | 1130 | if len(query) and not isinstance(query[0], tuple): |
Skip Montanaro | 14f1ad4 | 2001-01-28 21:11:12 +0000 | [diff] [blame] | 1131 | raise TypeError |
| 1132 | # zero-length sequences of all types will get here and succeed, |
| 1133 | # but that's a minor nit - since the original implementation |
| 1134 | # allowed empty dicts that type of behavior probably should be |
| 1135 | # preserved for consistency |
| 1136 | except TypeError: |
| 1137 | ty,va,tb = sys.exc_info() |
| 1138 | raise TypeError, "not a valid non-string sequence or mapping object", tb |
| 1139 | |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 1140 | l = [] |
Skip Montanaro | a5d23a1 | 2001-01-20 15:56:39 +0000 | [diff] [blame] | 1141 | if not doseq: |
| 1142 | # preserve old behavior |
Skip Montanaro | 14f1ad4 | 2001-01-28 21:11:12 +0000 | [diff] [blame] | 1143 | for k, v in query: |
Skip Montanaro | a5d23a1 | 2001-01-20 15:56:39 +0000 | [diff] [blame] | 1144 | k = quote_plus(str(k)) |
| 1145 | v = quote_plus(str(v)) |
| 1146 | l.append(k + '=' + v) |
| 1147 | else: |
Skip Montanaro | 14f1ad4 | 2001-01-28 21:11:12 +0000 | [diff] [blame] | 1148 | for k, v in query: |
Skip Montanaro | a5d23a1 | 2001-01-20 15:56:39 +0000 | [diff] [blame] | 1149 | k = quote_plus(str(k)) |
Walter Dörwald | 65230a2 | 2002-06-03 15:58:32 +0000 | [diff] [blame] | 1150 | if isinstance(v, str): |
Skip Montanaro | a5d23a1 | 2001-01-20 15:56:39 +0000 | [diff] [blame] | 1151 | v = quote_plus(v) |
| 1152 | l.append(k + '=' + v) |
Guido van Rossum | 4b46c0a | 2002-05-24 17:58:05 +0000 | [diff] [blame] | 1153 | elif _is_unicode(v): |
Skip Montanaro | a5d23a1 | 2001-01-20 15:56:39 +0000 | [diff] [blame] | 1154 | # is there a reasonable way to convert to ASCII? |
| 1155 | # encode generates a string, but "replace" or "ignore" |
| 1156 | # lose information and "strict" can raise UnicodeError |
| 1157 | v = quote_plus(v.encode("ASCII","replace")) |
| 1158 | l.append(k + '=' + v) |
| 1159 | else: |
| 1160 | try: |
| 1161 | # is this a sufficient test for sequence-ness? |
| 1162 | x = len(v) |
| 1163 | except TypeError: |
| 1164 | # not a sequence |
| 1165 | v = quote_plus(str(v)) |
| 1166 | l.append(k + '=' + v) |
| 1167 | else: |
| 1168 | # loop over the sequence |
| 1169 | for elt in v: |
| 1170 | l.append(k + '=' + quote_plus(str(elt))) |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 1171 | return '&'.join(l) |
Guido van Rossum | 810a339 | 1998-07-22 21:33:23 +0000 | [diff] [blame] | 1172 | |
Guido van Rossum | 442e720 | 1996-03-20 15:33:11 +0000 | [diff] [blame] | 1173 | # Proxy handling |
Mark Hammond | 4f570b9 | 2000-07-26 07:04:38 +0000 | [diff] [blame] | 1174 | def getproxies_environment(): |
| 1175 | """Return a dictionary of scheme -> proxy server URL mappings. |
| 1176 | |
| 1177 | Scan the environment for variables named <scheme>_proxy; |
| 1178 | this seems to be the standard convention. If you need a |
| 1179 | different way, you can pass a proxies dictionary to the |
| 1180 | [Fancy]URLopener constructor. |
| 1181 | |
| 1182 | """ |
| 1183 | proxies = {} |
| 1184 | for name, value in os.environ.items(): |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 1185 | name = name.lower() |
Mark Hammond | 4f570b9 | 2000-07-26 07:04:38 +0000 | [diff] [blame] | 1186 | if value and name[-6:] == '_proxy': |
| 1187 | proxies[name[:-6]] = value |
| 1188 | return proxies |
| 1189 | |
Guido van Rossum | 4163e70 | 1998-08-06 13:39:09 +0000 | [diff] [blame] | 1190 | if os.name == 'mac': |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1191 | def getproxies(): |
| 1192 | """Return a dictionary of scheme -> proxy server URL mappings. |
Guido van Rossum | 442e720 | 1996-03-20 15:33:11 +0000 | [diff] [blame] | 1193 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1194 | By convention the mac uses Internet Config to store |
| 1195 | proxies. An HTTP proxy, for instance, is stored under |
| 1196 | the HttpProxy key. |
Guido van Rossum | 442e720 | 1996-03-20 15:33:11 +0000 | [diff] [blame] | 1197 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1198 | """ |
| 1199 | try: |
| 1200 | import ic |
| 1201 | except ImportError: |
| 1202 | return {} |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 1203 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1204 | try: |
| 1205 | config = ic.IC() |
| 1206 | except ic.error: |
| 1207 | return {} |
| 1208 | proxies = {} |
| 1209 | # HTTP: |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 1210 | if 'UseHTTPProxy' in config and config['UseHTTPProxy']: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1211 | try: |
| 1212 | value = config['HTTPProxyHost'] |
| 1213 | except ic.error: |
| 1214 | pass |
| 1215 | else: |
| 1216 | proxies['http'] = 'http://%s' % value |
| 1217 | # FTP: XXXX To be done. |
| 1218 | # Gopher: XXXX To be done. |
| 1219 | return proxies |
Mark Hammond | 4f570b9 | 2000-07-26 07:04:38 +0000 | [diff] [blame] | 1220 | |
Tim Peters | 55c12d4 | 2001-08-09 18:04:14 +0000 | [diff] [blame] | 1221 | def proxy_bypass(x): |
| 1222 | return 0 |
| 1223 | |
Mark Hammond | 4f570b9 | 2000-07-26 07:04:38 +0000 | [diff] [blame] | 1224 | elif os.name == 'nt': |
| 1225 | def getproxies_registry(): |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1226 | """Return a dictionary of scheme -> proxy server URL mappings. |
Mark Hammond | 4f570b9 | 2000-07-26 07:04:38 +0000 | [diff] [blame] | 1227 | |
| 1228 | Win32 uses the registry to store proxies. |
| 1229 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1230 | """ |
| 1231 | proxies = {} |
Mark Hammond | 4f570b9 | 2000-07-26 07:04:38 +0000 | [diff] [blame] | 1232 | try: |
| 1233 | import _winreg |
| 1234 | except ImportError: |
| 1235 | # Std module, so should be around - but you never know! |
| 1236 | return proxies |
| 1237 | try: |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 1238 | internetSettings = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, |
| 1239 | r'Software\Microsoft\Windows\CurrentVersion\Internet Settings') |
Mark Hammond | 4f570b9 | 2000-07-26 07:04:38 +0000 | [diff] [blame] | 1240 | proxyEnable = _winreg.QueryValueEx(internetSettings, |
| 1241 | 'ProxyEnable')[0] |
| 1242 | if proxyEnable: |
| 1243 | # Returned as Unicode but problems if not converted to ASCII |
| 1244 | proxyServer = str(_winreg.QueryValueEx(internetSettings, |
| 1245 | 'ProxyServer')[0]) |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 1246 | if '=' in proxyServer: |
| 1247 | # Per-protocol settings |
Mark Hammond | 4f570b9 | 2000-07-26 07:04:38 +0000 | [diff] [blame] | 1248 | for p in proxyServer.split(';'): |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 1249 | protocol, address = p.split('=', 1) |
Guido van Rossum | b955d6c | 2002-03-31 23:38:48 +0000 | [diff] [blame] | 1250 | # See if address has a type:// prefix |
Guido van Rossum | 64e5aa9 | 2002-04-02 14:38:16 +0000 | [diff] [blame] | 1251 | import re |
| 1252 | if not re.match('^([^/:]+)://', address): |
Guido van Rossum | b955d6c | 2002-03-31 23:38:48 +0000 | [diff] [blame] | 1253 | address = '%s://%s' % (protocol, address) |
| 1254 | proxies[protocol] = address |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 1255 | else: |
| 1256 | # Use one setting for all protocols |
| 1257 | if proxyServer[:5] == 'http:': |
| 1258 | proxies['http'] = proxyServer |
| 1259 | else: |
| 1260 | proxies['http'] = 'http://%s' % proxyServer |
| 1261 | proxies['ftp'] = 'ftp://%s' % proxyServer |
Mark Hammond | 4f570b9 | 2000-07-26 07:04:38 +0000 | [diff] [blame] | 1262 | internetSettings.Close() |
| 1263 | except (WindowsError, ValueError, TypeError): |
| 1264 | # Either registry key not found etc, or the value in an |
| 1265 | # unexpected format. |
| 1266 | # proxies already set up to be empty so nothing to do |
| 1267 | pass |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1268 | return proxies |
Guido van Rossum | 442e720 | 1996-03-20 15:33:11 +0000 | [diff] [blame] | 1269 | |
Mark Hammond | 4f570b9 | 2000-07-26 07:04:38 +0000 | [diff] [blame] | 1270 | def getproxies(): |
| 1271 | """Return a dictionary of scheme -> proxy server URL mappings. |
| 1272 | |
| 1273 | Returns settings gathered from the environment, if specified, |
| 1274 | or the registry. |
| 1275 | |
| 1276 | """ |
| 1277 | return getproxies_environment() or getproxies_registry() |
Tim Peters | 55c12d4 | 2001-08-09 18:04:14 +0000 | [diff] [blame] | 1278 | |
| 1279 | def proxy_bypass(host): |
| 1280 | try: |
| 1281 | import _winreg |
| 1282 | import re |
Tim Peters | 55c12d4 | 2001-08-09 18:04:14 +0000 | [diff] [blame] | 1283 | except ImportError: |
| 1284 | # Std modules, so should be around - but you never know! |
| 1285 | return 0 |
| 1286 | try: |
| 1287 | internetSettings = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, |
| 1288 | r'Software\Microsoft\Windows\CurrentVersion\Internet Settings') |
| 1289 | proxyEnable = _winreg.QueryValueEx(internetSettings, |
| 1290 | 'ProxyEnable')[0] |
| 1291 | proxyOverride = str(_winreg.QueryValueEx(internetSettings, |
| 1292 | 'ProxyOverride')[0]) |
| 1293 | # ^^^^ Returned as Unicode but problems if not converted to ASCII |
| 1294 | except WindowsError: |
| 1295 | return 0 |
| 1296 | if not proxyEnable or not proxyOverride: |
| 1297 | return 0 |
| 1298 | # try to make a host list from name and IP address. |
| 1299 | host = [host] |
| 1300 | try: |
| 1301 | addr = socket.gethostbyname(host[0]) |
| 1302 | if addr != host: |
| 1303 | host.append(addr) |
| 1304 | except socket.error: |
| 1305 | pass |
| 1306 | # make a check value list from the registry entry: replace the |
| 1307 | # '<local>' string by the localhost entry and the corresponding |
| 1308 | # canonical entry. |
| 1309 | proxyOverride = proxyOverride.split(';') |
| 1310 | i = 0 |
| 1311 | while i < len(proxyOverride): |
| 1312 | if proxyOverride[i] == '<local>': |
| 1313 | proxyOverride[i:i+1] = ['localhost', |
| 1314 | '127.0.0.1', |
| 1315 | socket.gethostname(), |
| 1316 | socket.gethostbyname( |
| 1317 | socket.gethostname())] |
| 1318 | i += 1 |
| 1319 | # print proxyOverride |
| 1320 | # now check if we match one of the registry values. |
| 1321 | for test in proxyOverride: |
Tim Peters | ab9ba27 | 2001-08-09 21:40:30 +0000 | [diff] [blame] | 1322 | test = test.replace(".", r"\.") # mask dots |
| 1323 | test = test.replace("*", r".*") # change glob sequence |
| 1324 | test = test.replace("?", r".") # change glob char |
Tim Peters | 55c12d4 | 2001-08-09 18:04:14 +0000 | [diff] [blame] | 1325 | for val in host: |
| 1326 | # print "%s <--> %s" %( test, val ) |
| 1327 | if re.match(test, val, re.I): |
| 1328 | return 1 |
| 1329 | return 0 |
| 1330 | |
Mark Hammond | 4f570b9 | 2000-07-26 07:04:38 +0000 | [diff] [blame] | 1331 | else: |
| 1332 | # By default use environment variables |
| 1333 | getproxies = getproxies_environment |
| 1334 | |
Tim Peters | 55c12d4 | 2001-08-09 18:04:14 +0000 | [diff] [blame] | 1335 | def proxy_bypass(host): |
| 1336 | return 0 |
Guido van Rossum | 442e720 | 1996-03-20 15:33:11 +0000 | [diff] [blame] | 1337 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1338 | # Test and time quote() and unquote() |
| 1339 | def test1(): |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1340 | s = '' |
| 1341 | for i in range(256): s = s + chr(i) |
| 1342 | s = s*4 |
| 1343 | t0 = time.time() |
| 1344 | qs = quote(s) |
| 1345 | uqs = unquote(qs) |
| 1346 | t1 = time.time() |
| 1347 | if uqs != s: |
| 1348 | print 'Wrong!' |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 1349 | print repr(s) |
| 1350 | print repr(qs) |
| 1351 | print repr(uqs) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1352 | print round(t1 - t0, 3), 'sec' |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1353 | |
| 1354 | |
Guido van Rossum | 9ab96d4 | 1998-09-28 14:07:00 +0000 | [diff] [blame] | 1355 | def reporthook(blocknum, blocksize, totalsize): |
| 1356 | # Report during remote transfers |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 1357 | print "Block number: %d, Block size: %d, Total size: %d" % ( |
| 1358 | blocknum, blocksize, totalsize) |
Guido van Rossum | 9ab96d4 | 1998-09-28 14:07:00 +0000 | [diff] [blame] | 1359 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1360 | # Test program |
Guido van Rossum | 2349015 | 1998-06-25 02:39:00 +0000 | [diff] [blame] | 1361 | def test(args=[]): |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1362 | if not args: |
| 1363 | args = [ |
| 1364 | '/etc/passwd', |
| 1365 | 'file:/etc/passwd', |
| 1366 | 'file://localhost/etc/passwd', |
Andrew M. Kuchling | 56a4235 | 2002-03-18 22:18:46 +0000 | [diff] [blame] | 1367 | 'ftp://ftp.python.org/pub/python/README', |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1368 | ## 'gopher://gopher.micro.umn.edu/1/', |
| 1369 | 'http://www.python.org/index.html', |
| 1370 | ] |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 1371 | if hasattr(URLopener, "open_https"): |
| 1372 | args.append('https://synergy.as.cmu.edu/~geek/') |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1373 | try: |
| 1374 | for url in args: |
| 1375 | print '-'*10, url, '-'*10 |
| 1376 | fn, h = urlretrieve(url, None, reporthook) |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 1377 | print fn |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1378 | if h: |
| 1379 | print '======' |
| 1380 | for k in h.keys(): print k + ':', h[k] |
| 1381 | print '======' |
| 1382 | fp = open(fn, 'rb') |
| 1383 | data = fp.read() |
| 1384 | del fp |
| 1385 | if '\r' in data: |
| 1386 | table = string.maketrans("", "") |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 1387 | data = data.translate(table, "\r") |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1388 | print data |
| 1389 | fn, h = None, None |
| 1390 | print '-'*40 |
| 1391 | finally: |
| 1392 | urlcleanup() |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1393 | |
Guido van Rossum | 2349015 | 1998-06-25 02:39:00 +0000 | [diff] [blame] | 1394 | def main(): |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1395 | import getopt, sys |
| 1396 | try: |
| 1397 | opts, args = getopt.getopt(sys.argv[1:], "th") |
| 1398 | except getopt.error, msg: |
| 1399 | print msg |
| 1400 | print "Use -h for help" |
| 1401 | return |
| 1402 | t = 0 |
| 1403 | for o, a in opts: |
| 1404 | if o == '-t': |
| 1405 | t = t + 1 |
| 1406 | if o == '-h': |
| 1407 | print "Usage: python urllib.py [-t] [url ...]" |
| 1408 | print "-t runs self-test;", |
| 1409 | print "otherwise, contents of urls are printed" |
| 1410 | return |
| 1411 | if t: |
| 1412 | if t > 1: |
| 1413 | test1() |
| 1414 | test(args) |
| 1415 | else: |
| 1416 | if not args: |
| 1417 | print "Use -h for help" |
| 1418 | for url in args: |
| 1419 | print urlopen(url).read(), |
Guido van Rossum | 2349015 | 1998-06-25 02:39:00 +0000 | [diff] [blame] | 1420 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1421 | # Run test program when run as a script |
| 1422 | if __name__ == '__main__': |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1423 | main() |