blob: dfed76edddf102e20037aafa33ef1b5b2ad8a895 [file] [log] [blame]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001# Open an arbitrary URL
2#
Guido van Rossum838cb281997-02-10 17:51:56 +00003# 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 Rossum7c6ebb51994-03-22 12:05:32 +000015#
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 Rossum838cb281997-02-10 17:51:56 +000020# The info() method returns a mimetools.Message object which can be
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000021# used to query various info about the object, if available.
Guido van Rossumbbb0a051995-08-04 04:29:05 +000022# (mimetools.Message objects are queried with the getheader() method.)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000023
Guido van Rossum7c395db1994-07-04 22:14:49 +000024import string
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000025import socket
Jack Jansendc3e3f61995-12-15 13:22:13 +000026import os
Guido van Rossum3c8484e1996-11-20 22:02:24 +000027import sys
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000028
29
Guido van Rossum8a666e71998-02-13 01:39:16 +000030__version__ = '1.10'
Guido van Rossumf668d171997-06-06 21:11:11 +000031
32MAXFTPCACHE = 10 # Trim the ftp cache beyond this size
Guido van Rossum6cb15a01995-06-22 19:00:13 +000033
Jack Jansendc3e3f61995-12-15 13:22:13 +000034# Helper for non-unix systems
35if os.name == 'mac':
Guido van Rossum71ac9451996-03-21 16:31:41 +000036 from macurl2path import url2pathname, pathname2url
Guido van Rossum2281d351996-06-26 19:47:37 +000037elif os.name == 'nt':
38 from nturl2path import url2pathname, pathname2url
Jack Jansendc3e3f61995-12-15 13:22:13 +000039else:
Jack Jansene8ea21b1995-12-21 15:43:53 +000040 def url2pathname(pathname):
Jack Jansendc3e3f61995-12-15 13:22:13 +000041 return pathname
Jack Jansene8ea21b1995-12-21 15:43:53 +000042 def pathname2url(pathname):
43 return pathname
Guido van Rossum6cb15a01995-06-22 19:00:13 +000044
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000045# 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 Rossumbd013741996-12-10 16:00:28 +000054def urlopen(url, data=None):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000055 global _urlopener
56 if not _urlopener:
Guido van Rossumbbb0a051995-08-04 04:29:05 +000057 _urlopener = FancyURLopener()
Guido van Rossumbd013741996-12-10 16:00:28 +000058 if data is None:
59 return _urlopener.open(url)
60 else:
61 return _urlopener.open(url, data)
Guido van Rossuma7e4b281996-06-11 00:16:27 +000062def urlretrieve(url, filename=None):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000063 global _urlopener
64 if not _urlopener:
Guido van Rossumbbb0a051995-08-04 04:29:05 +000065 _urlopener = FancyURLopener()
Guido van Rossuma7e4b281996-06-11 00:16:27 +000066 if filename:
67 return _urlopener.retrieve(url, filename)
68 else:
69 return _urlopener.retrieve(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000070def 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 Rossumbbb0a051995-08-04 04:29:05 +000078# 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 Rossum7c6ebb51994-03-22 12:05:32 +000081ftpcache = {}
82class URLopener:
83
Guido van Rossum036309b1997-10-27 18:56:19 +000084 __tempfiles = None
Guido van Rossum29e77811996-11-27 19:39:58 +000085
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000086 # Constructor
Guido van Rossum442e7201996-03-20 15:33:11 +000087 def __init__(self, proxies=None):
88 if proxies is None:
89 proxies = getproxies()
Guido van Rossum83600051997-11-18 15:50:39 +000090 assert hasattr(proxies, 'has_key'), "proxies must be a mapping"
Guido van Rossum442e7201996-03-20 15:33:11 +000091 self.proxies = proxies
Guido van Rossum6cb15a01995-06-22 19:00:13 +000092 server_version = "Python-urllib/%s" % __version__
93 self.addheaders = [('User-agent', server_version)]
Guido van Rossum10499321997-09-08 02:16:33 +000094 self.__tempfiles = []
Guido van Rossum036309b1997-10-27 18:56:19 +000095 self.__unlink = os.unlink # See cleanup()
Guido van Rossum7aeb4b91994-08-23 13:32:20 +000096 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 Rossum7c6ebb51994-03-22 12:05:32 +0000103 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
107
108 def __del__(self):
109 self.close()
110
111 def close(self):
112 self.cleanup()
113
114 def cleanup(self):
Guido van Rossum036309b1997-10-27 18:56:19 +0000115 # This code sometimes runs when the rest of this module
116 # has already been deleted, so it can't use any globals
117 # or import anything.
Guido van Rossum2b3fd761997-09-03 22:36:15 +0000118 if self.__tempfiles:
Guido van Rossum2b3fd761997-09-03 22:36:15 +0000119 for file in self.__tempfiles:
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000120 try:
Guido van Rossum036309b1997-10-27 18:56:19 +0000121 self.__unlink(file)
122 except:
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000123 pass
Guido van Rossum036309b1997-10-27 18:56:19 +0000124 del self.__tempfiles[:]
125 if self.tempcache:
126 self.tempcache.clear()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000127
128 # Add a header to be used by the HTTP interface only
129 # e.g. u.addheader('Accept', 'sound/basic')
130 def addheader(self, *args):
131 self.addheaders.append(args)
132
133 # External interface
134 # Use URLopener().open(file) instead of open(file, 'r')
Guido van Rossumbd013741996-12-10 16:00:28 +0000135 def open(self, fullurl, data=None):
Guido van Rossumca445401995-08-29 19:19:12 +0000136 fullurl = unwrap(fullurl)
Guido van Rossum03710d21998-02-05 16:22:27 +0000137 if self.tempcache and self.tempcache.has_key(fullurl):
138 filename, headers = self.tempcache[fullurl]
139 fp = open(filename, 'rb')
140 return addinfourl(fp, headers, fullurl)
Guido van Rossumca445401995-08-29 19:19:12 +0000141 type, url = splittype(fullurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000142 if not type: type = 'file'
Guido van Rossum442e7201996-03-20 15:33:11 +0000143 if self.proxies.has_key(type):
144 proxy = self.proxies[type]
145 type, proxy = splittype(proxy)
146 host, selector = splithost(proxy)
147 url = (host, fullurl) # Signal special case to open_*()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000148 name = 'open_' + type
149 if '-' in name:
Guido van Rossum332e1441997-09-29 23:23:46 +0000150 # replace - with _
151 name = string.join(string.split(name, '-'), '_')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000152 if not hasattr(self, name):
Guido van Rossumbd013741996-12-10 16:00:28 +0000153 if data is None:
154 return self.open_unknown(fullurl)
155 else:
156 return self.open_unknown(fullurl, data)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000157 try:
Guido van Rossumbd013741996-12-10 16:00:28 +0000158 if data is None:
159 return getattr(self, name)(url)
160 else:
161 return getattr(self, name)(url, data)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000162 except socket.error, msg:
Guido van Rossum332e1441997-09-29 23:23:46 +0000163 raise IOError, ('socket error', msg), sys.exc_info()[2]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000164
Guido van Rossumca445401995-08-29 19:19:12 +0000165 # Overridable interface to open unknown URL type
Guido van Rossumbd013741996-12-10 16:00:28 +0000166 def open_unknown(self, fullurl, data=None):
Guido van Rossumca445401995-08-29 19:19:12 +0000167 type, url = splittype(fullurl)
168 raise IOError, ('url error', 'unknown url type', type)
169
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000170 # External interface
171 # retrieve(url) returns (filename, None) for a local object
172 # or (tempfilename, headers) for a remote object
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000173 def retrieve(self, url, filename=None):
Guido van Rossum03710d21998-02-05 16:22:27 +0000174 url = unwrap(url)
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000175 if self.tempcache and self.tempcache.has_key(url):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000176 return self.tempcache[url]
Guido van Rossum03710d21998-02-05 16:22:27 +0000177 type, url1 = splittype(url)
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000178 if not filename and (not type or type == 'file'):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000179 try:
180 fp = self.open_local_file(url1)
181 del fp
Jack Jansene8ea21b1995-12-21 15:43:53 +0000182 return url2pathname(splithost(url1)[1]), None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000183 except IOError, msg:
184 pass
185 fp = self.open(url)
186 headers = fp.info()
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000187 if not filename:
188 import tempfile
189 filename = tempfile.mktemp()
Guido van Rossum2b3fd761997-09-03 22:36:15 +0000190 self.__tempfiles.append(filename)
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000191 result = filename, headers
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000192 if self.tempcache is not None:
Guido van Rossumfa59e831994-09-21 11:36:19 +0000193 self.tempcache[url] = result
Guido van Rossumc511aee1997-04-11 19:01:48 +0000194 tfp = open(filename, 'wb')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000195 bs = 1024*8
196 block = fp.read(bs)
197 while block:
198 tfp.write(block)
199 block = fp.read(bs)
Guido van Rossumab0abdc1997-08-26 19:06:40 +0000200 fp.close()
201 tfp.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000202 del fp
203 del tfp
204 return result
205
206 # Each method named open_<type> knows how to open that type of URL
207
208 # Use HTTP protocol
Guido van Rossumbd013741996-12-10 16:00:28 +0000209 def open_http(self, url, data=None):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000210 import httplib
Guido van Rossum442e7201996-03-20 15:33:11 +0000211 if type(url) is type(""):
212 host, selector = splithost(url)
Guido van Rossum78c96371996-08-26 18:09:59 +0000213 user_passwd, host = splituser(host)
Guido van Rossumc24751b1997-06-03 14:34:19 +0000214 realhost = host
Guido van Rossum442e7201996-03-20 15:33:11 +0000215 else:
216 host, selector = url
Guido van Rossum78c96371996-08-26 18:09:59 +0000217 urltype, rest = splittype(selector)
Guido van Rossumfd795661997-04-02 05:46:35 +0000218 user_passwd = None
Guido van Rossumc24751b1997-06-03 14:34:19 +0000219 if string.lower(urltype) != 'http':
220 realhost = None
221 else:
Guido van Rossum78c96371996-08-26 18:09:59 +0000222 realhost, rest = splithost(rest)
223 user_passwd, realhost = splituser(realhost)
224 if user_passwd:
225 selector = "%s://%s%s" % (urltype,
226 realhost, rest)
Guido van Rossumfd795661997-04-02 05:46:35 +0000227 #print "proxy via http:", host, selector
Guido van Rossum590b2891994-04-18 09:39:56 +0000228 if not host: raise IOError, ('http error', 'no host given')
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000229 if user_passwd:
230 import base64
231 auth = string.strip(base64.encodestring(user_passwd))
232 else:
233 auth = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000234 h = httplib.HTTP(host)
Guido van Rossumbd013741996-12-10 16:00:28 +0000235 if data is not None:
236 h.putrequest('POST', selector)
237 h.putheader('Content-type',
238 'application/x-www-form-urlencoded')
239 h.putheader('Content-length', '%d' % len(data))
240 else:
241 h.putrequest('GET', selector)
Guido van Rossumc5d7e801996-11-11 19:01:17 +0000242 if auth: h.putheader('Authorization', 'Basic %s' % auth)
Guido van Rossumc24751b1997-06-03 14:34:19 +0000243 if realhost: h.putheader('Host', realhost)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000244 for args in self.addheaders: apply(h.putheader, args)
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000245 h.endheaders()
Guido van Rossumbd013741996-12-10 16:00:28 +0000246 if data is not None:
247 h.send(data + '\r\n')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000248 errcode, errmsg, headers = h.getreply()
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000249 fp = h.getfile()
250 if errcode == 200:
Guido van Rossum8a666e71998-02-13 01:39:16 +0000251 return addinfourl(fp, headers, "http:" + url)
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000252 else:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000253 return self.http_error(url,
254 fp, errcode, errmsg, headers)
255
256 # Handle http errors.
257 # Derived class can override this, or provide specific handlers
258 # named http_error_DDD where DDD is the 3-digit error code
259 def http_error(self, url, fp, errcode, errmsg, headers):
260 # First check if there's a specific handler for this error
261 name = 'http_error_%d' % errcode
262 if hasattr(self, name):
263 method = getattr(self, name)
264 result = method(url, fp, errcode, errmsg, headers)
265 if result: return result
266 return self.http_error_default(
267 url, fp, errcode, errmsg, headers)
268
269 # Default http error handler: close the connection and raises IOError
270 def http_error_default(self, url, fp, errcode, errmsg, headers):
271 void = fp.read()
272 fp.close()
273 raise IOError, ('http error', errcode, errmsg, headers)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000274
275 # Use Gopher protocol
276 def open_gopher(self, url):
277 import gopherlib
278 host, selector = splithost(url)
Guido van Rossum590b2891994-04-18 09:39:56 +0000279 if not host: raise IOError, ('gopher error', 'no host given')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000280 type, selector = splitgophertype(selector)
281 selector, query = splitquery(selector)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000282 selector = unquote(selector)
283 if query:
284 query = unquote(query)
285 fp = gopherlib.send_query(selector, query, host)
286 else:
287 fp = gopherlib.send_selector(selector, host)
Guido van Rossum8a666e71998-02-13 01:39:16 +0000288 return addinfourl(fp, noheaders(), "gopher:" + url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000289
290 # Use local file or FTP depending on form of URL
291 def open_file(self, url):
Guido van Rossumb6784dc1997-08-20 23:34:01 +0000292 if url[:2] == '//' and url[2:3] != '/':
293 return self.open_ftp(url)
294 else:
295 return self.open_local_file(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000296
297 # Use local file
298 def open_local_file(self, url):
299 host, file = splithost(url)
Guido van Rossumb030bc01996-10-10 16:01:16 +0000300 if not host:
Guido van Rossum2966b321997-06-06 17:44:07 +0000301 return addinfourl(
302 open(url2pathname(file), 'rb'),
303 noheaders(), 'file:'+file)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000304 host, port = splitport(host)
305 if not port and socket.gethostbyname(host) in (
306 localhost(), thishost()):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000307 file = unquote(file)
Guido van Rossum2966b321997-06-06 17:44:07 +0000308 return addinfourl(
309 open(url2pathname(file), 'rb'),
310 noheaders(), 'file:'+file)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000311 raise IOError, ('local file error', 'not on local host')
312
313 # Use FTP protocol
314 def open_ftp(self, url):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000315 host, path = splithost(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000316 if not host: raise IOError, ('ftp error', 'no host given')
317 host, port = splitport(host)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000318 user, host = splituser(host)
319 if user: user, passwd = splitpasswd(user)
320 else: passwd = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000321 host = socket.gethostbyname(host)
322 if not port:
323 import ftplib
324 port = ftplib.FTP_PORT
Guido van Rossumc0f29c21997-12-02 20:26:21 +0000325 else:
326 port = int(port)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000327 path, attrs = splitattr(path)
328 dirs = string.splitfields(path, '/')
329 dirs, file = dirs[:-1], dirs[-1]
330 if dirs and not dirs[0]: dirs = dirs[1:]
331 key = (user, host, port, string.joinfields(dirs, '/'))
Guido van Rossumf668d171997-06-06 21:11:11 +0000332 if len(self.ftpcache) > MAXFTPCACHE:
333 # Prune the cache, rather arbitrarily
334 for k in self.ftpcache.keys():
335 if k != key:
336 v = self.ftpcache[k]
337 del self.ftpcache[k]
338 v.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000339 try:
340 if not self.ftpcache.has_key(key):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000341 self.ftpcache[key] = \
Guido van Rossum8a666e71998-02-13 01:39:16 +0000342 ftpwrapper(user, passwd,
343 host, port, dirs)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000344 if not file: type = 'D'
345 else: type = 'I'
346 for attr in attrs:
347 attr, value = splitvalue(attr)
348 if string.lower(attr) == 'type' and \
349 value in ('a', 'A', 'i', 'I', 'd', 'D'):
350 type = string.upper(value)
Guido van Rossum2966b321997-06-06 17:44:07 +0000351 return addinfourl(
352 self.ftpcache[key].retrfile(file, type),
Guido van Rossum8a666e71998-02-13 01:39:16 +0000353 noheaders(), "ftp:" + url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000354 except ftperrors(), msg:
Guido van Rossum332e1441997-09-29 23:23:46 +0000355 raise IOError, ('ftp error', msg), sys.exc_info()[2]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000356
Guido van Rossum6d4d1c21998-03-12 14:32:55 +0000357 # Use "data" URL
358 def open_data(self, url, data=None):
359 # ignore POSTed data
360 #
361 # syntax of data URLs:
362 # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
363 # mediatype := [ type "/" subtype ] *( ";" parameter )
364 # data := *urlchar
365 # parameter := attribute "=" value
366 import StringIO, mimetools, time
367 try:
368 [type, data] = string.split(url, ',', 1)
369 except ValueError:
370 raise IOError, ('data error', 'bad data URL')
371 if not type:
372 type = 'text/plain;charset=US-ASCII'
373 semi = string.rfind(type, ';')
374 if semi >= 0 and '=' not in type[semi:]:
375 encoding = type[semi+1:]
376 type = type[:semi]
377 else:
378 encoding = ''
379 msg = []
380 msg.append('Date: %s'%time.strftime('%a, %d %b %Y %T GMT',
381 time.gmtime(time.time())))
382 msg.append('Content-type: %s' % type)
383 if encoding == 'base64':
384 import base64
385 data = base64.decodestring(data)
386 else:
387 data = unquote(data)
388 msg.append('Content-length: %d' % len(data))
389 msg.append('')
390 msg.append(data)
391 msg = string.join(msg, '\n')
392 f = StringIO.StringIO(msg)
393 headers = mimetools.Message(f, 0)
394 f.fileno = None # needed for addinfourl
395 return addinfourl(f, headers, url)
396
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000397
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000398# Derived class with handlers for errors we can handle (perhaps)
399class FancyURLopener(URLopener):
400
401 def __init__(self, *args):
402 apply(URLopener.__init__, (self,) + args)
403 self.auth_cache = {}
404
405 # Default error handling -- don't raise an exception
406 def http_error_default(self, url, fp, errcode, errmsg, headers):
Guido van Rossum8a666e71998-02-13 01:39:16 +0000407 return addinfourl(fp, headers, "http:" + url)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000408
Guido van Rossume6ad8911996-09-10 17:02:56 +0000409 # Error 302 -- relocated (temporarily)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000410 def http_error_302(self, url, fp, errcode, errmsg, headers):
411 # XXX The server can force infinite recursion here!
412 if headers.has_key('location'):
413 newurl = headers['location']
414 elif headers.has_key('uri'):
415 newurl = headers['uri']
416 else:
417 return
418 void = fp.read()
419 fp.close()
420 return self.open(newurl)
421
Guido van Rossume6ad8911996-09-10 17:02:56 +0000422 # Error 301 -- also relocated (permanently)
423 http_error_301 = http_error_302
424
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000425 # Error 401 -- authentication required
426 # See this URL for a description of the basic authentication scheme:
427 # http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt
428 def http_error_401(self, url, fp, errcode, errmsg, headers):
429 if headers.has_key('www-authenticate'):
430 stuff = headers['www-authenticate']
Guido van Rossum332e1441997-09-29 23:23:46 +0000431 import re
432 match = re.match(
433 '[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
434 if match:
Guido van Rossumc5d8fed1998-02-05 16:21:28 +0000435 scheme, realm = match.groups()
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000436 if string.lower(scheme) == 'basic':
437 return self.retry_http_basic_auth(
438 url, realm)
439
440 def retry_http_basic_auth(self, url, realm):
441 host, selector = splithost(url)
442 i = string.find(host, '@') + 1
443 host = host[i:]
444 user, passwd = self.get_user_passwd(host, realm, i)
445 if not (user or passwd): return None
446 host = user + ':' + passwd + '@' + host
447 newurl = '//' + host + selector
448 return self.open_http(newurl)
449
450 def get_user_passwd(self, host, realm, clear_cache = 0):
451 key = realm + '@' + string.lower(host)
452 if self.auth_cache.has_key(key):
453 if clear_cache:
454 del self.auth_cache[key]
455 else:
456 return self.auth_cache[key]
457 user, passwd = self.prompt_user_passwd(host, realm)
458 if user or passwd: self.auth_cache[key] = (user, passwd)
459 return user, passwd
460
461 def prompt_user_passwd(self, host, realm):
462 # Override this in a GUI environment!
463 try:
464 user = raw_input("Enter username for %s at %s: " %
465 (realm, host))
466 self.echo_off()
467 try:
468 passwd = raw_input(
469 "Enter password for %s in %s at %s: " %
470 (user, realm, host))
471 finally:
472 self.echo_on()
473 return user, passwd
474 except KeyboardInterrupt:
475 return None, None
476
477 def echo_off(self):
Guido van Rossumc5d8fed1998-02-05 16:21:28 +0000478 # XXX Is this sufficient???
479 if hasattr(os, "system"):
480 os.system("stty -echo")
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000481
482 def echo_on(self):
Guido van Rossumc5d8fed1998-02-05 16:21:28 +0000483 # XXX Is this sufficient???
484 if hasattr(os, "system"):
485 print
486 os.system("stty echo")
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000487
488
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000489# Utility functions
490
491# Return the IP address of the magic hostname 'localhost'
492_localhost = None
493def localhost():
494 global _localhost
495 if not _localhost:
496 _localhost = socket.gethostbyname('localhost')
497 return _localhost
498
499# Return the IP address of the current host
500_thishost = None
501def thishost():
502 global _thishost
503 if not _thishost:
504 _thishost = socket.gethostbyname(socket.gethostname())
505 return _thishost
506
507# Return the set of errors raised by the FTP class
508_ftperrors = None
509def ftperrors():
510 global _ftperrors
511 if not _ftperrors:
512 import ftplib
Guido van Rossum2966b321997-06-06 17:44:07 +0000513 _ftperrors = ftplib.all_errors
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000514 return _ftperrors
515
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000516# Return an empty mimetools.Message object
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000517_noheaders = None
518def noheaders():
519 global _noheaders
520 if not _noheaders:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000521 import mimetools
522 import StringIO
523 _noheaders = mimetools.Message(StringIO.StringIO(), 0)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000524 _noheaders.fp.close() # Recycle file descriptor
525 return _noheaders
526
527
528# Utility classes
529
530# Class used by open_ftp() for cache of open FTP connections
531class ftpwrapper:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000532 def __init__(self, user, passwd, host, port, dirs):
533 self.user = unquote(user or '')
534 self.passwd = unquote(passwd or '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000535 self.host = host
536 self.port = port
Guido van Rossum7c395db1994-07-04 22:14:49 +0000537 self.dirs = []
538 for dir in dirs:
539 self.dirs.append(unquote(dir))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000540 self.init()
541 def init(self):
542 import ftplib
Guido van Rossumd4990041997-12-28 04:21:20 +0000543 self.busy = 0
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000544 self.ftp = ftplib.FTP()
545 self.ftp.connect(self.host, self.port)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000546 self.ftp.login(self.user, self.passwd)
547 for dir in self.dirs:
548 self.ftp.cwd(dir)
549 def retrfile(self, file, type):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000550 import ftplib
Guido van Rossumd4990041997-12-28 04:21:20 +0000551 self.endtransfer()
Guido van Rossum7c395db1994-07-04 22:14:49 +0000552 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
553 else: cmd = 'TYPE ' + type; isdir = 0
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000554 try:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000555 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000556 except ftplib.all_errors:
557 self.init()
Guido van Rossum7c395db1994-07-04 22:14:49 +0000558 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000559 conn = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000560 if file and not isdir:
Guido van Rossumd4990041997-12-28 04:21:20 +0000561 # Use nlst to see if the file exists at all
562 try:
563 self.ftp.nlst(file)
564 except ftplib.error_perm, reason:
565 raise IOError, ('ftp error', reason), \
566 sys.exc_info()[2]
Guido van Rossume7579621998-01-19 22:26:54 +0000567 # Restore the transfer mode!
568 self.ftp.voidcmd(cmd)
Guido van Rossumd4990041997-12-28 04:21:20 +0000569 # Try to retrieve as a file
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000570 try:
571 cmd = 'RETR ' + file
572 conn = self.ftp.transfercmd(cmd)
573 except ftplib.error_perm, reason:
574 if reason[:3] != '550':
Guido van Rossum3c8484e1996-11-20 22:02:24 +0000575 raise IOError, ('ftp error', reason), \
Guido van Rossum332e1441997-09-29 23:23:46 +0000576 sys.exc_info()[2]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000577 if not conn:
Guido van Rossume7579621998-01-19 22:26:54 +0000578 # Set transfer mode to ASCII!
579 self.ftp.voidcmd('TYPE A')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000580 # Try a directory listing
581 if file: cmd = 'LIST ' + file
582 else: cmd = 'LIST'
583 conn = self.ftp.transfercmd(cmd)
Guido van Rossumd4990041997-12-28 04:21:20 +0000584 self.busy = 1
Guido van Rossumf668d171997-06-06 21:11:11 +0000585 return addclosehook(conn.makefile('rb'), self.endtransfer)
586 def endtransfer(self):
Guido van Rossumd4990041997-12-28 04:21:20 +0000587 if not self.busy:
588 return
589 self.busy = 0
Guido van Rossumf668d171997-06-06 21:11:11 +0000590 try:
591 self.ftp.voidresp()
592 except ftperrors():
593 pass
594 def close(self):
Guido van Rossumd4990041997-12-28 04:21:20 +0000595 self.endtransfer()
Guido van Rossumf668d171997-06-06 21:11:11 +0000596 try:
597 self.ftp.close()
598 except ftperrors():
599 pass
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000600
601# Base class for addinfo and addclosehook
602class addbase:
603 def __init__(self, fp):
604 self.fp = fp
605 self.read = self.fp.read
606 self.readline = self.fp.readline
607 self.readlines = self.fp.readlines
608 self.fileno = self.fp.fileno
609 def __repr__(self):
610 return '<%s at %s whose fp = %s>' % (
611 self.__class__.__name__, `id(self)`, `self.fp`)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000612 def close(self):
613 self.read = None
614 self.readline = None
615 self.readlines = None
616 self.fileno = None
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000617 if self.fp: self.fp.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000618 self.fp = None
619
620# Class to add a close hook to an open file
621class addclosehook(addbase):
622 def __init__(self, fp, closehook, *hookargs):
623 addbase.__init__(self, fp)
624 self.closehook = closehook
625 self.hookargs = hookargs
626 def close(self):
627 if self.closehook:
628 apply(self.closehook, self.hookargs)
629 self.closehook = None
630 self.hookargs = None
631 addbase.close(self)
632
633# class to add an info() method to an open file
634class addinfo(addbase):
635 def __init__(self, fp, headers):
636 addbase.__init__(self, fp)
637 self.headers = headers
638 def info(self):
639 return self.headers
640
Guido van Rossume6ad8911996-09-10 17:02:56 +0000641# class to add info() and geturl() methods to an open file
642class addinfourl(addbase):
643 def __init__(self, fp, headers, url):
644 addbase.__init__(self, fp)
645 self.headers = headers
646 self.url = url
647 def info(self):
648 return self.headers
649 def geturl(self):
650 return self.url
651
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000652
653# Utility to combine a URL with a base URL to form a new URL
654
655def basejoin(base, url):
656 type, path = splittype(url)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000657 if type:
658 # if url is complete (i.e., it contains a type), return it
659 return url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000660 host, path = splithost(path)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000661 type, basepath = splittype(base) # inherit type from base
662 if host:
663 # if url contains host, just inherit type
664 if type: return type + '://' + host + path
665 else:
666 # no type inherited, so url must have started with //
667 # just return it
668 return url
669 host, basepath = splithost(basepath) # inherit host
670 basepath, basetag = splittag(basepath) # remove extraneuous cruft
671 basepath, basequery = splitquery(basepath) # idem
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000672 if path[:1] != '/':
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000673 # non-absolute path name
674 if path[:1] in ('#', '?'):
675 # path is just a tag or query, attach to basepath
676 i = len(basepath)
677 else:
678 # else replace last component
679 i = string.rfind(basepath, '/')
680 if i < 0:
681 # basepath not absolute
682 if host:
683 # host present, make absolute
684 basepath = '/'
685 else:
686 # else keep non-absolute
687 basepath = ''
688 else:
689 # remove last file component
690 basepath = basepath[:i+1]
Guido van Rossum54a1d0b1997-04-11 19:09:51 +0000691 # Interpret ../ (important because of symlinks)
692 while basepath and path[:3] == '../':
693 path = path[3:]
Guido van Rossum2b3fd761997-09-03 22:36:15 +0000694 i = string.rfind(basepath[:-1], '/')
Guido van Rossum54a1d0b1997-04-11 19:09:51 +0000695 if i > 0:
Guido van Rossum2b3fd761997-09-03 22:36:15 +0000696 basepath = basepath[:i+1]
697 elif i == 0:
698 basepath = '/'
699 break
700 else:
701 basepath = ''
Guido van Rossum54a1d0b1997-04-11 19:09:51 +0000702
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000703 path = basepath + path
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000704 if type and host: return type + '://' + host + path
705 elif type: return type + ':' + path
706 elif host: return '//' + host + path # don't know what this means
707 else: return path
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000708
709
Guido van Rossum7c395db1994-07-04 22:14:49 +0000710# Utilities to parse URLs (most of these return None for missing parts):
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000711# unwrap('<URL:type://host/path>') --> 'type://host/path'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000712# splittype('type:opaquestring') --> 'type', 'opaquestring'
713# splithost('//host[:port]/path') --> 'host[:port]', '/path'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000714# splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'
715# splitpasswd('user:passwd') -> 'user', 'passwd'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000716# splitport('host:port') --> 'host', 'port'
717# splitquery('/path?query') --> '/path', 'query'
718# splittag('/path#tag') --> '/path', 'tag'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000719# splitattr('/path;attr1=value1;attr2=value2;...') ->
720# '/path', ['attr1=value1', 'attr2=value2', ...]
721# splitvalue('attr=value') --> 'attr', 'value'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000722# splitgophertype('/Xselector') --> 'X', 'selector'
723# unquote('abc%20def') -> 'abc def'
724# quote('abc def') -> 'abc%20def')
725
726def unwrap(url):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000727 url = string.strip(url)
728 if url[:1] == '<' and url[-1:] == '>':
729 url = string.strip(url[1:-1])
730 if url[:4] == 'URL:': url = string.strip(url[4:])
731 return url
732
Guido van Rossum332e1441997-09-29 23:23:46 +0000733_typeprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000734def splittype(url):
Guido van Rossum332e1441997-09-29 23:23:46 +0000735 global _typeprog
736 if _typeprog is None:
737 import re
738 _typeprog = re.compile('^([^/:]+):')
739
740 match = _typeprog.match(url)
741 if match:
742 scheme = match.group(1)
Guido van Rossumab0d1af1997-04-16 15:17:06 +0000743 return scheme, url[len(scheme) + 1:]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000744 return None, url
745
Guido van Rossum332e1441997-09-29 23:23:46 +0000746_hostprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000747def splithost(url):
Guido van Rossum332e1441997-09-29 23:23:46 +0000748 global _hostprog
749 if _hostprog is None:
750 import re
751 _hostprog = re.compile('^//([^/]+)(.*)$')
752
753 match = _hostprog.match(url)
754 if match: return match.group(1, 2)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000755 return None, url
756
Guido van Rossum332e1441997-09-29 23:23:46 +0000757_userprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000758def splituser(host):
Guido van Rossum332e1441997-09-29 23:23:46 +0000759 global _userprog
760 if _userprog is None:
761 import re
762 _userprog = re.compile('^([^@]*)@(.*)$')
763
764 match = _userprog.match(host)
765 if match: return match.group(1, 2)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000766 return None, host
767
Guido van Rossum332e1441997-09-29 23:23:46 +0000768_passwdprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000769def splitpasswd(user):
Guido van Rossum332e1441997-09-29 23:23:46 +0000770 global _passwdprog
771 if _passwdprog is None:
772 import re
773 _passwdprog = re.compile('^([^:]*):(.*)$')
774
Fred Drake654451d1997-10-14 13:30:57 +0000775 match = _passwdprog.match(user)
Guido van Rossum332e1441997-09-29 23:23:46 +0000776 if match: return match.group(1, 2)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000777 return user, None
778
Guido van Rossum332e1441997-09-29 23:23:46 +0000779_portprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000780def splitport(host):
Guido van Rossum332e1441997-09-29 23:23:46 +0000781 global _portprog
782 if _portprog is None:
783 import re
784 _portprog = re.compile('^(.*):([0-9]+)$')
785
786 match = _portprog.match(host)
787 if match: return match.group(1, 2)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000788 return host, None
789
Guido van Rossum53725a21996-06-13 19:12:35 +0000790# Split host and port, returning numeric port.
791# Return given default port if no ':' found; defaults to -1.
Guido van Rossum84a00a81996-06-17 17:11:40 +0000792# Return numerical port if a valid number are found after ':'.
793# Return None if ':' but not a valid number.
Guido van Rossum332e1441997-09-29 23:23:46 +0000794_nportprog = None
Guido van Rossum53725a21996-06-13 19:12:35 +0000795def splitnport(host, defport=-1):
Guido van Rossum332e1441997-09-29 23:23:46 +0000796 global _nportprog
797 if _nportprog is None:
798 import re
799 _nportprog = re.compile('^(.*):(.*)$')
800
801 match = _nportprog.match(host)
802 if match:
803 host, port = match.group(1, 2)
Guido van Rossum84a00a81996-06-17 17:11:40 +0000804 try:
805 if not port: raise string.atoi_error, "no digits"
806 nport = string.atoi(port)
807 except string.atoi_error:
808 nport = None
Guido van Rossum53725a21996-06-13 19:12:35 +0000809 return host, nport
810 return host, defport
811
Guido van Rossum332e1441997-09-29 23:23:46 +0000812_queryprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000813def splitquery(url):
Guido van Rossum332e1441997-09-29 23:23:46 +0000814 global _queryprog
815 if _queryprog is None:
816 import re
817 _queryprog = re.compile('^(.*)\?([^?]*)$')
818
819 match = _queryprog.match(url)
820 if match: return match.group(1, 2)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000821 return url, None
822
Guido van Rossum332e1441997-09-29 23:23:46 +0000823_tagprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000824def splittag(url):
Guido van Rossum332e1441997-09-29 23:23:46 +0000825 global _tagprog
826 if _tagprog is None:
827 import re
828 _tagprog = re.compile('^(.*)#([^#]*)$')
829
830 match = _tagprog.match(url)
831 if match: return match.group(1, 2)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000832 return url, None
833
Guido van Rossum7c395db1994-07-04 22:14:49 +0000834def splitattr(url):
835 words = string.splitfields(url, ';')
836 return words[0], words[1:]
837
Guido van Rossum332e1441997-09-29 23:23:46 +0000838_valueprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000839def splitvalue(attr):
Guido van Rossum332e1441997-09-29 23:23:46 +0000840 global _valueprog
841 if _valueprog is None:
842 import re
843 _valueprog = re.compile('^([^=]*)=(.*)$')
844
845 match = _valueprog.match(attr)
846 if match: return match.group(1, 2)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000847 return attr, None
848
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000849def splitgophertype(selector):
850 if selector[:1] == '/' and selector[1:2]:
851 return selector[1], selector[2:]
852 return None, selector
853
Guido van Rossum332e1441997-09-29 23:23:46 +0000854_quoteprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000855def unquote(s):
Guido van Rossum332e1441997-09-29 23:23:46 +0000856 global _quoteprog
857 if _quoteprog is None:
858 import re
859 _quoteprog = re.compile('%[0-9a-fA-F][0-9a-fA-F]')
860
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000861 i = 0
862 n = len(s)
Guido van Rossumf8abb381996-08-26 15:56:12 +0000863 res = []
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000864 while 0 <= i < n:
Guido van Rossum332e1441997-09-29 23:23:46 +0000865 match = _quoteprog.search(s, i)
866 if not match:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000867 res.append(s[i:])
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000868 break
Guido van Rossum332e1441997-09-29 23:23:46 +0000869 j = match.start(0)
Guido van Rossumf8abb381996-08-26 15:56:12 +0000870 res.append(s[i:j] + chr(string.atoi(s[j+1:j+3], 16)))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000871 i = j+3
Guido van Rossumf8abb381996-08-26 15:56:12 +0000872 return string.joinfields(res, '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000873
Guido van Rossum0564e121996-12-13 14:47:36 +0000874def unquote_plus(s):
875 if '+' in s:
Guido van Rossum332e1441997-09-29 23:23:46 +0000876 # replace '+' with ' '
877 s = string.join(string.split(s, '+'), ' ')
Guido van Rossum0564e121996-12-13 14:47:36 +0000878 return unquote(s)
879
Guido van Rossum3bb54481994-08-29 10:52:58 +0000880always_safe = string.letters + string.digits + '_,.-'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000881def quote(s, safe = '/'):
882 safe = always_safe + safe
Guido van Rossumf8abb381996-08-26 15:56:12 +0000883 res = []
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000884 for c in s:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000885 if c in safe:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000886 res.append(c)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000887 else:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000888 res.append('%%%02x' % ord(c))
889 return string.joinfields(res, '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000890
Guido van Rossum0564e121996-12-13 14:47:36 +0000891def quote_plus(s, safe = '/'):
892 if ' ' in s:
Guido van Rossum332e1441997-09-29 23:23:46 +0000893 # replace ' ' with '+'
894 s = string.join(string.split(s, ' '), '+')
Guido van Rossum0564e121996-12-13 14:47:36 +0000895 return quote(s, safe + '+')
896 else:
897 return quote(s, safe)
898
Guido van Rossum442e7201996-03-20 15:33:11 +0000899
900# Proxy handling
901def getproxies():
902 """Return a dictionary of protocol scheme -> proxy server URL mappings.
903
904 Scan the environment for variables named <scheme>_proxy;
905 this seems to be the standard convention. If you need a
906 different way, you can pass a proxies dictionary to the
907 [Fancy]URLopener constructor.
908
909 """
910 proxies = {}
911 for name, value in os.environ.items():
Guido van Rossum1aec3f01997-05-28 15:37:19 +0000912 name = string.lower(name)
Guido van Rossum442e7201996-03-20 15:33:11 +0000913 if value and name[-6:] == '_proxy':
914 proxies[name[:-6]] = value
915 return proxies
916
917
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000918# Test and time quote() and unquote()
919def test1():
920 import time
921 s = ''
922 for i in range(256): s = s + chr(i)
923 s = s*4
924 t0 = time.time()
925 qs = quote(s)
926 uqs = unquote(qs)
927 t1 = time.time()
928 if uqs != s:
929 print 'Wrong!'
930 print `s`
931 print `qs`
932 print `uqs`
933 print round(t1 - t0, 3), 'sec'
934
935
936# Test program
937def test():
938 import sys
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000939 args = sys.argv[1:]
940 if not args:
941 args = [
942 '/etc/passwd',
943 'file:/etc/passwd',
944 'file://localhost/etc/passwd',
Guido van Rossum332e1441997-09-29 23:23:46 +0000945 'ftp://ftp.python.org/etc/passwd',
946 'gopher://gopher.micro.umn.edu/1/',
947 'http://www.python.org/index.html',
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000948 ]
949 try:
950 for url in args:
951 print '-'*10, url, '-'*10
952 fn, h = urlretrieve(url)
953 print fn, h
954 if h:
955 print '======'
956 for k in h.keys(): print k + ':', h[k]
957 print '======'
Guido van Rossumc511aee1997-04-11 19:01:48 +0000958 fp = open(fn, 'rb')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000959 data = fp.read()
960 del fp
Guido van Rossum332e1441997-09-29 23:23:46 +0000961 if '\r' in data:
962 table = string.maketrans("", "")
963 data = string.translate(data, table, "\r")
964 print data
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000965 fn, h = None, None
966 print '-'*40
967 finally:
968 urlcleanup()
969
970# Run test program when run as a script
971if __name__ == '__main__':
Guido van Rossum332e1441997-09-29 23:23:46 +0000972 test1()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000973 test()