Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1 | # Open an arbitrary URL |
| 2 | # |
Guido van Rossum | 838cb28 | 1997-02-10 17:51:56 +0000 | [diff] [blame] | 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) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 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() |
| 19 | # and close() methods work like those of open files. |
Guido van Rossum | 838cb28 | 1997-02-10 17:51:56 +0000 | [diff] [blame] | 20 | # The info() method returns a mimetools.Message object which can be |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 21 | # used to query various info about the object, if available. |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 22 | # (mimetools.Message objects are queried with the getheader() method.) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 23 | |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 24 | import string |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 25 | import socket |
Jack Jansen | dc3e3f6 | 1995-12-15 13:22:13 +0000 | [diff] [blame] | 26 | import os |
Guido van Rossum | 3c8484e | 1996-11-20 22:02:24 +0000 | [diff] [blame] | 27 | import sys |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 28 | |
| 29 | |
Guido van Rossum | 8a666e7 | 1998-02-13 01:39:16 +0000 | [diff] [blame] | 30 | __version__ = '1.10' |
Guido van Rossum | f668d17 | 1997-06-06 21:11:11 +0000 | [diff] [blame] | 31 | |
| 32 | MAXFTPCACHE = 10 # Trim the ftp cache beyond this size |
Guido van Rossum | 6cb15a0 | 1995-06-22 19:00:13 +0000 | [diff] [blame] | 33 | |
Jack Jansen | dc3e3f6 | 1995-12-15 13:22:13 +0000 | [diff] [blame] | 34 | # Helper for non-unix systems |
| 35 | if os.name == 'mac': |
Guido van Rossum | 71ac945 | 1996-03-21 16:31:41 +0000 | [diff] [blame] | 36 | from macurl2path import url2pathname, pathname2url |
Guido van Rossum | 7e7ca0b | 1998-03-26 21:01:39 +0000 | [diff] [blame] | 37 | elif os.name == 'nt': |
Guido van Rossum | 2281d35 | 1996-06-26 19:47:37 +0000 | [diff] [blame] | 38 | from nturl2path import url2pathname, pathname2url |
Jack Jansen | dc3e3f6 | 1995-12-15 13:22:13 +0000 | [diff] [blame] | 39 | else: |
Jack Jansen | e8ea21b | 1995-12-21 15:43:53 +0000 | [diff] [blame] | 40 | def url2pathname(pathname): |
Jack Jansen | dc3e3f6 | 1995-12-15 13:22:13 +0000 | [diff] [blame] | 41 | return pathname |
Jack Jansen | e8ea21b | 1995-12-21 15:43:53 +0000 | [diff] [blame] | 42 | def pathname2url(pathname): |
| 43 | return pathname |
Guido van Rossum | 6cb15a0 | 1995-06-22 19:00:13 +0000 | [diff] [blame] | 44 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 45 | # This really consists of two pieces: |
| 46 | # (1) a class which handles opening of all sorts of URLs |
| 47 | # (plus assorted utilities etc.) |
| 48 | # (2) a set of functions for parsing URLs |
| 49 | # XXX Should these be separated out into different modules? |
| 50 | |
| 51 | |
| 52 | # Shortcut for basic usage |
| 53 | _urlopener = None |
Guido van Rossum | bd01374 | 1996-12-10 16:00:28 +0000 | [diff] [blame] | 54 | def urlopen(url, data=None): |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 55 | global _urlopener |
| 56 | if not _urlopener: |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 57 | _urlopener = FancyURLopener() |
Guido van Rossum | bd01374 | 1996-12-10 16:00:28 +0000 | [diff] [blame] | 58 | if data is None: |
| 59 | return _urlopener.open(url) |
| 60 | else: |
| 61 | return _urlopener.open(url, data) |
Guido van Rossum | a7e4b28 | 1996-06-11 00:16:27 +0000 | [diff] [blame] | 62 | def urlretrieve(url, filename=None): |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 63 | global _urlopener |
| 64 | if not _urlopener: |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 65 | _urlopener = FancyURLopener() |
Guido van Rossum | a7e4b28 | 1996-06-11 00:16:27 +0000 | [diff] [blame] | 66 | if filename: |
Guido van Rossum | 7e7ca0b | 1998-03-26 21:01:39 +0000 | [diff] [blame] | 67 | return _urlopener.retrieve(url, filename) |
Guido van Rossum | a7e4b28 | 1996-06-11 00:16:27 +0000 | [diff] [blame] | 68 | else: |
Guido van Rossum | 7e7ca0b | 1998-03-26 21:01:39 +0000 | [diff] [blame] | 69 | return _urlopener.retrieve(url) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 70 | def urlcleanup(): |
| 71 | if _urlopener: |
| 72 | _urlopener.cleanup() |
| 73 | |
| 74 | |
| 75 | # Class to open URLs. |
| 76 | # This is a class rather than just a subroutine because we may need |
| 77 | # more than one set of global protocol-specific options. |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 78 | # Note -- this is a base class for those who don't want the |
| 79 | # automatic handling of errors type 302 (relocated) and 401 |
| 80 | # (authorization needed). |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 81 | ftpcache = {} |
| 82 | class URLopener: |
| 83 | |
Guido van Rossum | 036309b | 1997-10-27 18:56:19 +0000 | [diff] [blame] | 84 | __tempfiles = None |
Guido van Rossum | 29e7781 | 1996-11-27 19:39:58 +0000 | [diff] [blame] | 85 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 86 | # Constructor |
Guido van Rossum | 442e720 | 1996-03-20 15:33:11 +0000 | [diff] [blame] | 87 | def __init__(self, proxies=None): |
| 88 | if proxies is None: |
| 89 | proxies = getproxies() |
Guido van Rossum | 8360005 | 1997-11-18 15:50:39 +0000 | [diff] [blame] | 90 | assert hasattr(proxies, 'has_key'), "proxies must be a mapping" |
Guido van Rossum | 442e720 | 1996-03-20 15:33:11 +0000 | [diff] [blame] | 91 | self.proxies = proxies |
Guido van Rossum | 6cb15a0 | 1995-06-22 19:00:13 +0000 | [diff] [blame] | 92 | server_version = "Python-urllib/%s" % __version__ |
| 93 | self.addheaders = [('User-agent', server_version)] |
Guido van Rossum | 1049932 | 1997-09-08 02:16:33 +0000 | [diff] [blame] | 94 | self.__tempfiles = [] |
Guido van Rossum | 036309b | 1997-10-27 18:56:19 +0000 | [diff] [blame] | 95 | self.__unlink = os.unlink # See cleanup() |
Guido van Rossum | 7aeb4b9 | 1994-08-23 13:32:20 +0000 | [diff] [blame] | 96 | self.tempcache = None |
| 97 | # Undocumented feature: if you assign {} to tempcache, |
| 98 | # it is used to cache files retrieved with |
| 99 | # self.retrieve(). This is not enabled by default |
| 100 | # since it does not work for changing documents (and I |
| 101 | # haven't got the logic to check expiration headers |
| 102 | # yet). |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 103 | self.ftpcache = ftpcache |
| 104 | # Undocumented feature: you can use a different |
| 105 | # ftp cache by assigning to the .ftpcache member; |
| 106 | # in case you want logically independent URL openers |
Guido van Rossum | 4163e70 | 1998-08-06 13:39:09 +0000 | [diff] [blame] | 107 | # XXX This is not threadsafe. Bah. |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 108 | |
| 109 | def __del__(self): |
| 110 | self.close() |
| 111 | |
| 112 | def close(self): |
| 113 | self.cleanup() |
| 114 | |
| 115 | def cleanup(self): |
Guido van Rossum | 036309b | 1997-10-27 18:56:19 +0000 | [diff] [blame] | 116 | # This code sometimes runs when the rest of this module |
| 117 | # has already been deleted, so it can't use any globals |
| 118 | # or import anything. |
Guido van Rossum | 2b3fd76 | 1997-09-03 22:36:15 +0000 | [diff] [blame] | 119 | if self.__tempfiles: |
Guido van Rossum | 2b3fd76 | 1997-09-03 22:36:15 +0000 | [diff] [blame] | 120 | for file in self.__tempfiles: |
Guido van Rossum | 7aeb4b9 | 1994-08-23 13:32:20 +0000 | [diff] [blame] | 121 | try: |
Guido van Rossum | 036309b | 1997-10-27 18:56:19 +0000 | [diff] [blame] | 122 | self.__unlink(file) |
| 123 | except: |
Guido van Rossum | 7aeb4b9 | 1994-08-23 13:32:20 +0000 | [diff] [blame] | 124 | pass |
Guido van Rossum | 036309b | 1997-10-27 18:56:19 +0000 | [diff] [blame] | 125 | del self.__tempfiles[:] |
| 126 | if self.tempcache: |
Guido van Rossum | 7e7ca0b | 1998-03-26 21:01:39 +0000 | [diff] [blame] | 127 | self.tempcache.clear() |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 128 | |
| 129 | # Add a header to be used by the HTTP interface only |
| 130 | # e.g. u.addheader('Accept', 'sound/basic') |
| 131 | def addheader(self, *args): |
| 132 | self.addheaders.append(args) |
| 133 | |
| 134 | # External interface |
| 135 | # Use URLopener().open(file) instead of open(file, 'r') |
Guido van Rossum | bd01374 | 1996-12-10 16:00:28 +0000 | [diff] [blame] | 136 | def open(self, fullurl, data=None): |
Guido van Rossum | ca44540 | 1995-08-29 19:19:12 +0000 | [diff] [blame] | 137 | fullurl = unwrap(fullurl) |
Guido van Rossum | 03710d2 | 1998-02-05 16:22:27 +0000 | [diff] [blame] | 138 | if self.tempcache and self.tempcache.has_key(fullurl): |
| 139 | filename, headers = self.tempcache[fullurl] |
| 140 | fp = open(filename, 'rb') |
| 141 | return addinfourl(fp, headers, fullurl) |
Guido van Rossum | ca44540 | 1995-08-29 19:19:12 +0000 | [diff] [blame] | 142 | type, url = splittype(fullurl) |
Guido van Rossum | a08faba | 1998-03-30 17:17:24 +0000 | [diff] [blame] | 143 | if not type: type = 'file' |
Guido van Rossum | 442e720 | 1996-03-20 15:33:11 +0000 | [diff] [blame] | 144 | if self.proxies.has_key(type): |
| 145 | proxy = self.proxies[type] |
| 146 | type, proxy = splittype(proxy) |
| 147 | host, selector = splithost(proxy) |
| 148 | url = (host, fullurl) # Signal special case to open_*() |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 149 | name = 'open_' + type |
| 150 | if '-' in name: |
Guido van Rossum | 7e7ca0b | 1998-03-26 21:01:39 +0000 | [diff] [blame] | 151 | # replace - with _ |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 152 | name = string.join(string.split(name, '-'), '_') |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 153 | if not hasattr(self, name): |
Guido van Rossum | bd01374 | 1996-12-10 16:00:28 +0000 | [diff] [blame] | 154 | if data is None: |
| 155 | return self.open_unknown(fullurl) |
| 156 | else: |
| 157 | return self.open_unknown(fullurl, data) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 158 | try: |
Guido van Rossum | bd01374 | 1996-12-10 16:00:28 +0000 | [diff] [blame] | 159 | if data is None: |
| 160 | return getattr(self, name)(url) |
| 161 | else: |
| 162 | return getattr(self, name)(url, data) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 163 | except socket.error, msg: |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 164 | raise IOError, ('socket error', msg), sys.exc_info()[2] |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 165 | |
Guido van Rossum | ca44540 | 1995-08-29 19:19:12 +0000 | [diff] [blame] | 166 | # Overridable interface to open unknown URL type |
Guido van Rossum | bd01374 | 1996-12-10 16:00:28 +0000 | [diff] [blame] | 167 | def open_unknown(self, fullurl, data=None): |
Guido van Rossum | ca44540 | 1995-08-29 19:19:12 +0000 | [diff] [blame] | 168 | type, url = splittype(fullurl) |
| 169 | raise IOError, ('url error', 'unknown url type', type) |
| 170 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 171 | # External interface |
| 172 | # retrieve(url) returns (filename, None) for a local object |
| 173 | # or (tempfilename, headers) for a remote object |
Guido van Rossum | a7e4b28 | 1996-06-11 00:16:27 +0000 | [diff] [blame] | 174 | def retrieve(self, url, filename=None): |
Guido van Rossum | 03710d2 | 1998-02-05 16:22:27 +0000 | [diff] [blame] | 175 | url = unwrap(url) |
Guido van Rossum | 7aeb4b9 | 1994-08-23 13:32:20 +0000 | [diff] [blame] | 176 | if self.tempcache and self.tempcache.has_key(url): |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 177 | return self.tempcache[url] |
Guido van Rossum | 03710d2 | 1998-02-05 16:22:27 +0000 | [diff] [blame] | 178 | type, url1 = splittype(url) |
Guido van Rossum | a7e4b28 | 1996-06-11 00:16:27 +0000 | [diff] [blame] | 179 | if not filename and (not type or type == 'file'): |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 180 | try: |
| 181 | fp = self.open_local_file(url1) |
Guido van Rossum | 0454b51 | 1998-04-03 15:57:58 +0000 | [diff] [blame] | 182 | hdrs = fp.info() |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 183 | del fp |
Guido van Rossum | b5916ab | 1998-04-03 15:56:16 +0000 | [diff] [blame] | 184 | return url2pathname(splithost(url1)[1]), hdrs |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 185 | except IOError, msg: |
| 186 | pass |
| 187 | fp = self.open(url) |
| 188 | headers = fp.info() |
Guido van Rossum | a7e4b28 | 1996-06-11 00:16:27 +0000 | [diff] [blame] | 189 | if not filename: |
Guido van Rossum | 7e7ca0b | 1998-03-26 21:01:39 +0000 | [diff] [blame] | 190 | import tempfile |
Guido van Rossum | 0454b51 | 1998-04-03 15:57:58 +0000 | [diff] [blame] | 191 | garbage, path = splittype(url) |
Guido van Rossum | 0454b51 | 1998-04-03 15:57:58 +0000 | [diff] [blame] | 192 | garbage, path = splithost(path or "") |
Guido van Rossum | 0454b51 | 1998-04-03 15:57:58 +0000 | [diff] [blame] | 193 | path, garbage = splitquery(path or "") |
Guido van Rossum | 0454b51 | 1998-04-03 15:57:58 +0000 | [diff] [blame] | 194 | path, garbage = splitattr(path or "") |
Guido van Rossum | b5916ab | 1998-04-03 15:56:16 +0000 | [diff] [blame] | 195 | suffix = os.path.splitext(path)[1] |
| 196 | filename = tempfile.mktemp(suffix) |
Guido van Rossum | 7e7ca0b | 1998-03-26 21:01:39 +0000 | [diff] [blame] | 197 | self.__tempfiles.append(filename) |
Guido van Rossum | a7e4b28 | 1996-06-11 00:16:27 +0000 | [diff] [blame] | 198 | result = filename, headers |
Guido van Rossum | 7aeb4b9 | 1994-08-23 13:32:20 +0000 | [diff] [blame] | 199 | if self.tempcache is not None: |
Guido van Rossum | fa59e83 | 1994-09-21 11:36:19 +0000 | [diff] [blame] | 200 | self.tempcache[url] = result |
Guido van Rossum | c511aee | 1997-04-11 19:01:48 +0000 | [diff] [blame] | 201 | tfp = open(filename, 'wb') |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 202 | bs = 1024*8 |
| 203 | block = fp.read(bs) |
| 204 | while block: |
| 205 | tfp.write(block) |
| 206 | block = fp.read(bs) |
Guido van Rossum | ab0abdc | 1997-08-26 19:06:40 +0000 | [diff] [blame] | 207 | fp.close() |
| 208 | tfp.close() |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 209 | del fp |
| 210 | del tfp |
| 211 | return result |
| 212 | |
| 213 | # Each method named open_<type> knows how to open that type of URL |
| 214 | |
| 215 | # Use HTTP protocol |
Guido van Rossum | bd01374 | 1996-12-10 16:00:28 +0000 | [diff] [blame] | 216 | def open_http(self, url, data=None): |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 217 | import httplib |
Guido van Rossum | 0eae8fb | 1998-04-27 15:19:17 +0000 | [diff] [blame] | 218 | user_passwd = None |
Guido van Rossum | 442e720 | 1996-03-20 15:33:11 +0000 | [diff] [blame] | 219 | if type(url) is type(""): |
| 220 | host, selector = splithost(url) |
Guido van Rossum | 0eae8fb | 1998-04-27 15:19:17 +0000 | [diff] [blame] | 221 | if host: |
| 222 | user_passwd, host = splituser(host) |
Guido van Rossum | c24751b | 1997-06-03 14:34:19 +0000 | [diff] [blame] | 223 | realhost = host |
Guido van Rossum | 442e720 | 1996-03-20 15:33:11 +0000 | [diff] [blame] | 224 | else: |
| 225 | host, selector = url |
Guido van Rossum | 78c9637 | 1996-08-26 18:09:59 +0000 | [diff] [blame] | 226 | urltype, rest = splittype(selector) |
Guido van Rossum | e0c0da9 | 1998-05-05 13:58:13 +0000 | [diff] [blame] | 227 | url = rest |
Guido van Rossum | fd79566 | 1997-04-02 05:46:35 +0000 | [diff] [blame] | 228 | user_passwd = None |
Guido van Rossum | c24751b | 1997-06-03 14:34:19 +0000 | [diff] [blame] | 229 | if string.lower(urltype) != 'http': |
Guido van Rossum | 7e7ca0b | 1998-03-26 21:01:39 +0000 | [diff] [blame] | 230 | realhost = None |
Guido van Rossum | c24751b | 1997-06-03 14:34:19 +0000 | [diff] [blame] | 231 | else: |
Guido van Rossum | 7e7ca0b | 1998-03-26 21:01:39 +0000 | [diff] [blame] | 232 | realhost, rest = splithost(rest) |
Guido van Rossum | 0eae8fb | 1998-04-27 15:19:17 +0000 | [diff] [blame] | 233 | if realhost: |
| 234 | user_passwd, realhost = \ |
| 235 | splituser(realhost) |
Guido van Rossum | 7e7ca0b | 1998-03-26 21:01:39 +0000 | [diff] [blame] | 236 | if user_passwd: |
| 237 | selector = "%s://%s%s" % (urltype, |
| 238 | realhost, |
| 239 | rest) |
Guido van Rossum | fd79566 | 1997-04-02 05:46:35 +0000 | [diff] [blame] | 240 | #print "proxy via http:", host, selector |
Guido van Rossum | 590b289 | 1994-04-18 09:39:56 +0000 | [diff] [blame] | 241 | if not host: raise IOError, ('http error', 'no host given') |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 242 | if user_passwd: |
| 243 | import base64 |
| 244 | auth = string.strip(base64.encodestring(user_passwd)) |
| 245 | else: |
| 246 | auth = None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 247 | h = httplib.HTTP(host) |
Guido van Rossum | bd01374 | 1996-12-10 16:00:28 +0000 | [diff] [blame] | 248 | if data is not None: |
| 249 | h.putrequest('POST', selector) |
| 250 | h.putheader('Content-type', |
| 251 | 'application/x-www-form-urlencoded') |
| 252 | h.putheader('Content-length', '%d' % len(data)) |
| 253 | else: |
| 254 | h.putrequest('GET', selector) |
Guido van Rossum | c5d7e80 | 1996-11-11 19:01:17 +0000 | [diff] [blame] | 255 | if auth: h.putheader('Authorization', 'Basic %s' % auth) |
Guido van Rossum | c24751b | 1997-06-03 14:34:19 +0000 | [diff] [blame] | 256 | if realhost: h.putheader('Host', realhost) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 257 | for args in self.addheaders: apply(h.putheader, args) |
Guido van Rossum | 6cb15a0 | 1995-06-22 19:00:13 +0000 | [diff] [blame] | 258 | h.endheaders() |
Guido van Rossum | bd01374 | 1996-12-10 16:00:28 +0000 | [diff] [blame] | 259 | if data is not None: |
| 260 | h.send(data + '\r\n') |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 261 | errcode, errmsg, headers = h.getreply() |
Guido van Rossum | 6cb15a0 | 1995-06-22 19:00:13 +0000 | [diff] [blame] | 262 | fp = h.getfile() |
| 263 | if errcode == 200: |
Guido van Rossum | 8a666e7 | 1998-02-13 01:39:16 +0000 | [diff] [blame] | 264 | return addinfourl(fp, headers, "http:" + url) |
Guido van Rossum | 6cb15a0 | 1995-06-22 19:00:13 +0000 | [diff] [blame] | 265 | else: |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 266 | return self.http_error(url, |
| 267 | fp, errcode, errmsg, headers) |
| 268 | |
| 269 | # Handle http errors. |
| 270 | # Derived class can override this, or provide specific handlers |
| 271 | # named http_error_DDD where DDD is the 3-digit error code |
| 272 | def http_error(self, url, fp, errcode, errmsg, headers): |
| 273 | # First check if there's a specific handler for this error |
| 274 | name = 'http_error_%d' % errcode |
| 275 | if hasattr(self, name): |
| 276 | method = getattr(self, name) |
| 277 | result = method(url, fp, errcode, errmsg, headers) |
| 278 | if result: return result |
| 279 | return self.http_error_default( |
| 280 | url, fp, errcode, errmsg, headers) |
| 281 | |
| 282 | # Default http error handler: close the connection and raises IOError |
| 283 | def http_error_default(self, url, fp, errcode, errmsg, headers): |
| 284 | void = fp.read() |
| 285 | fp.close() |
| 286 | raise IOError, ('http error', errcode, errmsg, headers) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 287 | |
| 288 | # Use Gopher protocol |
| 289 | def open_gopher(self, url): |
| 290 | import gopherlib |
| 291 | host, selector = splithost(url) |
Guido van Rossum | 590b289 | 1994-04-18 09:39:56 +0000 | [diff] [blame] | 292 | if not host: raise IOError, ('gopher error', 'no host given') |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 293 | type, selector = splitgophertype(selector) |
| 294 | selector, query = splitquery(selector) |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 295 | selector = unquote(selector) |
| 296 | if query: |
| 297 | query = unquote(query) |
| 298 | fp = gopherlib.send_query(selector, query, host) |
| 299 | else: |
| 300 | fp = gopherlib.send_selector(selector, host) |
Guido van Rossum | 8a666e7 | 1998-02-13 01:39:16 +0000 | [diff] [blame] | 301 | return addinfourl(fp, noheaders(), "gopher:" + url) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 302 | |
| 303 | # Use local file or FTP depending on form of URL |
| 304 | def open_file(self, url): |
Guido van Rossum | 7e7ca0b | 1998-03-26 21:01:39 +0000 | [diff] [blame] | 305 | if url[:2] == '//' and url[2:3] != '/': |
| 306 | return self.open_ftp(url) |
| 307 | else: |
| 308 | return self.open_local_file(url) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 309 | |
| 310 | # Use local file |
| 311 | def open_local_file(self, url): |
Guido van Rossum | b5916ab | 1998-04-03 15:56:16 +0000 | [diff] [blame] | 312 | import mimetypes, mimetools, StringIO |
| 313 | mtype = mimetypes.guess_type(url)[0] |
| 314 | headers = mimetools.Message(StringIO.StringIO( |
| 315 | 'Content-Type: %s\n' % (mtype or 'text/plain'))) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 316 | host, file = splithost(url) |
Guido van Rossum | b030bc0 | 1996-10-10 16:01:16 +0000 | [diff] [blame] | 317 | if not host: |
Guido van Rossum | 2966b32 | 1997-06-06 17:44:07 +0000 | [diff] [blame] | 318 | return addinfourl( |
| 319 | open(url2pathname(file), 'rb'), |
Guido van Rossum | b5916ab | 1998-04-03 15:56:16 +0000 | [diff] [blame] | 320 | headers, 'file:'+file) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 321 | host, port = splitport(host) |
| 322 | if not port and socket.gethostbyname(host) in ( |
| 323 | localhost(), thishost()): |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 324 | file = unquote(file) |
Guido van Rossum | 2966b32 | 1997-06-06 17:44:07 +0000 | [diff] [blame] | 325 | return addinfourl( |
| 326 | open(url2pathname(file), 'rb'), |
Guido van Rossum | b5916ab | 1998-04-03 15:56:16 +0000 | [diff] [blame] | 327 | headers, 'file:'+file) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 328 | raise IOError, ('local file error', 'not on local host') |
| 329 | |
| 330 | # Use FTP protocol |
| 331 | def open_ftp(self, url): |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 332 | host, path = splithost(url) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 333 | if not host: raise IOError, ('ftp error', 'no host given') |
| 334 | host, port = splitport(host) |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 335 | user, host = splituser(host) |
| 336 | if user: user, passwd = splitpasswd(user) |
| 337 | else: passwd = None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 338 | host = socket.gethostbyname(host) |
| 339 | if not port: |
| 340 | import ftplib |
| 341 | port = ftplib.FTP_PORT |
Guido van Rossum | c0f29c2 | 1997-12-02 20:26:21 +0000 | [diff] [blame] | 342 | else: |
| 343 | port = int(port) |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 344 | path, attrs = splitattr(path) |
| 345 | dirs = string.splitfields(path, '/') |
| 346 | dirs, file = dirs[:-1], dirs[-1] |
| 347 | if dirs and not dirs[0]: dirs = dirs[1:] |
| 348 | key = (user, host, port, string.joinfields(dirs, '/')) |
Guido van Rossum | 4163e70 | 1998-08-06 13:39:09 +0000 | [diff] [blame] | 349 | # XXX thread unsafe! |
Guido van Rossum | f668d17 | 1997-06-06 21:11:11 +0000 | [diff] [blame] | 350 | if len(self.ftpcache) > MAXFTPCACHE: |
| 351 | # Prune the cache, rather arbitrarily |
| 352 | for k in self.ftpcache.keys(): |
| 353 | if k != key: |
| 354 | v = self.ftpcache[k] |
| 355 | del self.ftpcache[k] |
| 356 | v.close() |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 357 | try: |
| 358 | if not self.ftpcache.has_key(key): |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 359 | self.ftpcache[key] = \ |
Guido van Rossum | 8a666e7 | 1998-02-13 01:39:16 +0000 | [diff] [blame] | 360 | ftpwrapper(user, passwd, |
| 361 | host, port, dirs) |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 362 | if not file: type = 'D' |
| 363 | else: type = 'I' |
| 364 | for attr in attrs: |
| 365 | attr, value = splitvalue(attr) |
| 366 | if string.lower(attr) == 'type' and \ |
| 367 | value in ('a', 'A', 'i', 'I', 'd', 'D'): |
| 368 | type = string.upper(value) |
Guido van Rossum | 2966b32 | 1997-06-06 17:44:07 +0000 | [diff] [blame] | 369 | return addinfourl( |
| 370 | self.ftpcache[key].retrfile(file, type), |
Guido van Rossum | 8a666e7 | 1998-02-13 01:39:16 +0000 | [diff] [blame] | 371 | noheaders(), "ftp:" + url) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 372 | except ftperrors(), msg: |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 373 | raise IOError, ('ftp error', msg), sys.exc_info()[2] |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 374 | |
Guido van Rossum | 6d4d1c2 | 1998-03-12 14:32:55 +0000 | [diff] [blame] | 375 | # Use "data" URL |
| 376 | def open_data(self, url, data=None): |
| 377 | # ignore POSTed data |
| 378 | # |
| 379 | # syntax of data URLs: |
| 380 | # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data |
| 381 | # mediatype := [ type "/" subtype ] *( ";" parameter ) |
| 382 | # data := *urlchar |
| 383 | # parameter := attribute "=" value |
| 384 | import StringIO, mimetools, time |
| 385 | try: |
| 386 | [type, data] = string.split(url, ',', 1) |
| 387 | except ValueError: |
| 388 | raise IOError, ('data error', 'bad data URL') |
| 389 | if not type: |
| 390 | type = 'text/plain;charset=US-ASCII' |
| 391 | semi = string.rfind(type, ';') |
| 392 | if semi >= 0 and '=' not in type[semi:]: |
| 393 | encoding = type[semi+1:] |
| 394 | type = type[:semi] |
| 395 | else: |
| 396 | encoding = '' |
| 397 | msg = [] |
| 398 | msg.append('Date: %s'%time.strftime('%a, %d %b %Y %T GMT', |
| 399 | time.gmtime(time.time()))) |
| 400 | msg.append('Content-type: %s' % type) |
| 401 | if encoding == 'base64': |
| 402 | import base64 |
| 403 | data = base64.decodestring(data) |
| 404 | else: |
| 405 | data = unquote(data) |
| 406 | msg.append('Content-length: %d' % len(data)) |
| 407 | msg.append('') |
| 408 | msg.append(data) |
| 409 | msg = string.join(msg, '\n') |
| 410 | f = StringIO.StringIO(msg) |
| 411 | headers = mimetools.Message(f, 0) |
| 412 | f.fileno = None # needed for addinfourl |
| 413 | return addinfourl(f, headers, url) |
| 414 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 415 | |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 416 | # Derived class with handlers for errors we can handle (perhaps) |
| 417 | class FancyURLopener(URLopener): |
| 418 | |
| 419 | def __init__(self, *args): |
| 420 | apply(URLopener.__init__, (self,) + args) |
| 421 | self.auth_cache = {} |
| 422 | |
| 423 | # Default error handling -- don't raise an exception |
| 424 | def http_error_default(self, url, fp, errcode, errmsg, headers): |
Guido van Rossum | 7e7ca0b | 1998-03-26 21:01:39 +0000 | [diff] [blame] | 425 | return addinfourl(fp, headers, "http:" + url) |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 426 | |
Guido van Rossum | e6ad891 | 1996-09-10 17:02:56 +0000 | [diff] [blame] | 427 | # Error 302 -- relocated (temporarily) |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 428 | def http_error_302(self, url, fp, errcode, errmsg, headers): |
| 429 | # XXX The server can force infinite recursion here! |
| 430 | if headers.has_key('location'): |
| 431 | newurl = headers['location'] |
| 432 | elif headers.has_key('uri'): |
| 433 | newurl = headers['uri'] |
| 434 | else: |
| 435 | return |
| 436 | void = fp.read() |
| 437 | fp.close() |
| 438 | return self.open(newurl) |
| 439 | |
Guido van Rossum | e6ad891 | 1996-09-10 17:02:56 +0000 | [diff] [blame] | 440 | # Error 301 -- also relocated (permanently) |
| 441 | http_error_301 = http_error_302 |
| 442 | |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 443 | # Error 401 -- authentication required |
| 444 | # See this URL for a description of the basic authentication scheme: |
| 445 | # http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt |
| 446 | def http_error_401(self, url, fp, errcode, errmsg, headers): |
| 447 | if headers.has_key('www-authenticate'): |
| 448 | stuff = headers['www-authenticate'] |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 449 | import re |
| 450 | match = re.match( |
| 451 | '[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff) |
| 452 | if match: |
Guido van Rossum | 7e7ca0b | 1998-03-26 21:01:39 +0000 | [diff] [blame] | 453 | scheme, realm = match.groups() |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 454 | if string.lower(scheme) == 'basic': |
| 455 | return self.retry_http_basic_auth( |
| 456 | url, realm) |
| 457 | |
| 458 | def retry_http_basic_auth(self, url, realm): |
| 459 | host, selector = splithost(url) |
| 460 | i = string.find(host, '@') + 1 |
| 461 | host = host[i:] |
| 462 | user, passwd = self.get_user_passwd(host, realm, i) |
| 463 | if not (user or passwd): return None |
| 464 | host = user + ':' + passwd + '@' + host |
Guido van Rossum | e0c0da9 | 1998-05-05 13:58:13 +0000 | [diff] [blame] | 465 | newurl = 'http://' + host + selector |
| 466 | return self.open(newurl) |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 467 | |
| 468 | def get_user_passwd(self, host, realm, clear_cache = 0): |
| 469 | key = realm + '@' + string.lower(host) |
| 470 | if self.auth_cache.has_key(key): |
| 471 | if clear_cache: |
| 472 | del self.auth_cache[key] |
| 473 | else: |
| 474 | return self.auth_cache[key] |
| 475 | user, passwd = self.prompt_user_passwd(host, realm) |
| 476 | if user or passwd: self.auth_cache[key] = (user, passwd) |
| 477 | return user, passwd |
| 478 | |
| 479 | def prompt_user_passwd(self, host, realm): |
| 480 | # Override this in a GUI environment! |
Guido van Rossum | ae9ee73 | 1998-06-12 14:21:13 +0000 | [diff] [blame] | 481 | import getpass |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 482 | try: |
| 483 | user = raw_input("Enter username for %s at %s: " % |
| 484 | (realm, host)) |
Guido van Rossum | ae9ee73 | 1998-06-12 14:21:13 +0000 | [diff] [blame] | 485 | passwd = getpass.getpass( |
| 486 | "Enter password for %s in %s at %s: " % |
| 487 | (user, realm, host)) |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 488 | return user, passwd |
| 489 | except KeyboardInterrupt: |
Guido van Rossum | c5d8fed | 1998-02-05 16:21:28 +0000 | [diff] [blame] | 490 | print |
Guido van Rossum | ae9ee73 | 1998-06-12 14:21:13 +0000 | [diff] [blame] | 491 | return None, None |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 492 | |
| 493 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 494 | # Utility functions |
| 495 | |
| 496 | # Return the IP address of the magic hostname 'localhost' |
| 497 | _localhost = None |
| 498 | def localhost(): |
| 499 | global _localhost |
| 500 | if not _localhost: |
| 501 | _localhost = socket.gethostbyname('localhost') |
| 502 | return _localhost |
| 503 | |
| 504 | # Return the IP address of the current host |
| 505 | _thishost = None |
| 506 | def thishost(): |
| 507 | global _thishost |
| 508 | if not _thishost: |
| 509 | _thishost = socket.gethostbyname(socket.gethostname()) |
| 510 | return _thishost |
| 511 | |
| 512 | # Return the set of errors raised by the FTP class |
| 513 | _ftperrors = None |
| 514 | def ftperrors(): |
| 515 | global _ftperrors |
| 516 | if not _ftperrors: |
| 517 | import ftplib |
Guido van Rossum | 2966b32 | 1997-06-06 17:44:07 +0000 | [diff] [blame] | 518 | _ftperrors = ftplib.all_errors |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 519 | return _ftperrors |
| 520 | |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 521 | # Return an empty mimetools.Message object |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 522 | _noheaders = None |
| 523 | def noheaders(): |
| 524 | global _noheaders |
| 525 | if not _noheaders: |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 526 | import mimetools |
| 527 | import StringIO |
| 528 | _noheaders = mimetools.Message(StringIO.StringIO(), 0) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 529 | _noheaders.fp.close() # Recycle file descriptor |
| 530 | return _noheaders |
| 531 | |
| 532 | |
| 533 | # Utility classes |
| 534 | |
| 535 | # Class used by open_ftp() for cache of open FTP connections |
| 536 | class ftpwrapper: |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 537 | def __init__(self, user, passwd, host, port, dirs): |
| 538 | self.user = unquote(user or '') |
| 539 | self.passwd = unquote(passwd or '') |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 540 | self.host = host |
| 541 | self.port = port |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 542 | self.dirs = [] |
| 543 | for dir in dirs: |
| 544 | self.dirs.append(unquote(dir)) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 545 | self.init() |
| 546 | def init(self): |
| 547 | import ftplib |
Guido van Rossum | d499004 | 1997-12-28 04:21:20 +0000 | [diff] [blame] | 548 | self.busy = 0 |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 549 | self.ftp = ftplib.FTP() |
| 550 | self.ftp.connect(self.host, self.port) |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 551 | self.ftp.login(self.user, self.passwd) |
| 552 | for dir in self.dirs: |
| 553 | self.ftp.cwd(dir) |
| 554 | def retrfile(self, file, type): |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 555 | import ftplib |
Guido van Rossum | d499004 | 1997-12-28 04:21:20 +0000 | [diff] [blame] | 556 | self.endtransfer() |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 557 | if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1 |
| 558 | else: cmd = 'TYPE ' + type; isdir = 0 |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 559 | try: |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 560 | self.ftp.voidcmd(cmd) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 561 | except ftplib.all_errors: |
| 562 | self.init() |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 563 | self.ftp.voidcmd(cmd) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 564 | conn = None |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 565 | if file and not isdir: |
Guido van Rossum | d499004 | 1997-12-28 04:21:20 +0000 | [diff] [blame] | 566 | # Use nlst to see if the file exists at all |
| 567 | try: |
| 568 | self.ftp.nlst(file) |
| 569 | except ftplib.error_perm, reason: |
| 570 | raise IOError, ('ftp error', reason), \ |
| 571 | sys.exc_info()[2] |
Guido van Rossum | e757962 | 1998-01-19 22:26:54 +0000 | [diff] [blame] | 572 | # Restore the transfer mode! |
| 573 | self.ftp.voidcmd(cmd) |
Guido van Rossum | d499004 | 1997-12-28 04:21:20 +0000 | [diff] [blame] | 574 | # Try to retrieve as a file |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 575 | try: |
| 576 | cmd = 'RETR ' + file |
| 577 | conn = self.ftp.transfercmd(cmd) |
| 578 | except ftplib.error_perm, reason: |
| 579 | if reason[:3] != '550': |
Guido van Rossum | 3c8484e | 1996-11-20 22:02:24 +0000 | [diff] [blame] | 580 | raise IOError, ('ftp error', reason), \ |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 581 | sys.exc_info()[2] |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 582 | if not conn: |
Guido van Rossum | e757962 | 1998-01-19 22:26:54 +0000 | [diff] [blame] | 583 | # Set transfer mode to ASCII! |
| 584 | self.ftp.voidcmd('TYPE A') |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 585 | # Try a directory listing |
| 586 | if file: cmd = 'LIST ' + file |
| 587 | else: cmd = 'LIST' |
| 588 | conn = self.ftp.transfercmd(cmd) |
Guido van Rossum | d499004 | 1997-12-28 04:21:20 +0000 | [diff] [blame] | 589 | self.busy = 1 |
Guido van Rossum | f668d17 | 1997-06-06 21:11:11 +0000 | [diff] [blame] | 590 | return addclosehook(conn.makefile('rb'), self.endtransfer) |
| 591 | def endtransfer(self): |
Guido van Rossum | d499004 | 1997-12-28 04:21:20 +0000 | [diff] [blame] | 592 | if not self.busy: |
| 593 | return |
| 594 | self.busy = 0 |
Guido van Rossum | f668d17 | 1997-06-06 21:11:11 +0000 | [diff] [blame] | 595 | try: |
| 596 | self.ftp.voidresp() |
| 597 | except ftperrors(): |
| 598 | pass |
| 599 | def close(self): |
Guido van Rossum | d499004 | 1997-12-28 04:21:20 +0000 | [diff] [blame] | 600 | self.endtransfer() |
Guido van Rossum | f668d17 | 1997-06-06 21:11:11 +0000 | [diff] [blame] | 601 | try: |
| 602 | self.ftp.close() |
| 603 | except ftperrors(): |
| 604 | pass |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 605 | |
| 606 | # Base class for addinfo and addclosehook |
| 607 | class addbase: |
| 608 | def __init__(self, fp): |
| 609 | self.fp = fp |
| 610 | self.read = self.fp.read |
| 611 | self.readline = self.fp.readline |
| 612 | self.readlines = self.fp.readlines |
| 613 | self.fileno = self.fp.fileno |
| 614 | def __repr__(self): |
| 615 | return '<%s at %s whose fp = %s>' % ( |
| 616 | self.__class__.__name__, `id(self)`, `self.fp`) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 617 | def close(self): |
| 618 | self.read = None |
| 619 | self.readline = None |
| 620 | self.readlines = None |
| 621 | self.fileno = None |
Guido van Rossum | 6cb15a0 | 1995-06-22 19:00:13 +0000 | [diff] [blame] | 622 | if self.fp: self.fp.close() |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 623 | self.fp = None |
| 624 | |
| 625 | # Class to add a close hook to an open file |
| 626 | class addclosehook(addbase): |
| 627 | def __init__(self, fp, closehook, *hookargs): |
| 628 | addbase.__init__(self, fp) |
| 629 | self.closehook = closehook |
| 630 | self.hookargs = hookargs |
| 631 | def close(self): |
| 632 | if self.closehook: |
| 633 | apply(self.closehook, self.hookargs) |
| 634 | self.closehook = None |
| 635 | self.hookargs = None |
| 636 | addbase.close(self) |
| 637 | |
| 638 | # class to add an info() method to an open file |
| 639 | class addinfo(addbase): |
| 640 | def __init__(self, fp, headers): |
| 641 | addbase.__init__(self, fp) |
| 642 | self.headers = headers |
| 643 | def info(self): |
| 644 | return self.headers |
| 645 | |
Guido van Rossum | e6ad891 | 1996-09-10 17:02:56 +0000 | [diff] [blame] | 646 | # class to add info() and geturl() methods to an open file |
| 647 | class addinfourl(addbase): |
| 648 | def __init__(self, fp, headers, url): |
| 649 | addbase.__init__(self, fp) |
| 650 | self.headers = headers |
| 651 | self.url = url |
| 652 | def info(self): |
| 653 | return self.headers |
| 654 | def geturl(self): |
| 655 | return self.url |
| 656 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 657 | |
| 658 | # Utility to combine a URL with a base URL to form a new URL |
| 659 | |
| 660 | def basejoin(base, url): |
| 661 | type, path = splittype(url) |
Sjoerd Mullender | e0371b8 | 1995-11-10 10:36:07 +0000 | [diff] [blame] | 662 | if type: |
| 663 | # if url is complete (i.e., it contains a type), return it |
| 664 | return url |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 665 | host, path = splithost(path) |
Sjoerd Mullender | e0371b8 | 1995-11-10 10:36:07 +0000 | [diff] [blame] | 666 | type, basepath = splittype(base) # inherit type from base |
| 667 | if host: |
| 668 | # if url contains host, just inherit type |
| 669 | if type: return type + '://' + host + path |
| 670 | else: |
| 671 | # no type inherited, so url must have started with // |
| 672 | # just return it |
| 673 | return url |
| 674 | host, basepath = splithost(basepath) # inherit host |
| 675 | basepath, basetag = splittag(basepath) # remove extraneuous cruft |
| 676 | basepath, basequery = splitquery(basepath) # idem |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 677 | if path[:1] != '/': |
Sjoerd Mullender | e0371b8 | 1995-11-10 10:36:07 +0000 | [diff] [blame] | 678 | # non-absolute path name |
| 679 | if path[:1] in ('#', '?'): |
| 680 | # path is just a tag or query, attach to basepath |
| 681 | i = len(basepath) |
| 682 | else: |
| 683 | # else replace last component |
| 684 | i = string.rfind(basepath, '/') |
| 685 | if i < 0: |
| 686 | # basepath not absolute |
| 687 | if host: |
| 688 | # host present, make absolute |
| 689 | basepath = '/' |
| 690 | else: |
| 691 | # else keep non-absolute |
| 692 | basepath = '' |
| 693 | else: |
| 694 | # remove last file component |
| 695 | basepath = basepath[:i+1] |
Guido van Rossum | 54a1d0b | 1997-04-11 19:09:51 +0000 | [diff] [blame] | 696 | # Interpret ../ (important because of symlinks) |
| 697 | while basepath and path[:3] == '../': |
| 698 | path = path[3:] |
Guido van Rossum | 2b3fd76 | 1997-09-03 22:36:15 +0000 | [diff] [blame] | 699 | i = string.rfind(basepath[:-1], '/') |
Guido van Rossum | 54a1d0b | 1997-04-11 19:09:51 +0000 | [diff] [blame] | 700 | if i > 0: |
Guido van Rossum | 2b3fd76 | 1997-09-03 22:36:15 +0000 | [diff] [blame] | 701 | basepath = basepath[:i+1] |
| 702 | elif i == 0: |
| 703 | basepath = '/' |
| 704 | break |
| 705 | else: |
| 706 | basepath = '' |
Guido van Rossum | 54a1d0b | 1997-04-11 19:09:51 +0000 | [diff] [blame] | 707 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 708 | path = basepath + path |
Sjoerd Mullender | e0371b8 | 1995-11-10 10:36:07 +0000 | [diff] [blame] | 709 | if type and host: return type + '://' + host + path |
| 710 | elif type: return type + ':' + path |
| 711 | elif host: return '//' + host + path # don't know what this means |
| 712 | else: return path |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 713 | |
| 714 | |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 715 | # Utilities to parse URLs (most of these return None for missing parts): |
Sjoerd Mullender | e0371b8 | 1995-11-10 10:36:07 +0000 | [diff] [blame] | 716 | # unwrap('<URL:type://host/path>') --> 'type://host/path' |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 717 | # splittype('type:opaquestring') --> 'type', 'opaquestring' |
| 718 | # splithost('//host[:port]/path') --> 'host[:port]', '/path' |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 719 | # splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]' |
| 720 | # splitpasswd('user:passwd') -> 'user', 'passwd' |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 721 | # splitport('host:port') --> 'host', 'port' |
| 722 | # splitquery('/path?query') --> '/path', 'query' |
| 723 | # splittag('/path#tag') --> '/path', 'tag' |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 724 | # splitattr('/path;attr1=value1;attr2=value2;...') -> |
| 725 | # '/path', ['attr1=value1', 'attr2=value2', ...] |
| 726 | # splitvalue('attr=value') --> 'attr', 'value' |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 727 | # splitgophertype('/Xselector') --> 'X', 'selector' |
| 728 | # unquote('abc%20def') -> 'abc def' |
| 729 | # quote('abc def') -> 'abc%20def') |
| 730 | |
| 731 | def unwrap(url): |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 732 | url = string.strip(url) |
| 733 | if url[:1] == '<' and url[-1:] == '>': |
| 734 | url = string.strip(url[1:-1]) |
| 735 | if url[:4] == 'URL:': url = string.strip(url[4:]) |
| 736 | return url |
| 737 | |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 738 | _typeprog = None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 739 | def splittype(url): |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 740 | global _typeprog |
| 741 | if _typeprog is None: |
Guido van Rossum | 7e7ca0b | 1998-03-26 21:01:39 +0000 | [diff] [blame] | 742 | import re |
| 743 | _typeprog = re.compile('^([^/:]+):') |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 744 | |
Guido van Rossum | 7e7ca0b | 1998-03-26 21:01:39 +0000 | [diff] [blame] | 745 | match = _typeprog.match(url) |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 746 | if match: |
| 747 | scheme = match.group(1) |
Guido van Rossum | ab0d1af | 1997-04-16 15:17:06 +0000 | [diff] [blame] | 748 | return scheme, url[len(scheme) + 1:] |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 749 | return None, url |
| 750 | |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 751 | _hostprog = None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 752 | def splithost(url): |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 753 | global _hostprog |
| 754 | if _hostprog is None: |
Guido van Rossum | 7e7ca0b | 1998-03-26 21:01:39 +0000 | [diff] [blame] | 755 | import re |
| 756 | _hostprog = re.compile('^//([^/]+)(.*)$') |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 757 | |
Guido van Rossum | a08faba | 1998-03-30 17:17:24 +0000 | [diff] [blame] | 758 | match = _hostprog.match(url) |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 759 | if match: return match.group(1, 2) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 760 | return None, url |
| 761 | |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 762 | _userprog = None |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 763 | def splituser(host): |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 764 | global _userprog |
| 765 | if _userprog is None: |
Guido van Rossum | 7e7ca0b | 1998-03-26 21:01:39 +0000 | [diff] [blame] | 766 | import re |
| 767 | _userprog = re.compile('^([^@]*)@(.*)$') |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 768 | |
Guido van Rossum | a08faba | 1998-03-30 17:17:24 +0000 | [diff] [blame] | 769 | match = _userprog.match(host) |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 770 | if match: return match.group(1, 2) |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 771 | return None, host |
| 772 | |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 773 | _passwdprog = None |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 774 | def splitpasswd(user): |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 775 | global _passwdprog |
| 776 | if _passwdprog is None: |
Guido van Rossum | 7e7ca0b | 1998-03-26 21:01:39 +0000 | [diff] [blame] | 777 | import re |
| 778 | _passwdprog = re.compile('^([^:]*):(.*)$') |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 779 | |
Guido van Rossum | a08faba | 1998-03-30 17:17:24 +0000 | [diff] [blame] | 780 | match = _passwdprog.match(user) |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 781 | if match: return match.group(1, 2) |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 782 | return user, None |
| 783 | |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 784 | _portprog = None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 785 | def splitport(host): |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 786 | global _portprog |
| 787 | if _portprog is None: |
Guido van Rossum | 7e7ca0b | 1998-03-26 21:01:39 +0000 | [diff] [blame] | 788 | import re |
| 789 | _portprog = re.compile('^(.*):([0-9]+)$') |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 790 | |
Guido van Rossum | a08faba | 1998-03-30 17:17:24 +0000 | [diff] [blame] | 791 | match = _portprog.match(host) |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 792 | if match: return match.group(1, 2) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 793 | return host, None |
| 794 | |
Guido van Rossum | 53725a2 | 1996-06-13 19:12:35 +0000 | [diff] [blame] | 795 | # Split host and port, returning numeric port. |
| 796 | # Return given default port if no ':' found; defaults to -1. |
Guido van Rossum | 84a00a8 | 1996-06-17 17:11:40 +0000 | [diff] [blame] | 797 | # Return numerical port if a valid number are found after ':'. |
| 798 | # Return None if ':' but not a valid number. |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 799 | _nportprog = None |
Guido van Rossum | 53725a2 | 1996-06-13 19:12:35 +0000 | [diff] [blame] | 800 | def splitnport(host, defport=-1): |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 801 | global _nportprog |
| 802 | if _nportprog is None: |
Guido van Rossum | 7e7ca0b | 1998-03-26 21:01:39 +0000 | [diff] [blame] | 803 | import re |
| 804 | _nportprog = re.compile('^(.*):(.*)$') |
| 805 | |
Guido van Rossum | a08faba | 1998-03-30 17:17:24 +0000 | [diff] [blame] | 806 | match = _nportprog.match(host) |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 807 | if match: |
Guido van Rossum | 7e7ca0b | 1998-03-26 21:01:39 +0000 | [diff] [blame] | 808 | host, port = match.group(1, 2) |
| 809 | try: |
| 810 | if not port: raise string.atoi_error, "no digits" |
| 811 | nport = string.atoi(port) |
| 812 | except string.atoi_error: |
| 813 | nport = None |
| 814 | return host, nport |
Guido van Rossum | 53725a2 | 1996-06-13 19:12:35 +0000 | [diff] [blame] | 815 | return host, defport |
| 816 | |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 817 | _queryprog = None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 818 | def splitquery(url): |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 819 | global _queryprog |
| 820 | if _queryprog is None: |
Guido van Rossum | 7e7ca0b | 1998-03-26 21:01:39 +0000 | [diff] [blame] | 821 | import re |
| 822 | _queryprog = re.compile('^(.*)\?([^?]*)$') |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 823 | |
Guido van Rossum | a08faba | 1998-03-30 17:17:24 +0000 | [diff] [blame] | 824 | match = _queryprog.match(url) |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 825 | if match: return match.group(1, 2) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 826 | return url, None |
| 827 | |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 828 | _tagprog = None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 829 | def splittag(url): |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 830 | global _tagprog |
| 831 | if _tagprog is None: |
Guido van Rossum | 7e7ca0b | 1998-03-26 21:01:39 +0000 | [diff] [blame] | 832 | import re |
| 833 | _tagprog = re.compile('^(.*)#([^#]*)$') |
| 834 | |
Guido van Rossum | a08faba | 1998-03-30 17:17:24 +0000 | [diff] [blame] | 835 | match = _tagprog.match(url) |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 836 | if match: return match.group(1, 2) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 837 | return url, None |
| 838 | |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 839 | def splitattr(url): |
| 840 | words = string.splitfields(url, ';') |
| 841 | return words[0], words[1:] |
| 842 | |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 843 | _valueprog = None |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 844 | def splitvalue(attr): |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 845 | global _valueprog |
| 846 | if _valueprog is None: |
Guido van Rossum | 7e7ca0b | 1998-03-26 21:01:39 +0000 | [diff] [blame] | 847 | import re |
| 848 | _valueprog = re.compile('^([^=]*)=(.*)$') |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 849 | |
Guido van Rossum | 7e7ca0b | 1998-03-26 21:01:39 +0000 | [diff] [blame] | 850 | match = _valueprog.match(attr) |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 851 | if match: return match.group(1, 2) |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 852 | return attr, None |
| 853 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 854 | def splitgophertype(selector): |
| 855 | if selector[:1] == '/' and selector[1:2]: |
| 856 | return selector[1], selector[2:] |
| 857 | return None, selector |
| 858 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 859 | def unquote(s): |
Guido van Rossum | 52e86ad | 1998-06-28 23:49:35 +0000 | [diff] [blame] | 860 | mychr = chr |
| 861 | myatoi = string.atoi |
| 862 | list = string.split(s, '%') |
| 863 | res = [list[0]] |
| 864 | myappend = res.append |
| 865 | del list[0] |
| 866 | for item in list: |
| 867 | if item[1:2]: |
| 868 | try: |
| 869 | myappend(mychr(myatoi(item[:2], 16)) |
| 870 | + item[2:]) |
| 871 | except: |
Guido van Rossum | c94f16f | 1998-06-29 00:42:54 +0000 | [diff] [blame] | 872 | myappend('%' + item) |
Guido van Rossum | 52e86ad | 1998-06-28 23:49:35 +0000 | [diff] [blame] | 873 | else: |
Guido van Rossum | c94f16f | 1998-06-29 00:42:54 +0000 | [diff] [blame] | 874 | myappend('%' + item) |
Guido van Rossum | 52e86ad | 1998-06-28 23:49:35 +0000 | [diff] [blame] | 875 | return string.join(res, "") |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 876 | |
Guido van Rossum | 0564e12 | 1996-12-13 14:47:36 +0000 | [diff] [blame] | 877 | def unquote_plus(s): |
Guido van Rossum | 7e7ca0b | 1998-03-26 21:01:39 +0000 | [diff] [blame] | 878 | if '+' in s: |
| 879 | # replace '+' with ' ' |
| 880 | s = string.join(string.split(s, '+'), ' ') |
| 881 | return unquote(s) |
Guido van Rossum | 0564e12 | 1996-12-13 14:47:36 +0000 | [diff] [blame] | 882 | |
Guido van Rossum | 3bb5448 | 1994-08-29 10:52:58 +0000 | [diff] [blame] | 883 | always_safe = string.letters + string.digits + '_,.-' |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 884 | def quote(s, safe = '/'): |
| 885 | safe = always_safe + safe |
Guido van Rossum | 810a339 | 1998-07-22 21:33:23 +0000 | [diff] [blame] | 886 | res = list(s) |
| 887 | for i in range(len(res)): |
| 888 | c = res[i] |
| 889 | if c not in safe: |
| 890 | res[i] = '%%%02x' % ord(c) |
Guido van Rossum | f8abb38 | 1996-08-26 15:56:12 +0000 | [diff] [blame] | 891 | return string.joinfields(res, '') |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 892 | |
Guido van Rossum | 0564e12 | 1996-12-13 14:47:36 +0000 | [diff] [blame] | 893 | def quote_plus(s, safe = '/'): |
Guido van Rossum | 7e7ca0b | 1998-03-26 21:01:39 +0000 | [diff] [blame] | 894 | if ' ' in s: |
| 895 | # replace ' ' with '+' |
Guido van Rossum | 810a339 | 1998-07-22 21:33:23 +0000 | [diff] [blame] | 896 | l = string.split(s, ' ') |
| 897 | for i in range(len(l)): |
| 898 | l[i] = quote(l[i], safe) |
| 899 | return string.join(l, '+') |
Guido van Rossum | 7e7ca0b | 1998-03-26 21:01:39 +0000 | [diff] [blame] | 900 | else: |
| 901 | return quote(s, safe) |
Guido van Rossum | 0564e12 | 1996-12-13 14:47:36 +0000 | [diff] [blame] | 902 | |
Guido van Rossum | 810a339 | 1998-07-22 21:33:23 +0000 | [diff] [blame] | 903 | def urlencode(dict): |
| 904 | l = [] |
| 905 | for k, v in dict.items(): |
| 906 | k = quote_plus(str(k)) |
| 907 | v = quote_plus(str(v)) |
| 908 | l.append(k + '=' + v) |
| 909 | return string.join(l, '&') |
| 910 | |
Guido van Rossum | 442e720 | 1996-03-20 15:33:11 +0000 | [diff] [blame] | 911 | |
| 912 | # Proxy handling |
Guido van Rossum | 4163e70 | 1998-08-06 13:39:09 +0000 | [diff] [blame] | 913 | if os.name == 'mac': |
| 914 | def getproxies(): |
| 915 | """Return a dictionary of scheme -> proxy server URL mappings. |
Guido van Rossum | 442e720 | 1996-03-20 15:33:11 +0000 | [diff] [blame] | 916 | |
Guido van Rossum | 4163e70 | 1998-08-06 13:39:09 +0000 | [diff] [blame] | 917 | By convention the mac uses Internet Config to store |
| 918 | proxies. An HTTP proxy, for instance, is stored under |
| 919 | the HttpProxy key. |
Guido van Rossum | 442e720 | 1996-03-20 15:33:11 +0000 | [diff] [blame] | 920 | |
Guido van Rossum | 4163e70 | 1998-08-06 13:39:09 +0000 | [diff] [blame] | 921 | """ |
| 922 | try: |
| 923 | import ic |
| 924 | except ImportError: |
| 925 | return {} |
| 926 | |
| 927 | try: |
| 928 | config = ic.IC() |
| 929 | except ic.error: |
| 930 | return {} |
| 931 | proxies = {} |
| 932 | # HTTP: |
| 933 | if config.has_key('UseHTTPProxy') and config['UseHTTPProxy']: |
| 934 | try: |
| 935 | value = config['HTTPProxyHost'] |
| 936 | except ic.error: |
| 937 | pass |
| 938 | else: |
| 939 | proxies['http'] = 'http://%s' % value |
| 940 | # FTP: XXXX To be done. |
| 941 | # Gopher: XXXX To be done. |
| 942 | return proxies |
| 943 | |
| 944 | else: |
| 945 | def getproxies(): |
| 946 | """Return a dictionary of scheme -> proxy server URL mappings. |
| 947 | |
| 948 | Scan the environment for variables named <scheme>_proxy; |
| 949 | this seems to be the standard convention. If you need a |
| 950 | different way, you can pass a proxies dictionary to the |
| 951 | [Fancy]URLopener constructor. |
| 952 | |
| 953 | """ |
| 954 | proxies = {} |
| 955 | for name, value in os.environ.items(): |
| 956 | name = string.lower(name) |
| 957 | if value and name[-6:] == '_proxy': |
| 958 | proxies[name[:-6]] = value |
| 959 | return proxies |
Guido van Rossum | 442e720 | 1996-03-20 15:33:11 +0000 | [diff] [blame] | 960 | |
| 961 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 962 | # Test and time quote() and unquote() |
| 963 | def test1(): |
| 964 | import time |
| 965 | s = '' |
| 966 | for i in range(256): s = s + chr(i) |
| 967 | s = s*4 |
| 968 | t0 = time.time() |
| 969 | qs = quote(s) |
| 970 | uqs = unquote(qs) |
| 971 | t1 = time.time() |
| 972 | if uqs != s: |
| 973 | print 'Wrong!' |
| 974 | print `s` |
| 975 | print `qs` |
| 976 | print `uqs` |
| 977 | print round(t1 - t0, 3), 'sec' |
| 978 | |
| 979 | |
| 980 | # Test program |
Guido van Rossum | 2349015 | 1998-06-25 02:39:00 +0000 | [diff] [blame] | 981 | def test(args=[]): |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 982 | if not args: |
| 983 | args = [ |
| 984 | '/etc/passwd', |
| 985 | 'file:/etc/passwd', |
| 986 | 'file://localhost/etc/passwd', |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 987 | 'ftp://ftp.python.org/etc/passwd', |
| 988 | 'gopher://gopher.micro.umn.edu/1/', |
| 989 | 'http://www.python.org/index.html', |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 990 | ] |
| 991 | try: |
| 992 | for url in args: |
| 993 | print '-'*10, url, '-'*10 |
| 994 | fn, h = urlretrieve(url) |
| 995 | print fn, h |
| 996 | if h: |
| 997 | print '======' |
| 998 | for k in h.keys(): print k + ':', h[k] |
| 999 | print '======' |
Guido van Rossum | c511aee | 1997-04-11 19:01:48 +0000 | [diff] [blame] | 1000 | fp = open(fn, 'rb') |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1001 | data = fp.read() |
| 1002 | del fp |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 1003 | if '\r' in data: |
Guido van Rossum | 7e7ca0b | 1998-03-26 21:01:39 +0000 | [diff] [blame] | 1004 | table = string.maketrans("", "") |
| 1005 | data = string.translate(data, table, "\r") |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 1006 | print data |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1007 | fn, h = None, None |
| 1008 | print '-'*40 |
| 1009 | finally: |
| 1010 | urlcleanup() |
| 1011 | |
Guido van Rossum | 2349015 | 1998-06-25 02:39:00 +0000 | [diff] [blame] | 1012 | def main(): |
| 1013 | import getopt, sys |
| 1014 | try: |
| 1015 | opts, args = getopt.getopt(sys.argv[1:], "th") |
| 1016 | except getopt.error, msg: |
| 1017 | print msg |
| 1018 | print "Use -h for help" |
| 1019 | return |
| 1020 | t = 0 |
| 1021 | for o, a in opts: |
| 1022 | if o == '-t': |
| 1023 | t = t + 1 |
| 1024 | if o == '-h': |
| 1025 | print "Usage: python urllib.py [-t] [url ...]" |
| 1026 | print "-t runs self-test;", |
| 1027 | print "otherwise, contents of urls are printed" |
| 1028 | return |
| 1029 | if t: |
| 1030 | if t > 1: |
| 1031 | test1() |
| 1032 | test(args) |
| 1033 | else: |
| 1034 | if not args: |
| 1035 | print "Use -h for help" |
| 1036 | for url in args: |
| 1037 | print urlopen(url).read(), |
| 1038 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1039 | # Run test program when run as a script |
| 1040 | if __name__ == '__main__': |
Guido van Rossum | 2349015 | 1998-06-25 02:39:00 +0000 | [diff] [blame] | 1041 | main() |