ยปCore Development>Code coverage>Lib/urllib.py

Python code coverage for Lib/urllib.py

#countcontent
1n/a"""Open an arbitrary URL.
2n/a
3n/aSee the following document for more info on URLs:
4n/a"Names and Addresses, URIs, URLs, URNs, URCs", at
5n/ahttp://www.w3.org/pub/WWW/Addressing/Overview.html
6n/a
7n/aSee also the HTTP spec (from which the error codes are derived):
8n/a"HTTP - Hypertext Transfer Protocol", at
9n/ahttp://www.w3.org/pub/WWW/Protocols/
10n/a
11n/aRelated standards and specs:
12n/a- RFC1808: the "relative URL" spec. (authoritative status)
13n/a- RFC1738 - the "URL standard". (authoritative status)
14n/a- RFC1630 - the "URI spec". (informational status)
15n/a
16n/aThe object returned by URLopener().open(file) will differ per
17n/aprotocol. All you know is that is has methods read(), readline(),
18n/areadlines(), fileno(), close() and info(). The read*(), fileno()
19n/aand close() methods work like those of open files.
20n/aThe info() method returns a mimetools.Message object which can be
21n/aused to query various info about the object, if available.
22n/a(mimetools.Message objects are queried with the getheader() method.)
231"""
24n/a
251import string
261import socket
271import os
281import time
291import sys
301from urlparse import urljoin as basejoin
31n/a
321__all__ = ["urlopen", "URLopener", "FancyURLopener", "urlretrieve",
331 "urlcleanup", "quote", "quote_plus", "unquote", "unquote_plus",
341 "urlencode", "url2pathname", "pathname2url", "splittag",
351 "localhost", "thishost", "ftperrors", "basejoin", "unwrap",
361 "splittype", "splithost", "splituser", "splitpasswd", "splitport",
371 "splitnport", "splitquery", "splitattr", "splitvalue",
381 "getproxies"]
39n/a
401__version__ = '1.17' # XXX This version is not always updated :-(
41n/a
421MAXFTPCACHE = 10 # Trim the ftp cache beyond this size
43n/a
44n/a# Helper for non-unix systems
451if os.name == 'nt':
460 from nturl2path import url2pathname, pathname2url
471elif os.name == 'riscos':
480 from rourl2path import url2pathname, pathname2url
49n/aelse:
501 def url2pathname(pathname):
51n/a """OS-specific conversion from a relative URL of the 'file' scheme
52n/a to a file system path; not recommended for general use."""
5335 return unquote(pathname)
54n/a
551 def pathname2url(pathname):
56n/a """OS-specific conversion from a file system path to a relative URL
57n/a of the 'file' scheme; not recommended for general use."""
5810 return quote(pathname)
59n/a
60n/a# This really consists of two pieces:
61n/a# (1) a class which handles opening of all sorts of URLs
62n/a# (plus assorted utilities etc.)
63n/a# (2) a set of functions for parsing URLs
64n/a# XXX Should these be separated out into different modules?
65n/a
66n/a
67n/a# Shortcut for basic usage
681_urlopener = None
691def urlopen(url, data=None, proxies=None):
70n/a """Create a file-like object for the specified URL to read from."""
7121 from warnings import warnpy3k
7221 warnpy3k("urllib.urlopen() has been removed in Python 3.0 in "
7321 "favor of urllib2.urlopen()", stacklevel=2)
74n/a
75n/a global _urlopener
7621 if proxies is not None:
770 opener = FancyURLopener(proxies=proxies)
7821 elif not _urlopener:
791 opener = FancyURLopener()
801 _urlopener = opener
81n/a else:
8220 opener = _urlopener
8321 if data is None:
8421 return opener.open(url)
85n/a else:
860 return opener.open(url, data)
871def urlretrieve(url, filename=None, reporthook=None, data=None):
88n/a global _urlopener
8910 if not _urlopener:
900 _urlopener = FancyURLopener()
9110 return _urlopener.retrieve(url, filename, reporthook, data)
921def urlcleanup():
930 if _urlopener:
940 _urlopener.cleanup()
950 _safe_quoters.clear()
960 ftpcache.clear()
97n/a
98n/a# check for SSL
991try:
1001 import ssl
1010except:
1020 _have_ssl = False
103n/aelse:
1041 _have_ssl = True
105n/a
106n/a# exception raised when downloaded size does not match content-length
1072class ContentTooShortError(IOError):
1081 def __init__(self, message, content):
1090 IOError.__init__(self, message)
1100 self.content = content
111n/a
1121ftpcache = {}
1132class URLopener:
114n/a """Class to open URLs.
115n/a This is a class rather than just a subroutine because we may need
116n/a more than one set of global protocol-specific options.
117n/a Note -- this is a base class for those who don't want the
118n/a automatic handling of errors type 302 (relocated) and 401
1191 (authorization needed)."""
120n/a
1211 __tempfiles = None
122n/a
1231 version = "Python-urllib/%s" % __version__
124n/a
125n/a # Constructor
1261 def __init__(self, proxies=None, **x509):
1276 if proxies is None:
1286 proxies = getproxies()
1296 assert hasattr(proxies, 'has_key'), "proxies must be a mapping"
1306 self.proxies = proxies
1316 self.key_file = x509.get('key_file')
1326 self.cert_file = x509.get('cert_file')
1336 self.addheaders = [('User-Agent', self.version)]
1346 self.__tempfiles = []
1356 self.__unlink = os.unlink # See cleanup()
1366 self.tempcache = None
137n/a # Undocumented feature: if you assign {} to tempcache,
138n/a # it is used to cache files retrieved with
139n/a # self.retrieve(). This is not enabled by default
140n/a # since it does not work for changing documents (and I
141n/a # haven't got the logic to check expiration headers
142n/a # yet).
1436 self.ftpcache = ftpcache
144n/a # Undocumented feature: you can use a different
145n/a # ftp cache by assigning to the .ftpcache member;
146n/a # in case you want logically independent URL openers
147n/a # XXX This is not threadsafe. Bah.
148n/a
1491 def __del__(self):
1505 self.close()
151n/a
1521 def close(self):
1535 self.cleanup()
154n/a
1551 def cleanup(self):
156n/a # This code sometimes runs when the rest of this module
157n/a # has already been deleted, so it can't use any globals
158n/a # or import anything.
1595 if self.__tempfiles:
1600 for file in self.__tempfiles:
1610 try:
1620 self.__unlink(file)
1630 except OSError:
1640 pass
1650 del self.__tempfiles[:]
1665 if self.tempcache:
1670 self.tempcache.clear()
168n/a
1691 def addheader(self, *args):
170n/a """Add a header to be used by the HTTP interface only
171n/a e.g. u.addheader('Accept', 'sound/basic')"""
1720 self.addheaders.append(args)
173n/a
174n/a # External interface
1751 def open(self, fullurl, data=None):
176n/a """Use URLopener().open(file) instead of open(file, 'r')."""
17735 fullurl = unwrap(toBytes(fullurl))
178n/a # percent encode url, fixing lame server errors for e.g, like space
179n/a # within url paths.
18035 fullurl = quote(fullurl, safe="%/:=&?~#+!$,;'@()*[]|")
18135 if self.tempcache and fullurl in self.tempcache:
1820 filename, headers = self.tempcache[fullurl]
1830 fp = open(filename, 'rb')
1840 return addinfourl(fp, headers, fullurl)
18535 urltype, url = splittype(fullurl)
18635 if not urltype:
1870 urltype = 'file'
18835 if urltype in self.proxies:
1890 proxy = self.proxies[urltype]
1900 urltype, proxyhost = splittype(proxy)
1910 host, selector = splithost(proxyhost)
1920 url = (host, fullurl) # Signal special case to open_*()
193n/a else:
19435 proxy = None
19535 name = 'open_' + urltype
19635 self.type = urltype
19735 name = name.replace('-', '_')
19835 if not hasattr(self, name):
1990 if proxy:
2000 return self.open_unknown_proxy(proxy, fullurl, data)
201n/a else:
2020 return self.open_unknown(fullurl, data)
20335 try:
20435 if data is None:
20535 return getattr(self, name)(url)
206n/a else:
2070 return getattr(self, name)(url, data)
2083 except socket.error, msg:
2091 raise IOError, ('socket error', msg), sys.exc_info()[2]
210n/a
2111 def open_unknown(self, fullurl, data=None):
212n/a """Overridable interface to open unknown URL type."""
2130 type, url = splittype(fullurl)
2140 raise IOError, ('url error', 'unknown url type', type)
215n/a
2161 def open_unknown_proxy(self, proxy, fullurl, data=None):
217n/a """Overridable interface to open unknown URL type."""
2180 type, url = splittype(fullurl)
2190 raise IOError, ('url error', 'invalid proxy for %s' % type, proxy)
220n/a
221n/a # External interface
2221 def retrieve(self, url, filename=None, reporthook=None, data=None):
223n/a """retrieve(url) returns (filename, headers) for a local object
224n/a or (tempfilename, headers) for a remote object."""
22510 url = unwrap(toBytes(url))
22610 if self.tempcache and url in self.tempcache:
2270 return self.tempcache[url]
22810 type, url1 = splittype(url)
22910 if filename is None and (not type or type == 'file'):
2301 try:
2311 fp = self.open_local_file(url1)
2321 hdrs = fp.info()
2331 fp.close()
2341 return url2pathname(splithost(url1)[1]), hdrs
2350 except IOError:
2360 pass
2379 fp = self.open(url, data)
2389 try:
2399 headers = fp.info()
2409 if filename:
2416 tfp = open(filename, 'wb')
242n/a else:
2433 import tempfile
2443 garbage, path = splittype(url)
2453 garbage, path = splithost(path or "")
2463 path, garbage = splitquery(path or "")
2473 path, garbage = splitattr(path or "")
2483 suffix = os.path.splitext(path)[1]
2493 (fd, filename) = tempfile.mkstemp(suffix)
2503 self.__tempfiles.append(filename)
2513 tfp = os.fdopen(fd, 'wb')
2529 try:
2539 result = filename, headers
2549 if self.tempcache is not None:
2550 self.tempcache[url] = result
2569 bs = 1024*8
2579 size = -1
2589 read = 0
2599 blocknum = 0
2609 if reporthook:
2614 if "content-length" in headers:
2624 size = int(headers["Content-Length"])
2634 reporthook(blocknum, bs, size)
2649 while 1:
26534 block = fp.read(bs)
26634 if block == "":
2679 break
26825 read += len(block)
26925 tfp.write(block)
27025 blocknum += 1
27125 if reporthook:
2724 reporthook(blocknum, bs, size)
273n/a finally:
2749 tfp.close()
275n/a finally:
2769 fp.close()
277n/a
278n/a # raise exception if actual size does not match content-length header
2799 if size >= 0 and read < size:
2800 raise ContentTooShortError("retrieval incomplete: got only %i out "
2810 "of %i bytes" % (read, size), result)
282n/a
2839 return result
284n/a
285n/a # Each method named open_<type> knows how to open that type of URL
286n/a
2871 def open_http(self, url, data=None):
288n/a """Use HTTP protocol."""
28917 import httplib
29017 user_passwd = None
29117 proxy_passwd= None
29217 if isinstance(url, str):
29317 host, selector = splithost(url)
29417 if host:
29517 user_passwd, host = splituser(host)
29617 host = unquote(host)
29717 realhost = host
298n/a else:
2990 host, selector = url
300n/a # check whether the proxy contains authorization information
3010 proxy_passwd, host = splituser(host)
302n/a # now we proceed with the url we want to obtain
3030 urltype, rest = splittype(selector)
3040 url = rest
3050 user_passwd = None
3060 if urltype.lower() != 'http':
3070 realhost = None
308n/a else:
3090 realhost, rest = splithost(rest)
3100 if realhost:
3110 user_passwd, realhost = splituser(realhost)
3120 if user_passwd:
3130 selector = "%s://%s%s" % (urltype, realhost, rest)
3140 if proxy_bypass(realhost):
3150 host = realhost
316n/a
317n/a #print "proxy via http:", host, selector
31817 if not host: raise IOError, ('http error', 'no host given')
319n/a
32017 if proxy_passwd:
3210 import base64
3220 proxy_auth = base64.b64encode(proxy_passwd).strip()
323n/a else:
32417 proxy_auth = None
325n/a
32617 if user_passwd:
3270 import base64
3280 auth = base64.b64encode(user_passwd).strip()
329n/a else:
33017 auth = None
33117 h = httplib.HTTP(host)
33217 if data is not None:
3330 h.putrequest('POST', selector)
3340 h.putheader('Content-Type', 'application/x-www-form-urlencoded')
3350 h.putheader('Content-Length', '%d' % len(data))
336n/a else:
33717 h.putrequest('GET', selector)
33817 if proxy_auth: h.putheader('Proxy-Authorization', 'Basic %s' % proxy_auth)
33917 if auth: h.putheader('Authorization', 'Basic %s' % auth)
34017 if realhost: h.putheader('Host', realhost)
34134 for args in self.addheaders: h.putheader(*args)
34217 h.endheaders(data)
34316 errcode, errmsg, headers = h.getreply()
34416 fp = h.getfile()
34516 if errcode == -1:
3461 if fp: fp.close()
347n/a # something went wrong with the HTTP status line
3481 raise IOError, ('http protocol error', 0,
3491 'got a bad status line', None)
350n/a # According to RFC 2616, "2xx" code indicates that the client's
351n/a # request was successfully received, understood, and accepted.
35215 if (200 <= errcode < 300):
35312 return addinfourl(fp, headers, "http:" + url, errcode)
354n/a else:
3553 if data is None:
3563 return self.http_error(url, fp, errcode, errmsg, headers)
357n/a else:
3580 return self.http_error(url, fp, errcode, errmsg, headers, data)
359n/a
3601 def http_error(self, url, fp, errcode, errmsg, headers, data=None):
361n/a """Handle http errors.
362n/a Derived class can override this, or provide specific handlers
363n/a named http_error_DDD where DDD is the 3-digit error code."""
364n/a # First check if there's a specific handler for this error
3653 name = 'http_error_%d' % errcode
3663 if hasattr(self, name):
3672 method = getattr(self, name)
3682 if data is None:
3692 result = method(url, fp, errcode, errmsg, headers)
370n/a else:
3710 result = method(url, fp, errcode, errmsg, headers, data)
3721 if result: return result
3732 return self.http_error_default(url, fp, errcode, errmsg, headers)
374n/a
3751 def http_error_default(self, url, fp, errcode, errmsg, headers):
376n/a """Default error handler: close the connection and raise IOError."""
3771 void = fp.read()
3781 fp.close()
3791 raise IOError, ('http error', errcode, errmsg, headers)
380n/a
3811 if _have_ssl:
3821 def open_https(self, url, data=None):
383n/a """Use HTTPS protocol."""
384n/a
3851 import httplib
3861 user_passwd = None
3871 proxy_passwd = None
3881 if isinstance(url, str):
3891 host, selector = splithost(url)
3901 if host:
3911 user_passwd, host = splituser(host)
3921 host = unquote(host)
3931 realhost = host
394n/a else:
3950 host, selector = url
396n/a # here, we determine, whether the proxy contains authorization information
3970 proxy_passwd, host = splituser(host)
3980 urltype, rest = splittype(selector)
3990 url = rest
4000 user_passwd = None
4010 if urltype.lower() != 'https':
4020 realhost = None
403n/a else:
4040 realhost, rest = splithost(rest)
4050 if realhost:
4060 user_passwd, realhost = splituser(realhost)
4070 if user_passwd:
4080 selector = "%s://%s%s" % (urltype, realhost, rest)
409n/a #print "proxy via https:", host, selector
4101 if not host: raise IOError, ('https error', 'no host given')
4111 if proxy_passwd:
4120 import base64
4130 proxy_auth = base64.b64encode(proxy_passwd).strip()
414n/a else:
4151 proxy_auth = None
4161 if user_passwd:
4170 import base64
4180 auth = base64.b64encode(user_passwd).strip()
419n/a else:
4201 auth = None
4211 h = httplib.HTTPS(host, 0,
4221 key_file=self.key_file,
4231 cert_file=self.cert_file)
4241 if data is not None:
4250 h.putrequest('POST', selector)
4260 h.putheader('Content-Type',
4270 'application/x-www-form-urlencoded')
4280 h.putheader('Content-Length', '%d' % len(data))
429n/a else:
4301 h.putrequest('GET', selector)
4311 if proxy_auth: h.putheader('Proxy-Authorization', 'Basic %s' % proxy_auth)
4321 if auth: h.putheader('Authorization', 'Basic %s' % auth)
4331 if realhost: h.putheader('Host', realhost)
4342 for args in self.addheaders: h.putheader(*args)
4351 h.endheaders(data)
4361 errcode, errmsg, headers = h.getreply()
4371 fp = h.getfile()
4381 if errcode == -1:
4390 if fp: fp.close()
440n/a # something went wrong with the HTTP status line
4410 raise IOError, ('http protocol error', 0,
4420 'got a bad status line', None)
443n/a # According to RFC 2616, "2xx" code indicates that the client's
444n/a # request was successfully received, understood, and accepted.
4451 if (200 <= errcode < 300):
4461 return addinfourl(fp, headers, "https:" + url, errcode)
447n/a else:
4480 if data is None:
4490 return self.http_error(url, fp, errcode, errmsg, headers)
450n/a else:
4510 return self.http_error(url, fp, errcode, errmsg, headers,
4520 data)
453n/a
4541 def open_file(self, url):
455n/a """Use local file or FTP depending on form of URL."""
45615 if not isinstance(url, str):
4570 raise IOError, ('file error', 'proxy support for file protocol currently not implemented')
45815 if url[:2] == '//' and url[2:3] != '/' and url[2:12].lower() != 'localhost/':
4590 return self.open_ftp(url)
460n/a else:
46115 return self.open_local_file(url)
462n/a
4631 def open_local_file(self, url):
464n/a """Use local file."""
46516 import mimetypes, mimetools, email.utils
46616 try:
46716 from cStringIO import StringIO
4680 except ImportError:
4690 from StringIO import StringIO
47016 host, file = splithost(url)
47116 localname = url2pathname(file)
47216 try:
47316 stats = os.stat(localname)
4740 except OSError, e:
4750 raise IOError(e.errno, e.strerror, e.filename)
47616 size = stats.st_size
47716 modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
47816 mtype = mimetypes.guess_type(url)[0]
47916 headers = mimetools.Message(StringIO(
48016 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' %
48116 (mtype or 'text/plain', size, modified)))
48216 if not host:
48316 urlfile = file
48416 if file[:1] == '/':
4855 urlfile = 'file://' + file
48616 return addinfourl(open(localname, 'rb'),
48716 headers, urlfile)
4880 host, port = splitport(host)
4890 if not port \
4900 and socket.gethostbyname(host) in (localhost(), thishost()):
4910 urlfile = file
4920 if file[:1] == '/':
4930 urlfile = 'file://' + file
4940 return addinfourl(open(localname, 'rb'),
4950 headers, urlfile)
4960 raise IOError, ('local file error', 'not on local host')
497n/a
4981 def open_ftp(self, url):
499n/a """Use FTP protocol."""
5000 if not isinstance(url, str):
5010 raise IOError, ('ftp error', 'proxy support for ftp protocol currently not implemented')
5020 import mimetypes, mimetools
5030 try:
5040 from cStringIO import StringIO
5050 except ImportError:
5060 from StringIO import StringIO
5070 host, path = splithost(url)
5080 if not host: raise IOError, ('ftp error', 'no host given')
5090 host, port = splitport(host)
5100 user, host = splituser(host)
5110 if user: user, passwd = splitpasswd(user)
5120 else: passwd = None
5130 host = unquote(host)
5140 user = unquote(user or '')
5150 passwd = unquote(passwd or '')
5160 host = socket.gethostbyname(host)
5170 if not port:
5180 import ftplib
5190 port = ftplib.FTP_PORT
520n/a else:
5210 port = int(port)
5220 path, attrs = splitattr(path)
5230 path = unquote(path)
5240 dirs = path.split('/')
5250 dirs, file = dirs[:-1], dirs[-1]
5260 if dirs and not dirs[0]: dirs = dirs[1:]
5270 if dirs and not dirs[0]: dirs[0] = '/'
5280 key = user, host, port, '/'.join(dirs)
529n/a # XXX thread unsafe!
5300 if len(self.ftpcache) > MAXFTPCACHE:
531n/a # Prune the cache, rather arbitrarily
5320 for k in self.ftpcache.keys():
5330 if k != key:
5340 v = self.ftpcache[k]
5350 del self.ftpcache[k]
5360 v.close()
5370 try:
5380 if not key in self.ftpcache:
539n/a self.ftpcache[key] = \
5400 ftpwrapper(user, passwd, host, port, dirs)
5410 if not file: type = 'D'
5420 else: type = 'I'
5430 for attr in attrs:
5440 attr, value = splitvalue(attr)
5450 if attr.lower() == 'type' and \
5460 value in ('a', 'A', 'i', 'I', 'd', 'D'):
5470 type = value.upper()
5480 (fp, retrlen) = self.ftpcache[key].retrfile(file, type)
5490 mtype = mimetypes.guess_type("ftp:" + url)[0]
5500 headers = ""
5510 if mtype:
5520 headers += "Content-Type: %s\n" % mtype
5530 if retrlen is not None and retrlen >= 0:
5540 headers += "Content-Length: %d\n" % retrlen
5550 headers = mimetools.Message(StringIO(headers))
5560 return addinfourl(fp, headers, "ftp:" + url)
5570 except ftperrors(), msg:
5580 raise IOError, ('ftp error', msg), sys.exc_info()[2]
559n/a
5601 def open_data(self, url, data=None):
561n/a """Use "data" URL."""
5620 if not isinstance(url, str):
5630 raise IOError, ('data error', 'proxy support for data protocol currently not implemented')
564n/a # ignore POSTed data
565n/a #
566n/a # syntax of data URLs:
567n/a # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
568n/a # mediatype := [ type "/" subtype ] *( ";" parameter )
569n/a # data := *urlchar
570n/a # parameter := attribute "=" value
5710 import mimetools
5720 try:
5730 from cStringIO import StringIO
5740 except ImportError:
5750 from StringIO import StringIO
5760 try:
5770 [type, data] = url.split(',', 1)
5780 except ValueError:
5790 raise IOError, ('data error', 'bad data URL')
5800 if not type:
5810 type = 'text/plain;charset=US-ASCII'
5820 semi = type.rfind(';')
5830 if semi >= 0 and '=' not in type[semi:]:
5840 encoding = type[semi+1:]
5850 type = type[:semi]
586n/a else:
5870 encoding = ''
5880 msg = []
5890 msg.append('Date: %s'%time.strftime('%a, %d %b %Y %H:%M:%S GMT',
5900 time.gmtime(time.time())))
5910 msg.append('Content-type: %s' % type)
5920 if encoding == 'base64':
5930 import base64
5940 data = base64.decodestring(data)
595n/a else:
5960 data = unquote(data)
5970 msg.append('Content-Length: %d' % len(data))
5980 msg.append('')
5990 msg.append(data)
6000 msg = '\n'.join(msg)
6010 f = StringIO(msg)
6020 headers = mimetools.Message(f, 0)
603n/a #f.fileno = None # needed for addinfourl
6040 return addinfourl(f, headers, url)
605n/a
606n/a
6072class FancyURLopener(URLopener):
6081 """Derived class with handlers for errors we can handle (perhaps)."""
609n/a
6101 def __init__(self, *args, **kwargs):
6114 URLopener.__init__(self, *args, **kwargs)
6124 self.auth_cache = {}
6134 self.tries = 0
6144 self.maxtries = 10
615n/a
6161 def http_error_default(self, url, fp, errcode, errmsg, headers):
617n/a """Default error handling -- don't raise an exception."""
6182 return addinfourl(fp, headers, "http:" + url, errcode)
619n/a
6201 def http_error_302(self, url, fp, errcode, errmsg, headers, data=None):
621n/a """Error 302 -- relocated (temporarily)."""
6220 self.tries += 1
6230 if self.maxtries and self.tries >= self.maxtries:
6240 if hasattr(self, "http_error_500"):
6250 meth = self.http_error_500
626n/a else:
6270 meth = self.http_error_default
6280 self.tries = 0
6290 return meth(url, fp, 500,
6300 "Internal Server Error: Redirect Recursion", headers)
6310 result = self.redirect_internal(url, fp, errcode, errmsg, headers,
6320 data)
6330 self.tries = 0
6340 return result
635n/a
6361 def redirect_internal(self, url, fp, errcode, errmsg, headers, data):
6370 if 'location' in headers:
6380 newurl = headers['location']
6390 elif 'uri' in headers:
6400 newurl = headers['uri']
641n/a else:
6420 return
6430 void = fp.read()
6440 fp.close()
645n/a # In case the server sent a relative URL, join with original:
6460 newurl = basejoin(self.type + ":" + url, newurl)
6470 return self.open(newurl)
648n/a
6491 def http_error_301(self, url, fp, errcode, errmsg, headers, data=None):
650n/a """Error 301 -- also relocated (permanently)."""
6510 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
652n/a
6531 def http_error_303(self, url, fp, errcode, errmsg, headers, data=None):
654n/a """Error 303 -- also relocated (essentially identical to 302)."""
6550 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
656n/a
6571 def http_error_307(self, url, fp, errcode, errmsg, headers, data=None):
658n/a """Error 307 -- relocated, but turn POST into error."""
6590 if data is None:
6600 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
661n/a else:
6620 return self.http_error_default(url, fp, errcode, errmsg, headers)
663n/a
6641 def http_error_401(self, url, fp, errcode, errmsg, headers, data=None):
665n/a """Error 401 -- authentication required.
666n/a This function supports Basic authentication only."""
6672 if not 'www-authenticate' in headers:
6681 URLopener.http_error_default(self, url, fp,
6691 errcode, errmsg, headers)
6701 stuff = headers['www-authenticate']
6711 import re
6721 match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
6731 if not match:
6740 URLopener.http_error_default(self, url, fp,
6750 errcode, errmsg, headers)
6761 scheme, realm = match.groups()
6771 if scheme.lower() != 'basic':
6780 URLopener.http_error_default(self, url, fp,
6790 errcode, errmsg, headers)
6801 name = 'retry_' + self.type + '_basic_auth'
6811 if data is None:
6821 return getattr(self,name)(url, realm)
683n/a else:
6840 return getattr(self,name)(url, realm, data)
685n/a
6861 def http_error_407(self, url, fp, errcode, errmsg, headers, data=None):
687n/a """Error 407 -- proxy authentication required.
688n/a This function supports Basic authentication only."""
6890 if not 'proxy-authenticate' in headers:
6900 URLopener.http_error_default(self, url, fp,
6910 errcode, errmsg, headers)
6920 stuff = headers['proxy-authenticate']
6930 import re
6940 match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
6950 if not match:
6960 URLopener.http_error_default(self, url, fp,
6970 errcode, errmsg, headers)
6980 scheme, realm = match.groups()
6990 if scheme.lower() != 'basic':
7000 URLopener.http_error_default(self, url, fp,
7010 errcode, errmsg, headers)
7020 name = 'retry_proxy_' + self.type + '_basic_auth'
7030 if data is None:
7040 return getattr(self,name)(url, realm)
705n/a else:
7060 return getattr(self,name)(url, realm, data)
707n/a
7081 def retry_proxy_http_basic_auth(self, url, realm, data=None):
7090 host, selector = splithost(url)
7100 newurl = 'http://' + host + selector
7110 proxy = self.proxies['http']
7120 urltype, proxyhost = splittype(proxy)
7130 proxyhost, proxyselector = splithost(proxyhost)
7140 i = proxyhost.find('@') + 1
7150 proxyhost = proxyhost[i:]
7160 user, passwd = self.get_user_passwd(proxyhost, realm, i)
7170 if not (user or passwd): return None
7180 proxyhost = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + proxyhost
7190 self.proxies['http'] = 'http://' + proxyhost + proxyselector
7200 if data is None:
7210 return self.open(newurl)
722n/a else:
7230 return self.open(newurl, data)
724n/a
7251 def retry_proxy_https_basic_auth(self, url, realm, data=None):
7260 host, selector = splithost(url)
7270 newurl = 'https://' + host + selector
7280 proxy = self.proxies['https']
7290 urltype, proxyhost = splittype(proxy)
7300 proxyhost, proxyselector = splithost(proxyhost)
7310 i = proxyhost.find('@') + 1
7320 proxyhost = proxyhost[i:]
7330 user, passwd = self.get_user_passwd(proxyhost, realm, i)
7340 if not (user or passwd): return None
7350 proxyhost = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + proxyhost
7360 self.proxies['https'] = 'https://' + proxyhost + proxyselector
7370 if data is None:
7380 return self.open(newurl)
739n/a else:
7400 return self.open(newurl, data)
741n/a
7421 def retry_http_basic_auth(self, url, realm, data=None):
7431 host, selector = splithost(url)
7441 i = host.find('@') + 1
7451 host = host[i:]
7461 user, passwd = self.get_user_passwd(host, realm, i)
7471 if not (user or passwd): return None
7480 host = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + host
7490 newurl = 'http://' + host + selector
7500 if data is None:
7510 return self.open(newurl)
752n/a else:
7530 return self.open(newurl, data)
754n/a
7551 def retry_https_basic_auth(self, url, realm, data=None):
7560 host, selector = splithost(url)
7570 i = host.find('@') + 1
7580 host = host[i:]
7590 user, passwd = self.get_user_passwd(host, realm, i)
7600 if not (user or passwd): return None
7610 host = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + host
7620 newurl = 'https://' + host + selector
7630 if data is None:
7640 return self.open(newurl)
765n/a else:
7660 return self.open(newurl, data)
767n/a
7681 def get_user_passwd(self, host, realm, clear_cache=0):
7691 key = realm + '@' + host.lower()
7701 if key in self.auth_cache:
7710 if clear_cache:
7720 del self.auth_cache[key]
773n/a else:
7740 return self.auth_cache[key]
7751 user, passwd = self.prompt_user_passwd(host, realm)
7761 if user or passwd: self.auth_cache[key] = (user, passwd)
7771 return user, passwd
778n/a
7791 def prompt_user_passwd(self, host, realm):
780n/a """Override this in a GUI environment!"""
7810 import getpass
7820 try:
7830 user = raw_input("Enter username for %s at %s: " % (realm,
7840 host))
7850 passwd = getpass.getpass("Enter password for %s in %s at %s: " %
7860 (user, realm, host))
7870 return user, passwd
7880 except KeyboardInterrupt:
7890 print
7900 return None, None
791n/a
792n/a
793n/a# Utility functions
794n/a
7951_localhost = None
7961def localhost():
797n/a """Return the IP address of the magic hostname 'localhost'."""
798n/a global _localhost
7990 if _localhost is None:
8000 _localhost = socket.gethostbyname('localhost')
8010 return _localhost
802n/a
8031_thishost = None
8041def thishost():
805n/a """Return the IP address of the current host."""
806n/a global _thishost
8070 if _thishost is None:
8080 _thishost = socket.gethostbyname(socket.gethostname())
8090 return _thishost
810n/a
8111_ftperrors = None
8121def ftperrors():
813n/a """Return the set of errors raised by the FTP class."""
814n/a global _ftperrors
8150 if _ftperrors is None:
8160 import ftplib
8170 _ftperrors = ftplib.all_errors
8180 return _ftperrors
819n/a
8201_noheaders = None
8211def noheaders():
822n/a """Return an empty mimetools.Message object."""
823n/a global _noheaders
8240 if _noheaders is None:
8250 import mimetools
8260 try:
8270 from cStringIO import StringIO
8280 except ImportError:
8290 from StringIO import StringIO
8300 _noheaders = mimetools.Message(StringIO(), 0)
8310 _noheaders.fp.close() # Recycle file descriptor
8320 return _noheaders
833n/a
834n/a
835n/a# Utility classes
836n/a
8372class ftpwrapper:
8381 """Class used by open_ftp() for cache of open FTP connections."""
839n/a
840n/a def __init__(self, user, passwd, host, port, dirs,
8411 timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
8426 self.user = user
8436 self.passwd = passwd
8446 self.host = host
8456 self.port = port
8466 self.dirs = dirs
8476 self.timeout = timeout
8486 self.init()
849n/a
8501 def init(self):
8516 import ftplib
8526 self.busy = 0
8536 self.ftp = ftplib.FTP()
8546 self.ftp.connect(self.host, self.port, self.timeout)
8556 self.ftp.login(self.user, self.passwd)
85621 for dir in self.dirs:
85715 self.ftp.cwd(dir)
858n/a
8591 def retrfile(self, file, type):
8609 import ftplib
8619 self.endtransfer()
8629 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
8635 else: cmd = 'TYPE ' + type; isdir = 0
8649 try:
8659 self.ftp.voidcmd(cmd)
8660 except ftplib.all_errors:
8670 self.init()
8680 self.ftp.voidcmd(cmd)
8699 conn = None
8709 if file and not isdir:
871n/a # Try to retrieve as a file
8725 try:
8735 cmd = 'RETR ' + file
8745 conn = self.ftp.ntransfercmd(cmd)
8753 except ftplib.error_perm, reason:
8763 if str(reason)[:3] != '550':
8770 raise IOError, ('ftp error', reason), sys.exc_info()[2]
8789 if not conn:
879n/a # Set transfer mode to ASCII!
8807 self.ftp.voidcmd('TYPE A')
881n/a # Try a directory listing. Verify that directory exists.
8827 if file:
8833 pwd = self.ftp.pwd()
8843 try:
8853 try:
8863 self.ftp.cwd(file)
8873 except ftplib.error_perm, reason:
8883 raise IOError, ('ftp error', reason), sys.exc_info()[2]
889n/a finally:
8903 self.ftp.cwd(pwd)
8910 cmd = 'LIST ' + file
892n/a else:
8934 cmd = 'LIST'
8944 conn = self.ftp.ntransfercmd(cmd)
8956 self.busy = 1
896n/a # Pass back both a suitably decorated object and a retrieval length
8976 return (addclosehook(conn[0].makefile('rb'),
8986 self.endtransfer), conn[1])
8991 def endtransfer(self):
90012 if not self.busy:
90110 return
9022 self.busy = 0
9032 try:
9042 self.ftp.voidresp()
9050 except ftperrors():
9060 pass
907n/a
9081 def close(self):
9091 self.endtransfer()
9101 try:
9111 self.ftp.close()
9120 except ftperrors():
9130 pass
914n/a
9152class addbase:
9161 """Base class for addinfo and addclosehook."""
917n/a
9181 def __init__(self, fp):
919100 self.fp = fp
920100 self.read = self.fp.read
921100 self.readline = self.fp.readline
922100 if hasattr(self.fp, "readlines"): self.readlines = self.fp.readlines
923100 if hasattr(self.fp, "fileno"):
92493 self.fileno = self.fp.fileno
925n/a else:
9267 self.fileno = lambda: None
927100 if hasattr(self.fp, "__iter__"):
92897 self.__iter__ = self.fp.__iter__
92997 if hasattr(self.fp, "next"):
93097 self.next = self.fp.next
931n/a
9321 def __repr__(self):
9330 return '<%s at %r whose fp = %r>' % (self.__class__.__name__,
9340 id(self), self.fp)
935n/a
9361 def close(self):
93763 self.read = None
93863 self.readline = None
93963 self.readlines = None
94063 self.fileno = None
94163 if self.fp: self.fp.close()
94263 self.fp = None
943n/a
9442class addclosehook(addbase):
9451 """Class to add a close hook to an open file."""
946n/a
9471 def __init__(self, fp, closehook, *hookargs):
9486 addbase.__init__(self, fp)
9496 self.closehook = closehook
9506 self.hookargs = hookargs
951n/a
9521 def close(self):
9532 addbase.close(self)
9542 if self.closehook:
9552 self.closehook(*self.hookargs)
9562 self.closehook = None
9572 self.hookargs = None
958n/a
9592class addinfo(addbase):
9601 """class to add an info() method to an open file."""
961n/a
9621 def __init__(self, fp, headers):
9630 addbase.__init__(self, fp)
9640 self.headers = headers
965n/a
9661 def info(self):
9670 return self.headers
968n/a
9692class addinfourl(addbase):
9701 """class to add info() and geturl() methods to an open file."""
971n/a
9721 def __init__(self, fp, headers, url, code=None):
97394 addbase.__init__(self, fp)
97494 self.headers = headers
97594 self.url = url
97694 self.code = code
977n/a
9781 def info(self):
97963 return self.headers
980n/a
9811 def getcode(self):
9823 return self.code
983n/a
9841 def geturl(self):
98510 return self.url
986n/a
987n/a
988n/a# Utilities to parse URLs (most of these return None for missing parts):
989n/a# unwrap('<URL:type://host/path>') --> 'type://host/path'
990n/a# splittype('type:opaquestring') --> 'type', 'opaquestring'
991n/a# splithost('//host[:port]/path') --> 'host[:port]', '/path'
992n/a# splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'
993n/a# splitpasswd('user:passwd') -> 'user', 'passwd'
994n/a# splitport('host:port') --> 'host', 'port'
995n/a# splitquery('/path?query') --> '/path', 'query'
996n/a# splittag('/path#tag') --> '/path', 'tag'
997n/a# splitattr('/path;attr1=value1;attr2=value2;...') ->
998n/a# '/path', ['attr1=value1', 'attr2=value2', ...]
999n/a# splitvalue('attr=value') --> 'attr', 'value'
1000n/a# unquote('abc%20def') -> 'abc def'
1001n/a# quote('abc def') -> 'abc%20def')
1002n/a
10031try:
10041 unicode
10050except NameError:
10060 def _is_unicode(x):
10070 return 0
1008n/aelse:
10091 def _is_unicode(x):
101046 return isinstance(x, unicode)
1011n/a
10121def toBytes(url):
1013n/a """toBytes(u"URL") --> 'URL'."""
1014n/a # Most URL schemes require ASCII. If that changes, the conversion
1015n/a # can be relaxed
101645 if _is_unicode(url):
10170 try:
10180 url = url.encode("ASCII")
10190 except UnicodeError:
10200 raise UnicodeError("URL " + repr(url) +
10210 " contains non-ASCII characters")
102245 return url
1023n/a
10241def unwrap(url):
1025n/a """unwrap('<URL:type://host/path>') --> 'type://host/path'."""
1026395 url = url.strip()
1027395 if url[:1] == '<' and url[-1:] == '>':
10280 url = url[1:-1].strip()
1029395 if url[:4] == 'URL:': url = url[4:].strip()
1030395 return url
1031n/a
10321_typeprog = None
10331def splittype(url):
1034n/a """splittype('type:opaquestring') --> 'type', 'opaquestring'."""
1035n/a global _typeprog
1036286 if _typeprog is None:
10371 import re
10381 _typeprog = re.compile('^([^/:]+):')
1039n/a
1040286 match = _typeprog.match(url)
1041286 if match:
1042250 scheme = match.group(1)
1043250 return scheme.lower(), url[len(scheme) + 1:]
104436 return None, url
1045n/a
10461_hostprog = None
10471def splithost(url):
1048n/a """splithost('//host[:port]/path') --> 'host[:port]', '/path'."""
1049n/a global _hostprog
1050181 if _hostprog is None:
10511 import re
10521 _hostprog = re.compile('^//([^/?]*)(.*)$')
1053n/a
1054181 match = _hostprog.match(url)
1055181 if match: return match.group(1, 2)
105614 return None, url
1057n/a
10581_userprog = None
10591def splituser(host):
1060n/a """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'."""
1061n/a global _userprog
106285 if _userprog is None:
10631 import re
10641 _userprog = re.compile('^(.*)@(.*)$')
1065n/a
106685 match = _userprog.match(host)
106785 if match: return map(unquote, match.group(1, 2))
106879 return None, host
1069n/a
10701_passwdprog = None
10711def splitpasswd(user):
1072n/a """splitpasswd('user:passwd') -> 'user', 'passwd'."""
1073n/a global _passwdprog
107413 if _passwdprog is None:
10751 import re
10761 _passwdprog = re.compile('^([^:]*):(.*)$',re.S)
1077n/a
107813 match = _passwdprog.match(user)
107913 if match: return match.group(1, 2)
10800 return user, None
1081n/a
1082n/a# splittag('/path#tag') --> '/path', 'tag'
10831_portprog = None
10841def splitport(host):
1085n/a """splitport('host:port') --> 'host', 'port'."""
1086n/a global _portprog
1087125 if _portprog is None:
10881 import re
10891 _portprog = re.compile('^(.*):([0-9]+)$')
1090n/a
1091125 match = _portprog.match(host)
1092125 if match: return match.group(1, 2)
109389 return host, None
1094n/a
10951_nportprog = None
10961def splitnport(host, defport=-1):
1097n/a """Split host and port, returning numeric port.
1098n/a Return given default port if no ':' found; defaults to -1.
1099n/a Return numerical port if a valid number are found after ':'.
1100n/a Return None if ':' but not a valid number."""
1101n/a global _nportprog
11020 if _nportprog is None:
11030 import re
11040 _nportprog = re.compile('^(.*):(.*)$')
1105n/a
11060 match = _nportprog.match(host)
11070 if match:
11080 host, port = match.group(1, 2)
11090 try:
11100 if not port: raise ValueError, "no digits"
11110 nport = int(port)
11120 except ValueError:
11130 nport = None
11140 return host, nport
11150 return host, defport
1116n/a
11171_queryprog = None
11181def splitquery(url):
1119n/a """splitquery('/path?query') --> '/path', 'query'."""
1120n/a global _queryprog
11213 if _queryprog is None:
11221 import re
11231 _queryprog = re.compile('^(.*)\?([^?]*)$')
1124n/a
11253 match = _queryprog.match(url)
11263 if match: return match.group(1, 2)
11273 return url, None
1128n/a
11291_tagprog = None
11301def splittag(url):
1131n/a """splittag('/path#tag') --> '/path', 'tag'."""
1132n/a global _tagprog
11330 if _tagprog is None:
11340 import re
11350 _tagprog = re.compile('^(.*)#([^#]*)$')
1136n/a
11370 match = _tagprog.match(url)
11380 if match: return match.group(1, 2)
11390 return url, None
1140n/a
11411def splitattr(url):
1142n/a """splitattr('/path;attr1=value1;attr2=value2;...') ->
1143n/a '/path', ['attr1=value1', 'attr2=value2', ...]."""
114415 words = url.split(';')
114515 return words[0], words[1:]
1146n/a
11471_valueprog = None
11481def splitvalue(attr):
1149n/a """splitvalue('attr=value') --> 'attr', 'value'."""
1150n/a global _valueprog
11511 if _valueprog is None:
11521 import re
11531 _valueprog = re.compile('^([^=]*)=(.*)$')
1154n/a
11551 match = _valueprog.match(attr)
11561 if match: return match.group(1, 2)
11570 return attr, None
1158n/a
1159n/a# urlparse contains a duplicate of this method to avoid a circular import. If
1160n/a# you update this method, also update the copy in urlparse. This code
1161n/a# duplication does not exist in Python3.
1162n/a
11631_hexdig = '0123456789ABCDEFabcdef'
1164508_hextochr = dict((a + b, chr(int(a + b, 16)))
11651 for a in _hexdig for b in _hexdig)
1166n/a
11671def unquote(s):
1168n/a """unquote('abc%20def') -> 'abc def'."""
1169775 res = s.split('%')
1170n/a # fastpath
1171775 if len(res) == 1:
1172423 return s
1173352 s = res[0]
11741272 for item in res[1:]:
1175920 try:
1176920 s += _hextochr[item[:2]] + item[2:]
11775 except KeyError:
11783 s += '%' + item
11792 except UnicodeDecodeError:
11802 s += unichr(int(item[:2], 16)) + item[2:]
1181352 return s
1182n/a
11831def unquote_plus(s):
1184n/a """unquote('%7e/abc+def') -> '~/abc def'"""
1185130 s = s.replace('+', ' ')
1186130 return unquote(s)
1187n/a
11881always_safe = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'
1189n/a 'abcdefghijklmnopqrstuvwxyz'
1190n/a '0123456789' '_.-')
11911_safe_map = {}
1192257for i, c in zip(xrange(256), str(bytearray(xrange(256)))):
1193256 _safe_map[c] = c if (i < 128 and c in always_safe) else '%{:02X}'.format(i)
11941_safe_quoters = {}
1195n/a
11961def quote(s, safe='/'):
1197n/a """quote('abc def') -> 'abc%20def'
1198n/a
1199n/a Each part of a URL, e.g. the path info, the query, etc., has a
1200n/a different set of reserved characters that must be quoted.
1201n/a
1202n/a RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists
1203n/a the following reserved characters.
1204n/a
1205n/a reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
1206n/a "$" | ","
1207n/a
1208n/a Each of these characters is reserved in some component of a URL,
1209n/a but not necessarily in all of them.
1210n/a
1211n/a By default, the quote function is intended for quoting the path
1212n/a section of a URL. Thus, it will not encode '/'. This character
1213n/a is reserved, but in typical usage the quote function is being
1214n/a called on a path where the existing slash characters are used as
1215n/a reserved characters.
1216n/a """
1217n/a # fastpath
1218590 if not s:
121923 return s
1220567 cachekey = (safe, always_safe)
1221567 try:
1222567 (quoter, safe) = _safe_quoters[cachekey]
12237 except KeyError:
12247 safe_map = _safe_map.copy()
122550 safe_map.update([(c, c) for c in safe])
12267 quoter = safe_map.__getitem__
12277 safe = always_safe + safe
12287 _safe_quoters[cachekey] = (quoter, safe)
1229567 if not s.rstrip(safe):
1230421 return s
1231146 return ''.join(map(quoter, s))
1232n/a
12331def quote_plus(s, safe=''):
1234n/a """Quote the query fragment of a URL; replacing ' ' with '+'"""
123581 if ' ' in s:
12368 s = quote(s, safe + ' ')
12378 return s.replace(' ', '+')
123873 return quote(s, safe)
1239n/a
12401def urlencode(query, doseq=0):
1241n/a """Encode a sequence of two-element tuples or dictionary into a URL query string.
1242n/a
1243n/a If any values in the query arg are sequences and doseq is true, each
1244n/a sequence element is converted to a separate parameter.
1245n/a
1246n/a If the query arg is a sequence of two-element tuples, the order of the
1247n/a parameters in the output will match the order of parameters in the
1248n/a input.
1249n/a """
1250n/a
12517 if hasattr(query,"items"):
1252n/a # mapping objects
12536 query = query.items()
1254n/a else:
1255n/a # it's a bother at times that strings and string-like objects are
1256n/a # sequences...
12571 try:
1258n/a # non-sequence items should not work with len()
1259n/a # non-empty strings will fail this
12601 if len(query) and not isinstance(query[0], tuple):
12610 raise TypeError
1262n/a # zero-length sequences of all types will get here and succeed,
1263n/a # but that's a minor nit - since the original implementation
1264n/a # allowed empty dicts that type of behavior probably should be
1265n/a # preserved for consistency
12660 except TypeError:
12670 ty,va,tb = sys.exc_info()
12680 raise TypeError, "not a valid non-string sequence or mapping object", tb
1269n/a
12707 l = []
12717 if not doseq:
1272n/a # preserve old behavior
127318 for k, v in query:
127412 k = quote_plus(str(k))
127512 v = quote_plus(str(v))
127612 l.append(k + '=' + v)
1277n/a else:
12782 for k, v in query:
12791 k = quote_plus(str(k))
12801 if isinstance(v, str):
12810 v = quote_plus(v)
12820 l.append(k + '=' + v)
12831 elif _is_unicode(v):
1284n/a # is there a reasonable way to convert to ASCII?
1285n/a # encode generates a string, but "replace" or "ignore"
1286n/a # lose information and "strict" can raise UnicodeError
12870 v = quote_plus(v.encode("ASCII","replace"))
12880 l.append(k + '=' + v)
1289n/a else:
12901 try:
1291n/a # is this a sufficient test for sequence-ness?
12921 len(v)
12930 except TypeError:
1294n/a # not a sequence
12950 v = quote_plus(str(v))
12960 l.append(k + '=' + v)
1297n/a else:
1298n/a # loop over the sequence
12994 for elt in v:
13003 l.append(k + '=' + quote_plus(str(elt)))
13017 return '&'.join(l)
1302n/a
1303n/a# Proxy handling
13041def getproxies_environment():
1305n/a """Return a dictionary of scheme -> proxy server URL mappings.
1306n/a
1307n/a Scan the environment for variables named <scheme>_proxy;
1308n/a this seems to be the standard convention. If you need a
1309n/a different way, you can pass a proxies dictionary to the
1310n/a [Fancy]URLopener constructor.
1311n/a
1312n/a """
131317 proxies = {}
1314630 for name, value in os.environ.items():
1315613 name = name.lower()
1316613 if value and name[-6:] == '_proxy':
13171 proxies[name[:-6]] = value
131817 return proxies
1319n/a
13201def proxy_bypass_environment(host):
1321n/a """Test if proxies should not be used for a particular host.
1322n/a
1323n/a Checks the environment for a variable named no_proxy, which should
1324n/a be a list of DNS suffixes separated by commas, or '*' for all hosts.
1325n/a """
132617 no_proxy = os.environ.get('no_proxy', '') or os.environ.get('NO_PROXY', '')
1327n/a # '*' is special case for always bypass
132817 if no_proxy == '*':
13290 return 1
1330n/a # strip port off host
133117 hostonly, port = splitport(host)
1332n/a # check if the host ends with any of the DNS suffixes
133333 for name in no_proxy.split(','):
133417 if name and (hostonly.endswith(name) or host.endswith(name)):
13351 return 1
1336n/a # otherwise, don't bypass
133716 return 0
1338n/a
1339n/a
13401if sys.platform == 'darwin':
13410 from _scproxy import _get_proxy_settings, _get_proxies
1342n/a
13430 def proxy_bypass_macosx_sysconf(host):
1344n/a """
1345n/a Return True iff this host shouldn't be accessed using a proxy
1346n/a
1347n/a This function uses the MacOSX framework SystemConfiguration
1348n/a to fetch the proxy information.
1349n/a """
13500 import re
13510 import socket
13520 from fnmatch import fnmatch
1353n/a
13540 hostonly, port = splitport(host)
1355n/a
13560 def ip2num(ipAddr):
13570 parts = ipAddr.split('.')
13580 parts = map(int, parts)
13590 if len(parts) != 4:
13600 parts = (parts + [0, 0, 0, 0])[:4]
13610 return (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3]
1362n/a
13630 proxy_settings = _get_proxy_settings()
1364n/a
1365n/a # Check for simple host names:
13660 if '.' not in host:
13670 if proxy_settings['exclude_simple']:
13680 return True
1369n/a
13700 hostIP = None
1371n/a
13720 for value in proxy_settings.get('exceptions', ()):
1373n/a # Items in the list are strings like these: *.local, 169.254/16
13740 if not value: continue
1375n/a
13760 m = re.match(r"(\d+(?:\.\d+)*)(/\d+)?", value)
13770 if m is not None:
13780 if hostIP is None:
13790 try:
13800 hostIP = socket.gethostbyname(hostonly)
13810 hostIP = ip2num(hostIP)
13820 except socket.error:
13830 continue
1384n/a
13850 base = ip2num(m.group(1))
13860 mask = m.group(2)
13870 if mask is None:
13880 mask = 8 * (m.group(1).count('.') + 1)
1389n/a
1390n/a else:
13910 mask = int(mask[1:])
13920 mask = 32 - mask
1393n/a
13940 if (hostIP >> mask) == (base >> mask):
13950 return True
1396n/a
13970 elif fnmatch(host, value):
13980 return True
1399n/a
14000 return False
1401n/a
14020 def getproxies_macosx_sysconf():
1403n/a """Return a dictionary of scheme -> proxy server URL mappings.
1404n/a
1405n/a This function uses the MacOSX framework SystemConfiguration
1406n/a to fetch the proxy information.
1407n/a """
14080 return _get_proxies()
1409n/a
14100 def proxy_bypass(host):
14110 if getproxies_environment():
14120 return proxy_bypass_environment(host)
1413n/a else:
14140 return proxy_bypass_macosx_sysconf(host)
1415n/a
14160 def getproxies():
14170 return getproxies_environment() or getproxies_macosx_sysconf()
1418n/a
14191elif os.name == 'nt':
14200 def getproxies_registry():
1421n/a """Return a dictionary of scheme -> proxy server URL mappings.
1422n/a
1423n/a Win32 uses the registry to store proxies.
1424n/a
1425n/a """
14260 proxies = {}
14270 try:
14280 import _winreg
14290 except ImportError:
1430n/a # Std module, so should be around - but you never know!
14310 return proxies
14320 try:
14330 internetSettings = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,
14340 r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
14350 proxyEnable = _winreg.QueryValueEx(internetSettings,
14360 'ProxyEnable')[0]
14370 if proxyEnable:
1438n/a # Returned as Unicode but problems if not converted to ASCII
14390 proxyServer = str(_winreg.QueryValueEx(internetSettings,
14400 'ProxyServer')[0])
14410 if '=' in proxyServer:
1442n/a # Per-protocol settings
14430 for p in proxyServer.split(';'):
14440 protocol, address = p.split('=', 1)
1445n/a # See if address has a type:// prefix
14460 import re
14470 if not re.match('^([^/:]+)://', address):
14480 address = '%s://%s' % (protocol, address)
14490 proxies[protocol] = address
1450n/a else:
1451n/a # Use one setting for all protocols
14520 if proxyServer[:5] == 'http:':
14530 proxies['http'] = proxyServer
1454n/a else:
14550 proxies['http'] = 'http://%s' % proxyServer
14560 proxies['ftp'] = 'ftp://%s' % proxyServer
14570 internetSettings.Close()
14580 except (WindowsError, ValueError, TypeError):
1459n/a # Either registry key not found etc, or the value in an
1460n/a # unexpected format.
1461n/a # proxies already set up to be empty so nothing to do
14620 pass
14630 return proxies
1464n/a
14650 def getproxies():
1466n/a """Return a dictionary of scheme -> proxy server URL mappings.
1467n/a
1468n/a Returns settings gathered from the environment, if specified,
1469n/a or the registry.
1470n/a
1471n/a """
14720 return getproxies_environment() or getproxies_registry()
1473n/a
14740 def proxy_bypass_registry(host):
14750 try:
14760 import _winreg
14770 import re
14780 except ImportError:
1479n/a # Std modules, so should be around - but you never know!
14800 return 0
14810 try:
14820 internetSettings = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,
14830 r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
14840 proxyEnable = _winreg.QueryValueEx(internetSettings,
14850 'ProxyEnable')[0]
14860 proxyOverride = str(_winreg.QueryValueEx(internetSettings,
14870 'ProxyOverride')[0])
1488n/a # ^^^^ Returned as Unicode but problems if not converted to ASCII
14890 except WindowsError:
14900 return 0
14910 if not proxyEnable or not proxyOverride:
14920 return 0
1493n/a # try to make a host list from name and IP address.
14940 rawHost, port = splitport(host)
14950 host = [rawHost]
14960 try:
14970 addr = socket.gethostbyname(rawHost)
14980 if addr != rawHost:
14990 host.append(addr)
15000 except socket.error:
15010 pass
15020 try:
15030 fqdn = socket.getfqdn(rawHost)
15040 if fqdn != rawHost:
15050 host.append(fqdn)
15060 except socket.error:
15070 pass
1508n/a # make a check value list from the registry entry: replace the
1509n/a # '<local>' string by the localhost entry and the corresponding
1510n/a # canonical entry.
15110 proxyOverride = proxyOverride.split(';')
1512n/a # now check if we match one of the registry values.
15130 for test in proxyOverride:
15140 if test == '<local>':
15150 if '.' not in rawHost:
15160 return 1
15170 test = test.replace(".", r"\.") # mask dots
15180 test = test.replace("*", r".*") # change glob sequence
15190 test = test.replace("?", r".") # change glob char
15200 for val in host:
1521n/a # print "%s <--> %s" %( test, val )
15220 if re.match(test, val, re.I):
15230 return 1
15240 return 0
1525n/a
15260 def proxy_bypass(host):
1527n/a """Return a dictionary of scheme -> proxy server URL mappings.
1528n/a
1529n/a Returns settings gathered from the environment, if specified,
1530n/a or the registry.
1531n/a
1532n/a """
15330 if getproxies_environment():
15340 return proxy_bypass_environment(host)
1535n/a else:
15360 return proxy_bypass_registry(host)
1537n/a
1538n/aelse:
1539n/a # By default use environment variables
15401 getproxies = getproxies_environment
15411 proxy_bypass = proxy_bypass_environment
1542n/a
1543n/a# Test and time quote() and unquote()
15441def test1():
15450 s = ''
15460 for i in range(256): s = s + chr(i)
15470 s = s*4
15480 t0 = time.time()
15490 qs = quote(s)
15500 uqs = unquote(qs)
15510 t1 = time.time()
15520 if uqs != s:
15530 print 'Wrong!'
15540 print repr(s)
15550 print repr(qs)
15560 print repr(uqs)
15570 print round(t1 - t0, 3), 'sec'
1558n/a
1559n/a
15601def reporthook(blocknum, blocksize, totalsize):
1561n/a # Report during remote transfers
15620 print "Block number: %d, Block size: %d, Total size: %d" % (
15630 blocknum, blocksize, totalsize)
1564n/a
1565n/a# Test program
15661def test(args=[]):
15670 if not args:
1568n/a args = [
15690 '/etc/passwd',
15700 'file:/etc/passwd',
15710 'file://localhost/etc/passwd',
15720 'ftp://ftp.gnu.org/pub/README',
15730 'http://www.python.org/index.html',
1574n/a ]
15750 if hasattr(URLopener, "open_https"):
15760 args.append('https://synergy.as.cmu.edu/~geek/')
15770 try:
15780 for url in args:
15790 print '-'*10, url, '-'*10
15800 fn, h = urlretrieve(url, None, reporthook)
15810 print fn
15820 if h:
15830 print '======'
15840 for k in h.keys(): print k + ':', h[k]
15850 print '======'
15860 with open(fn, 'rb') as fp:
15870 data = fp.read()
15880 if '\r' in data:
15890 table = string.maketrans("", "")
15900 data = data.translate(table, "\r")
15910 print data
15920 fn, h = None, None
15930 print '-'*40
1594n/a finally:
15950 urlcleanup()
1596n/a
15971def main():
15980 import getopt, sys
15990 try:
16000 opts, args = getopt.getopt(sys.argv[1:], "th")
16010 except getopt.error, msg:
16020 print msg
16030 print "Use -h for help"
16040 return
16050 t = 0
16060 for o, a in opts:
16070 if o == '-t':
16080 t = t + 1
16090 if o == '-h':
16100 print "Usage: python urllib.py [-t] [url ...]"
16110 print "-t runs self-test;",
16120 print "otherwise, contents of urls are printed"
16130 return
16140 if t:
16150 if t > 1:
16160 test1()
16170 test(args)
1618n/a else:
16190 if not args:
16200 print "Use -h for help"
16210 for url in args:
16220 print urlopen(url).read(),
1623n/a
1624n/a# Run test program when run as a script
16251if __name__ == '__main__':
16260 main()