blob: ffbab2264d6f311d3170e91a843c272739822558 [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 Rossum09c8b6c1999-12-07 21:37:17 +000030__version__ = '1.12' # XXX This version is not always updated :-(
Guido van Rossumf668d171997-06-06 21:11:11 +000031
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000032MAXFTPCACHE = 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':
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000036 from macurl2path import url2pathname, pathname2url
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +000037elif os.name == 'nt':
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000038 from nturl2path import url2pathname, pathname2url
Jack Jansendc3e3f61995-12-15 13:22:13 +000039else:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000040 def url2pathname(pathname):
Guido van Rossum367ac801999-03-12 14:31:10 +000041 return unquote(pathname)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000042 def pathname2url(pathname):
Guido van Rossum367ac801999-03-12 14:31:10 +000043 return quote(pathname)
Guido van Rossum33add0a1998-12-18 15:25:22 +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):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000055 global _urlopener
56 if not _urlopener:
57 _urlopener = FancyURLopener()
58 if data is None:
59 return _urlopener.open(url)
60 else:
61 return _urlopener.open(url, data)
Guido van Rossum9ab96d41998-09-28 14:07:00 +000062def urlretrieve(url, filename=None, reporthook=None):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000063 global _urlopener
64 if not _urlopener:
65 _urlopener = FancyURLopener()
66 return _urlopener.retrieve(url, filename, reporthook)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000067def urlcleanup():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000068 if _urlopener:
69 _urlopener.cleanup()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000070
71
72# Class to open URLs.
73# This is a class rather than just a subroutine because we may need
74# more than one set of global protocol-specific options.
Guido van Rossumbbb0a051995-08-04 04:29:05 +000075# Note -- this is a base class for those who don't want the
76# automatic handling of errors type 302 (relocated) and 401
77# (authorization needed).
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000078ftpcache = {}
79class URLopener:
80
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000081 __tempfiles = None
Guido van Rossum29e77811996-11-27 19:39:58 +000082
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000083 # Constructor
Guido van Rossum09c8b6c1999-12-07 21:37:17 +000084 def __init__(self, proxies=None, **x509):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000085 if proxies is None:
86 proxies = getproxies()
87 assert hasattr(proxies, 'has_key'), "proxies must be a mapping"
88 self.proxies = proxies
Guido van Rossum09c8b6c1999-12-07 21:37:17 +000089 self.key_file = x509.get('key_file')
90 self.cert_file = x509.get('cert_file')
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000091 server_version = "Python-urllib/%s" % __version__
92 self.addheaders = [('User-agent', server_version)]
93 self.__tempfiles = []
94 self.__unlink = os.unlink # See cleanup()
95 self.tempcache = None
96 # Undocumented feature: if you assign {} to tempcache,
97 # it is used to cache files retrieved with
98 # self.retrieve(). This is not enabled by default
99 # since it does not work for changing documents (and I
100 # haven't got the logic to check expiration headers
101 # yet).
102 self.ftpcache = ftpcache
103 # Undocumented feature: you can use a different
104 # ftp cache by assigning to the .ftpcache member;
105 # in case you want logically independent URL openers
106 # XXX This is not threadsafe. Bah.
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000107
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000108 def __del__(self):
109 self.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000110
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000111 def close(self):
112 self.cleanup()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000113
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000114 def cleanup(self):
115 # 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.
118 if self.__tempfiles:
119 for file in self.__tempfiles:
120 try:
121 self.__unlink(file)
122 except:
123 pass
124 del self.__tempfiles[:]
125 if self.tempcache:
126 self.tempcache.clear()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000127
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000128 # 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)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000132
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000133 # External interface
134 # Use URLopener().open(file) instead of open(file, 'r')
135 def open(self, fullurl, data=None):
136 fullurl = unwrap(fullurl)
137 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)
141 type, url = splittype(fullurl)
142 if not type: type = 'file'
143 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_*()
148 name = 'open_' + type
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000149 self.type = type
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000150 if '-' in name:
151 # replace - with _
152 name = string.join(string.split(name, '-'), '_')
153 if not hasattr(self, name):
154 if data is None:
155 return self.open_unknown(fullurl)
156 else:
157 return self.open_unknown(fullurl, data)
158 try:
159 if data is None:
160 return getattr(self, name)(url)
161 else:
162 return getattr(self, name)(url, data)
163 except socket.error, msg:
164 raise IOError, ('socket error', msg), sys.exc_info()[2]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000165
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000166 # Overridable interface to open unknown URL type
167 def open_unknown(self, fullurl, data=None):
168 type, url = splittype(fullurl)
169 raise IOError, ('url error', 'unknown url type', type)
Guido van Rossumca445401995-08-29 19:19:12 +0000170
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000171 # External interface
172 # retrieve(url) returns (filename, None) for a local object
173 # or (tempfilename, headers) for a remote object
174 def retrieve(self, url, filename=None, reporthook=None):
175 url = unwrap(url)
176 if self.tempcache and self.tempcache.has_key(url):
177 return self.tempcache[url]
178 type, url1 = splittype(url)
179 if not filename and (not type or type == 'file'):
180 try:
181 fp = self.open_local_file(url1)
182 hdrs = fp.info()
183 del fp
184 return url2pathname(splithost(url1)[1]), hdrs
185 except IOError, msg:
186 pass
187 fp = self.open(url)
188 headers = fp.info()
189 if not filename:
190 import tempfile
191 garbage, path = splittype(url)
192 garbage, path = splithost(path or "")
193 path, garbage = splitquery(path or "")
194 path, garbage = splitattr(path or "")
195 suffix = os.path.splitext(path)[1]
196 filename = tempfile.mktemp(suffix)
197 self.__tempfiles.append(filename)
198 result = filename, headers
199 if self.tempcache is not None:
200 self.tempcache[url] = result
201 tfp = open(filename, 'wb')
202 bs = 1024*8
203 size = -1
204 blocknum = 1
205 if reporthook:
206 if headers.has_key("content-length"):
207 size = int(headers["Content-Length"])
208 reporthook(0, bs, size)
209 block = fp.read(bs)
210 if reporthook:
211 reporthook(1, bs, size)
212 while block:
213 tfp.write(block)
214 block = fp.read(bs)
215 blocknum = blocknum + 1
216 if reporthook:
217 reporthook(blocknum, bs, size)
218 fp.close()
219 tfp.close()
220 del fp
221 del tfp
222 return result
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000223
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000224 # Each method named open_<type> knows how to open that type of URL
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000225
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000226 # Use HTTP protocol
227 def open_http(self, url, data=None):
228 import httplib
229 user_passwd = None
230 if type(url) is type(""):
231 host, selector = splithost(url)
232 if host:
233 user_passwd, host = splituser(host)
234 host = unquote(host)
235 realhost = host
236 else:
237 host, selector = url
238 urltype, rest = splittype(selector)
239 url = rest
240 user_passwd = None
241 if string.lower(urltype) != 'http':
242 realhost = None
243 else:
244 realhost, rest = splithost(rest)
245 if realhost:
246 user_passwd, realhost = splituser(realhost)
247 if user_passwd:
248 selector = "%s://%s%s" % (urltype, realhost, rest)
249 #print "proxy via http:", host, selector
250 if not host: raise IOError, ('http error', 'no host given')
251 if user_passwd:
252 import base64
253 auth = string.strip(base64.encodestring(user_passwd))
254 else:
255 auth = None
256 h = httplib.HTTP(host)
257 if data is not None:
258 h.putrequest('POST', selector)
259 h.putheader('Content-type', 'application/x-www-form-urlencoded')
260 h.putheader('Content-length', '%d' % len(data))
261 else:
262 h.putrequest('GET', selector)
263 if auth: h.putheader('Authorization', 'Basic %s' % auth)
264 if realhost: h.putheader('Host', realhost)
265 for args in self.addheaders: apply(h.putheader, args)
266 h.endheaders()
267 if data is not None:
268 h.send(data + '\r\n')
269 errcode, errmsg, headers = h.getreply()
270 fp = h.getfile()
271 if errcode == 200:
272 return addinfourl(fp, headers, "http:" + url)
273 else:
274 if data is None:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000275 return self.http_error(url, fp, errcode, errmsg, headers)
Guido van Rossum29aab751999-03-09 19:31:21 +0000276 else:
277 return self.http_error(url, fp, errcode, errmsg, headers, data)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000278
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000279 # Handle http errors.
280 # Derived class can override this, or provide specific handlers
281 # named http_error_DDD where DDD is the 3-digit error code
282 def http_error(self, url, fp, errcode, errmsg, headers, data=None):
283 # First check if there's a specific handler for this error
284 name = 'http_error_%d' % errcode
285 if hasattr(self, name):
286 method = getattr(self, name)
287 if data is None:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000288 result = method(url, fp, errcode, errmsg, headers)
Jeremy Hyltonb30f52a1999-02-25 16:14:58 +0000289 else:
290 result = method(url, fp, errcode, errmsg, headers, data)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000291 if result: return result
Jeremy Hyltonb30f52a1999-02-25 16:14:58 +0000292 return self.http_error_default(url, fp, errcode, errmsg, headers)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000293
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000294 # Default http error handler: close the connection and raises IOError
295 def http_error_default(self, url, fp, errcode, errmsg, headers):
296 void = fp.read()
297 fp.close()
298 raise IOError, ('http error', errcode, errmsg, headers)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000299
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000300 # Use HTTPS protocol
301 if hasattr(socket, "ssl"):
302 def open_https(self, url):
303 import httplib
304 if type(url) is type(""):
305 host, selector = splithost(url)
306 user_passwd, host = splituser(host)
307 else:
308 host, selector = url
309 urltype, rest = splittype(selector)
310 if string.lower(urltype) == 'https':
311 realhost, rest = splithost(rest)
312 user_passwd, realhost = splituser(realhost)
313 if user_passwd:
314 selector = "%s://%s%s" % (urltype, realhost, rest)
315 print "proxy via https:", host, selector
316 if not host: raise IOError, ('https error', 'no host given')
317 if user_passwd:
318 import base64
319 auth = string.strip(base64.encodestring(user_passwd))
320 else:
321 auth = None
322 h = httplib.HTTPS(host, 0,
323 key_file=self.key_file,
324 cert_file=self.cert_file)
325 h.putrequest('GET', selector)
326 if auth: h.putheader('Authorization: Basic %s' % auth)
327 for args in self.addheaders: apply(h.putheader, args)
328 h.endheaders()
329 errcode, errmsg, headers = h.getreply()
330 fp = h.getfile()
331 if errcode == 200:
332 return addinfourl(fp, headers, url)
333 else:
334 return self.http_error(url, fp, errcode, errmsg, headers)
335
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000336 # Use Gopher protocol
337 def open_gopher(self, url):
338 import gopherlib
339 host, selector = splithost(url)
340 if not host: raise IOError, ('gopher error', 'no host given')
341 host = unquote(host)
342 type, selector = splitgophertype(selector)
343 selector, query = splitquery(selector)
344 selector = unquote(selector)
345 if query:
346 query = unquote(query)
347 fp = gopherlib.send_query(selector, query, host)
348 else:
349 fp = gopherlib.send_selector(selector, host)
350 return addinfourl(fp, noheaders(), "gopher:" + url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000351
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000352 # Use local file or FTP depending on form of URL
353 def open_file(self, url):
354 if url[:2] == '//' and url[2:3] != '/':
355 return self.open_ftp(url)
356 else:
357 return self.open_local_file(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000358
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000359 # Use local file
360 def open_local_file(self, url):
361 import mimetypes, mimetools, StringIO
362 mtype = mimetypes.guess_type(url)[0]
363 headers = mimetools.Message(StringIO.StringIO(
364 'Content-Type: %s\n' % (mtype or 'text/plain')))
365 host, file = splithost(url)
366 if not host:
Guido van Rossum336a2011999-06-24 15:27:36 +0000367 urlfile = file
368 if file[:1] == '/':
369 urlfile = 'file://' + file
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000370 return addinfourl(open(url2pathname(file), 'rb'),
Guido van Rossum336a2011999-06-24 15:27:36 +0000371 headers, urlfile)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000372 host, port = splitport(host)
373 if not port \
374 and socket.gethostbyname(host) in (localhost(), thishost()):
Guido van Rossum336a2011999-06-24 15:27:36 +0000375 urlfile = file
376 if file[:1] == '/':
377 urlfile = 'file://' + file
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000378 return addinfourl(open(url2pathname(file), 'rb'),
Guido van Rossum336a2011999-06-24 15:27:36 +0000379 headers, urlfile)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000380 raise IOError, ('local file error', 'not on local host')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000381
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000382 # Use FTP protocol
383 def open_ftp(self, url):
384 host, path = splithost(url)
385 if not host: raise IOError, ('ftp error', 'no host given')
386 host, port = splitport(host)
387 user, host = splituser(host)
388 if user: user, passwd = splitpasswd(user)
389 else: passwd = None
390 host = unquote(host)
391 user = unquote(user or '')
392 passwd = unquote(passwd or '')
393 host = socket.gethostbyname(host)
394 if not port:
395 import ftplib
396 port = ftplib.FTP_PORT
397 else:
398 port = int(port)
399 path, attrs = splitattr(path)
400 path = unquote(path)
401 dirs = string.splitfields(path, '/')
402 dirs, file = dirs[:-1], dirs[-1]
403 if dirs and not dirs[0]: dirs = dirs[1:]
Guido van Rossum5e006a31999-08-18 17:40:33 +0000404 if dirs and not dirs[0]: dirs[0] = '/'
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000405 key = (user, host, port, string.joinfields(dirs, '/'))
406 # XXX thread unsafe!
407 if len(self.ftpcache) > MAXFTPCACHE:
408 # Prune the cache, rather arbitrarily
409 for k in self.ftpcache.keys():
410 if k != key:
411 v = self.ftpcache[k]
412 del self.ftpcache[k]
413 v.close()
414 try:
415 if not self.ftpcache.has_key(key):
416 self.ftpcache[key] = \
417 ftpwrapper(user, passwd, host, port, dirs)
418 if not file: type = 'D'
419 else: type = 'I'
420 for attr in attrs:
421 attr, value = splitvalue(attr)
422 if string.lower(attr) == 'type' and \
423 value in ('a', 'A', 'i', 'I', 'd', 'D'):
424 type = string.upper(value)
425 (fp, retrlen) = self.ftpcache[key].retrfile(file, type)
426 if retrlen is not None and retrlen >= 0:
427 import mimetools, StringIO
428 headers = mimetools.Message(StringIO.StringIO(
429 'Content-Length: %d\n' % retrlen))
430 else:
431 headers = noheaders()
432 return addinfourl(fp, headers, "ftp:" + url)
433 except ftperrors(), msg:
434 raise IOError, ('ftp error', msg), sys.exc_info()[2]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000435
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000436 # Use "data" URL
437 def open_data(self, url, data=None):
438 # ignore POSTed data
439 #
440 # syntax of data URLs:
441 # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
442 # mediatype := [ type "/" subtype ] *( ";" parameter )
443 # data := *urlchar
444 # parameter := attribute "=" value
445 import StringIO, mimetools, time
446 try:
447 [type, data] = string.split(url, ',', 1)
448 except ValueError:
449 raise IOError, ('data error', 'bad data URL')
450 if not type:
451 type = 'text/plain;charset=US-ASCII'
452 semi = string.rfind(type, ';')
453 if semi >= 0 and '=' not in type[semi:]:
454 encoding = type[semi+1:]
455 type = type[:semi]
456 else:
457 encoding = ''
458 msg = []
459 msg.append('Date: %s'%time.strftime('%a, %d %b %Y %T GMT',
460 time.gmtime(time.time())))
461 msg.append('Content-type: %s' % type)
462 if encoding == 'base64':
463 import base64
464 data = base64.decodestring(data)
465 else:
466 data = unquote(data)
467 msg.append('Content-length: %d' % len(data))
468 msg.append('')
469 msg.append(data)
470 msg = string.join(msg, '\n')
471 f = StringIO.StringIO(msg)
472 headers = mimetools.Message(f, 0)
473 f.fileno = None # needed for addinfourl
474 return addinfourl(f, headers, url)
Guido van Rossum6d4d1c21998-03-12 14:32:55 +0000475
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000476
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000477# Derived class with handlers for errors we can handle (perhaps)
478class FancyURLopener(URLopener):
479
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000480 def __init__(self, *args):
481 apply(URLopener.__init__, (self,) + args)
482 self.auth_cache = {}
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000483
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000484 # Default error handling -- don't raise an exception
485 def http_error_default(self, url, fp, errcode, errmsg, headers):
486 return addinfourl(fp, headers, "http:" + url)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000487
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000488 # Error 302 -- relocated (temporarily)
489 def http_error_302(self, url, fp, errcode, errmsg, headers,
490 data=None):
491 # XXX The server can force infinite recursion here!
492 if headers.has_key('location'):
493 newurl = headers['location']
494 elif headers.has_key('uri'):
495 newurl = headers['uri']
496 else:
497 return
498 void = fp.read()
499 fp.close()
Guido van Rossum3527f591999-03-29 20:23:41 +0000500 # In case the server sent a relative URL, join with original:
501 newurl = basejoin("http:" + url, newurl)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000502 return self.open(newurl, data)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000503
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000504 # Error 301 -- also relocated (permanently)
505 http_error_301 = http_error_302
Guido van Rossume6ad8911996-09-10 17:02:56 +0000506
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000507 # Error 401 -- authentication required
508 # See this URL for a description of the basic authentication scheme:
509 # http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt
510 def http_error_401(self, url, fp, errcode, errmsg, headers,
511 data=None):
512 if headers.has_key('www-authenticate'):
513 stuff = headers['www-authenticate']
514 import re
515 match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
516 if match:
517 scheme, realm = match.groups()
518 if string.lower(scheme) == 'basic':
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000519 name = 'retry_' + self.type + '_basic_auth'
520 return getattr(self,name)(url, realm)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000521
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000522 def retry_http_basic_auth(self, url, realm, data):
523 host, selector = splithost(url)
524 i = string.find(host, '@') + 1
525 host = host[i:]
526 user, passwd = self.get_user_passwd(host, realm, i)
527 if not (user or passwd): return None
528 host = user + ':' + passwd + '@' + host
529 newurl = 'http://' + host + selector
530 return self.open(newurl, data)
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000531
532 def retry_https_basic_auth(self, url, realm):
533 host, selector = splithost(url)
534 i = string.find(host, '@') + 1
535 host = host[i:]
536 user, passwd = self.get_user_passwd(host, realm, i)
537 if not (user or passwd): return None
538 host = user + ':' + passwd + '@' + host
539 newurl = '//' + host + selector
540 return self.open_https(newurl)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000541
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000542 def get_user_passwd(self, host, realm, clear_cache = 0):
543 key = realm + '@' + string.lower(host)
544 if self.auth_cache.has_key(key):
545 if clear_cache:
546 del self.auth_cache[key]
547 else:
548 return self.auth_cache[key]
549 user, passwd = self.prompt_user_passwd(host, realm)
550 if user or passwd: self.auth_cache[key] = (user, passwd)
551 return user, passwd
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000552
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000553 def prompt_user_passwd(self, host, realm):
554 # Override this in a GUI environment!
555 import getpass
556 try:
557 user = raw_input("Enter username for %s at %s: " % (realm,
558 host))
559 passwd = getpass.getpass("Enter password for %s in %s at %s: " %
560 (user, realm, host))
561 return user, passwd
562 except KeyboardInterrupt:
563 print
564 return None, None
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000565
566
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000567# Utility functions
568
569# Return the IP address of the magic hostname 'localhost'
570_localhost = None
571def localhost():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000572 global _localhost
573 if not _localhost:
574 _localhost = socket.gethostbyname('localhost')
575 return _localhost
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000576
577# Return the IP address of the current host
578_thishost = None
579def thishost():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000580 global _thishost
581 if not _thishost:
582 _thishost = socket.gethostbyname(socket.gethostname())
583 return _thishost
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000584
585# Return the set of errors raised by the FTP class
586_ftperrors = None
587def ftperrors():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000588 global _ftperrors
589 if not _ftperrors:
590 import ftplib
591 _ftperrors = ftplib.all_errors
592 return _ftperrors
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000593
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000594# Return an empty mimetools.Message object
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000595_noheaders = None
596def noheaders():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000597 global _noheaders
598 if not _noheaders:
599 import mimetools
600 import StringIO
601 _noheaders = mimetools.Message(StringIO.StringIO(), 0)
602 _noheaders.fp.close() # Recycle file descriptor
603 return _noheaders
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000604
605
606# Utility classes
607
608# Class used by open_ftp() for cache of open FTP connections
609class ftpwrapper:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000610 def __init__(self, user, passwd, host, port, dirs):
611 self.user = user
612 self.passwd = passwd
613 self.host = host
614 self.port = port
615 self.dirs = dirs
616 self.init()
617 def init(self):
618 import ftplib
619 self.busy = 0
620 self.ftp = ftplib.FTP()
621 self.ftp.connect(self.host, self.port)
622 self.ftp.login(self.user, self.passwd)
623 for dir in self.dirs:
624 self.ftp.cwd(dir)
625 def retrfile(self, file, type):
626 import ftplib
627 self.endtransfer()
628 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
629 else: cmd = 'TYPE ' + type; isdir = 0
630 try:
631 self.ftp.voidcmd(cmd)
632 except ftplib.all_errors:
633 self.init()
634 self.ftp.voidcmd(cmd)
635 conn = None
636 if file and not isdir:
637 # Use nlst to see if the file exists at all
638 try:
639 self.ftp.nlst(file)
640 except ftplib.error_perm, reason:
641 raise IOError, ('ftp error', reason), sys.exc_info()[2]
642 # Restore the transfer mode!
643 self.ftp.voidcmd(cmd)
644 # Try to retrieve as a file
645 try:
646 cmd = 'RETR ' + file
647 conn = self.ftp.ntransfercmd(cmd)
648 except ftplib.error_perm, reason:
649 if reason[:3] != '550':
650 raise IOError, ('ftp error', reason), sys.exc_info()[2]
651 if not conn:
652 # Set transfer mode to ASCII!
653 self.ftp.voidcmd('TYPE A')
654 # Try a directory listing
655 if file: cmd = 'LIST ' + file
656 else: cmd = 'LIST'
657 conn = self.ftp.ntransfercmd(cmd)
658 self.busy = 1
659 # Pass back both a suitably decorated object and a retrieval length
660 return (addclosehook(conn[0].makefile('rb'),
661 self.endtransfer), conn[1])
662 def endtransfer(self):
663 if not self.busy:
664 return
665 self.busy = 0
666 try:
667 self.ftp.voidresp()
668 except ftperrors():
669 pass
670 def close(self):
671 self.endtransfer()
672 try:
673 self.ftp.close()
674 except ftperrors():
675 pass
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000676
677# Base class for addinfo and addclosehook
678class addbase:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000679 def __init__(self, fp):
680 self.fp = fp
681 self.read = self.fp.read
682 self.readline = self.fp.readline
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000683 if hasattr(self.fp, "readlines"): self.readlines = self.fp.readlines
684 if hasattr(self.fp, "fileno"): self.fileno = self.fp.fileno
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000685 def __repr__(self):
686 return '<%s at %s whose fp = %s>' % (self.__class__.__name__,
687 `id(self)`, `self.fp`)
688 def close(self):
689 self.read = None
690 self.readline = None
691 self.readlines = None
692 self.fileno = None
693 if self.fp: self.fp.close()
694 self.fp = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000695
696# Class to add a close hook to an open file
697class addclosehook(addbase):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000698 def __init__(self, fp, closehook, *hookargs):
699 addbase.__init__(self, fp)
700 self.closehook = closehook
701 self.hookargs = hookargs
702 def close(self):
703 if self.closehook:
704 apply(self.closehook, self.hookargs)
705 self.closehook = None
706 self.hookargs = None
707 addbase.close(self)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000708
709# class to add an info() method to an open file
710class addinfo(addbase):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000711 def __init__(self, fp, headers):
712 addbase.__init__(self, fp)
713 self.headers = headers
714 def info(self):
715 return self.headers
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000716
Guido van Rossume6ad8911996-09-10 17:02:56 +0000717# class to add info() and geturl() methods to an open file
718class addinfourl(addbase):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000719 def __init__(self, fp, headers, url):
720 addbase.__init__(self, fp)
721 self.headers = headers
722 self.url = url
723 def info(self):
724 return self.headers
725 def geturl(self):
726 return self.url
Guido van Rossume6ad8911996-09-10 17:02:56 +0000727
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000728
729# Utility to combine a URL with a base URL to form a new URL
730
731def basejoin(base, url):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000732 type, path = splittype(url)
733 if type:
734 # if url is complete (i.e., it contains a type), return it
735 return url
736 host, path = splithost(path)
737 type, basepath = splittype(base) # inherit type from base
738 if host:
739 # if url contains host, just inherit type
740 if type: return type + '://' + host + path
741 else:
742 # no type inherited, so url must have started with //
743 # just return it
744 return url
745 host, basepath = splithost(basepath) # inherit host
746 basepath, basetag = splittag(basepath) # remove extraneuous cruft
747 basepath, basequery = splitquery(basepath) # idem
748 if path[:1] != '/':
749 # non-absolute path name
750 if path[:1] in ('#', '?'):
751 # path is just a tag or query, attach to basepath
752 i = len(basepath)
753 else:
754 # else replace last component
755 i = string.rfind(basepath, '/')
756 if i < 0:
757 # basepath not absolute
758 if host:
759 # host present, make absolute
760 basepath = '/'
761 else:
762 # else keep non-absolute
763 basepath = ''
764 else:
765 # remove last file component
766 basepath = basepath[:i+1]
767 # Interpret ../ (important because of symlinks)
768 while basepath and path[:3] == '../':
769 path = path[3:]
770 i = string.rfind(basepath[:-1], '/')
771 if i > 0:
772 basepath = basepath[:i+1]
773 elif i == 0:
774 basepath = '/'
775 break
776 else:
777 basepath = ''
778
779 path = basepath + path
780 if type and host: return type + '://' + host + path
781 elif type: return type + ':' + path
782 elif host: return '//' + host + path # don't know what this means
783 else: return path
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000784
785
Guido van Rossum7c395db1994-07-04 22:14:49 +0000786# Utilities to parse URLs (most of these return None for missing parts):
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000787# unwrap('<URL:type://host/path>') --> 'type://host/path'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000788# splittype('type:opaquestring') --> 'type', 'opaquestring'
789# splithost('//host[:port]/path') --> 'host[:port]', '/path'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000790# splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'
791# splitpasswd('user:passwd') -> 'user', 'passwd'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000792# splitport('host:port') --> 'host', 'port'
793# splitquery('/path?query') --> '/path', 'query'
794# splittag('/path#tag') --> '/path', 'tag'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000795# splitattr('/path;attr1=value1;attr2=value2;...') ->
796# '/path', ['attr1=value1', 'attr2=value2', ...]
797# splitvalue('attr=value') --> 'attr', 'value'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000798# splitgophertype('/Xselector') --> 'X', 'selector'
799# unquote('abc%20def') -> 'abc def'
800# quote('abc def') -> 'abc%20def')
801
802def unwrap(url):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000803 url = string.strip(url)
804 if url[:1] == '<' and url[-1:] == '>':
805 url = string.strip(url[1:-1])
806 if url[:4] == 'URL:': url = string.strip(url[4:])
807 return url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000808
Guido van Rossum332e1441997-09-29 23:23:46 +0000809_typeprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000810def splittype(url):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000811 global _typeprog
812 if _typeprog is None:
813 import re
814 _typeprog = re.compile('^([^/:]+):')
Guido van Rossum332e1441997-09-29 23:23:46 +0000815
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000816 match = _typeprog.match(url)
817 if match:
818 scheme = match.group(1)
819 return scheme, url[len(scheme) + 1:]
820 return None, url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000821
Guido van Rossum332e1441997-09-29 23:23:46 +0000822_hostprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000823def splithost(url):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000824 global _hostprog
825 if _hostprog is None:
826 import re
Guido van Rossum3427c1f1999-07-01 23:20:56 +0000827 _hostprog = re.compile('^//([^/]*)(.*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +0000828
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000829 match = _hostprog.match(url)
830 if match: return match.group(1, 2)
831 return None, url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000832
Guido van Rossum332e1441997-09-29 23:23:46 +0000833_userprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000834def splituser(host):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000835 global _userprog
836 if _userprog is None:
837 import re
838 _userprog = re.compile('^([^@]*)@(.*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +0000839
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000840 match = _userprog.match(host)
841 if match: return match.group(1, 2)
842 return None, host
Guido van Rossum7c395db1994-07-04 22:14:49 +0000843
Guido van Rossum332e1441997-09-29 23:23:46 +0000844_passwdprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000845def splitpasswd(user):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000846 global _passwdprog
847 if _passwdprog is None:
848 import re
849 _passwdprog = re.compile('^([^:]*):(.*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +0000850
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000851 match = _passwdprog.match(user)
852 if match: return match.group(1, 2)
853 return user, None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000854
Guido van Rossum332e1441997-09-29 23:23:46 +0000855_portprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000856def splitport(host):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000857 global _portprog
858 if _portprog is None:
859 import re
860 _portprog = re.compile('^(.*):([0-9]+)$')
Guido van Rossum332e1441997-09-29 23:23:46 +0000861
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000862 match = _portprog.match(host)
863 if match: return match.group(1, 2)
864 return host, None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000865
Guido van Rossum53725a21996-06-13 19:12:35 +0000866# Split host and port, returning numeric port.
867# Return given default port if no ':' found; defaults to -1.
Guido van Rossum84a00a81996-06-17 17:11:40 +0000868# Return numerical port if a valid number are found after ':'.
869# Return None if ':' but not a valid number.
Guido van Rossum332e1441997-09-29 23:23:46 +0000870_nportprog = None
Guido van Rossum53725a21996-06-13 19:12:35 +0000871def splitnport(host, defport=-1):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000872 global _nportprog
873 if _nportprog is None:
874 import re
875 _nportprog = re.compile('^(.*):(.*)$')
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000876
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000877 match = _nportprog.match(host)
878 if match:
879 host, port = match.group(1, 2)
880 try:
881 if not port: raise string.atoi_error, "no digits"
882 nport = string.atoi(port)
883 except string.atoi_error:
884 nport = None
885 return host, nport
886 return host, defport
Guido van Rossum53725a21996-06-13 19:12:35 +0000887
Guido van Rossum332e1441997-09-29 23:23:46 +0000888_queryprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000889def splitquery(url):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000890 global _queryprog
891 if _queryprog is None:
892 import re
893 _queryprog = re.compile('^(.*)\?([^?]*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +0000894
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000895 match = _queryprog.match(url)
896 if match: return match.group(1, 2)
897 return url, None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000898
Guido van Rossum332e1441997-09-29 23:23:46 +0000899_tagprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000900def splittag(url):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000901 global _tagprog
902 if _tagprog is None:
903 import re
904 _tagprog = re.compile('^(.*)#([^#]*)$')
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000905
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000906 match = _tagprog.match(url)
907 if match: return match.group(1, 2)
908 return url, None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000909
Guido van Rossum7c395db1994-07-04 22:14:49 +0000910def splitattr(url):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000911 words = string.splitfields(url, ';')
912 return words[0], words[1:]
Guido van Rossum7c395db1994-07-04 22:14:49 +0000913
Guido van Rossum332e1441997-09-29 23:23:46 +0000914_valueprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000915def splitvalue(attr):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000916 global _valueprog
917 if _valueprog is None:
918 import re
919 _valueprog = re.compile('^([^=]*)=(.*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +0000920
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000921 match = _valueprog.match(attr)
922 if match: return match.group(1, 2)
923 return attr, None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000924
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000925def splitgophertype(selector):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000926 if selector[:1] == '/' and selector[1:2]:
927 return selector[1], selector[2:]
928 return None, selector
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000929
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000930def unquote(s):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000931 mychr = chr
932 myatoi = string.atoi
933 list = string.split(s, '%')
934 res = [list[0]]
935 myappend = res.append
936 del list[0]
937 for item in list:
938 if item[1:2]:
939 try:
940 myappend(mychr(myatoi(item[:2], 16))
941 + item[2:])
942 except:
943 myappend('%' + item)
944 else:
945 myappend('%' + item)
946 return string.join(res, "")
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000947
Guido van Rossum0564e121996-12-13 14:47:36 +0000948def unquote_plus(s):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000949 if '+' in s:
950 # replace '+' with ' '
951 s = string.join(string.split(s, '+'), ' ')
952 return unquote(s)
Guido van Rossum0564e121996-12-13 14:47:36 +0000953
Guido van Rossum3bb54481994-08-29 10:52:58 +0000954always_safe = string.letters + string.digits + '_,.-'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000955def quote(s, safe = '/'):
Guido van Rossum0dee4ee1999-06-09 15:14:50 +0000956 # XXX Can speed this up an order of magnitude
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000957 safe = always_safe + safe
958 res = list(s)
959 for i in range(len(res)):
960 c = res[i]
961 if c not in safe:
962 res[i] = '%%%02x' % ord(c)
963 return string.joinfields(res, '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000964
Guido van Rossum0564e121996-12-13 14:47:36 +0000965def quote_plus(s, safe = '/'):
Guido van Rossum0dee4ee1999-06-09 15:14:50 +0000966 # XXX Can speed this up an order of magnitude
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000967 if ' ' in s:
968 # replace ' ' with '+'
969 l = string.split(s, ' ')
970 for i in range(len(l)):
971 l[i] = quote(l[i], safe)
972 return string.join(l, '+')
973 else:
974 return quote(s, safe)
Guido van Rossum0564e121996-12-13 14:47:36 +0000975
Guido van Rossum810a3391998-07-22 21:33:23 +0000976def urlencode(dict):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000977 l = []
978 for k, v in dict.items():
979 k = quote_plus(str(k))
980 v = quote_plus(str(v))
981 l.append(k + '=' + v)
982 return string.join(l, '&')
Guido van Rossum810a3391998-07-22 21:33:23 +0000983
Guido van Rossum442e7201996-03-20 15:33:11 +0000984
985# Proxy handling
Guido van Rossum4163e701998-08-06 13:39:09 +0000986if os.name == 'mac':
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000987 def getproxies():
988 """Return a dictionary of scheme -> proxy server URL mappings.
Guido van Rossum442e7201996-03-20 15:33:11 +0000989
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000990 By convention the mac uses Internet Config to store
991 proxies. An HTTP proxy, for instance, is stored under
992 the HttpProxy key.
Guido van Rossum442e7201996-03-20 15:33:11 +0000993
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000994 """
995 try:
996 import ic
997 except ImportError:
998 return {}
999
1000 try:
1001 config = ic.IC()
1002 except ic.error:
1003 return {}
1004 proxies = {}
1005 # HTTP:
1006 if config.has_key('UseHTTPProxy') and config['UseHTTPProxy']:
1007 try:
1008 value = config['HTTPProxyHost']
1009 except ic.error:
1010 pass
1011 else:
1012 proxies['http'] = 'http://%s' % value
1013 # FTP: XXXX To be done.
1014 # Gopher: XXXX To be done.
1015 return proxies
1016
Guido van Rossum4163e701998-08-06 13:39:09 +00001017else:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001018 def getproxies():
1019 """Return a dictionary of scheme -> proxy server URL mappings.
1020
1021 Scan the environment for variables named <scheme>_proxy;
1022 this seems to be the standard convention. If you need a
1023 different way, you can pass a proxies dictionary to the
1024 [Fancy]URLopener constructor.
1025
1026 """
1027 proxies = {}
1028 for name, value in os.environ.items():
1029 name = string.lower(name)
1030 if value and name[-6:] == '_proxy':
1031 proxies[name[:-6]] = value
1032 return proxies
Guido van Rossum442e7201996-03-20 15:33:11 +00001033
1034
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001035# Test and time quote() and unquote()
1036def test1():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001037 import time
1038 s = ''
1039 for i in range(256): s = s + chr(i)
1040 s = s*4
1041 t0 = time.time()
1042 qs = quote(s)
1043 uqs = unquote(qs)
1044 t1 = time.time()
1045 if uqs != s:
1046 print 'Wrong!'
1047 print `s`
1048 print `qs`
1049 print `uqs`
1050 print round(t1 - t0, 3), 'sec'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001051
1052
Guido van Rossum9ab96d41998-09-28 14:07:00 +00001053def reporthook(blocknum, blocksize, totalsize):
1054 # Report during remote transfers
1055 print "Block number: %d, Block size: %d, Total size: %d" % (blocknum, blocksize, totalsize)
1056
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001057# Test program
Guido van Rossum23490151998-06-25 02:39:00 +00001058def test(args=[]):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001059 if not args:
1060 args = [
1061 '/etc/passwd',
1062 'file:/etc/passwd',
1063 'file://localhost/etc/passwd',
1064 'ftp://ftp.python.org/etc/passwd',
1065## 'gopher://gopher.micro.umn.edu/1/',
1066 'http://www.python.org/index.html',
1067 ]
Guido van Rossum09c8b6c1999-12-07 21:37:17 +00001068 if hasattr(URLopener, "open_https"):
1069 args.append('https://synergy.as.cmu.edu/~geek/')
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001070 try:
1071 for url in args:
1072 print '-'*10, url, '-'*10
1073 fn, h = urlretrieve(url, None, reporthook)
1074 print fn, h
1075 if h:
1076 print '======'
1077 for k in h.keys(): print k + ':', h[k]
1078 print '======'
1079 fp = open(fn, 'rb')
1080 data = fp.read()
1081 del fp
1082 if '\r' in data:
1083 table = string.maketrans("", "")
1084 data = string.translate(data, table, "\r")
1085 print data
1086 fn, h = None, None
1087 print '-'*40
1088 finally:
1089 urlcleanup()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001090
Guido van Rossum23490151998-06-25 02:39:00 +00001091def main():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001092 import getopt, sys
1093 try:
1094 opts, args = getopt.getopt(sys.argv[1:], "th")
1095 except getopt.error, msg:
1096 print msg
1097 print "Use -h for help"
1098 return
1099 t = 0
1100 for o, a in opts:
1101 if o == '-t':
1102 t = t + 1
1103 if o == '-h':
1104 print "Usage: python urllib.py [-t] [url ...]"
1105 print "-t runs self-test;",
1106 print "otherwise, contents of urls are printed"
1107 return
1108 if t:
1109 if t > 1:
1110 test1()
1111 test(args)
1112 else:
1113 if not args:
1114 print "Use -h for help"
1115 for url in args:
1116 print urlopen(url).read(),
Guido van Rossum23490151998-06-25 02:39:00 +00001117
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001118# Run test program when run as a script
1119if __name__ == '__main__':
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001120 main()