PageRenderTime 59ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/lib-python/2/urllib.py

https://bitbucket.org/Martell/pypy
Python | 1604 lines | 1593 code | 3 blank | 8 comment | 29 complexity | 1250566277305b4b02ca18d3a6ea5e02 MD5 | raw file
Possible License(s): Apache-2.0

Large files files are truncated, but you can click here to view the full file

  1. """Open an arbitrary URL.
  2. See the following document for more info on URLs:
  3. "Names and Addresses, URIs, URLs, URNs, URCs", at
  4. http://www.w3.org/pub/WWW/Addressing/Overview.html
  5. See also the HTTP spec (from which the error codes are derived):
  6. "HTTP - Hypertext Transfer Protocol", at
  7. http://www.w3.org/pub/WWW/Protocols/
  8. Related standards and specs:
  9. - RFC1808: the "relative URL" spec. (authoritative status)
  10. - RFC1738 - the "URL standard". (authoritative status)
  11. - RFC1630 - the "URI spec". (informational status)
  12. The object returned by URLopener().open(file) will differ per
  13. protocol. All you know is that is has methods read(), readline(),
  14. readlines(), fileno(), close() and info(). The read*(), fileno()
  15. and close() methods work like those of open files.
  16. The info() method returns a mimetools.Message object which can be
  17. used to query various info about the object, if available.
  18. (mimetools.Message objects are queried with the getheader() method.)
  19. """
  20. import string
  21. import socket
  22. import os
  23. import time
  24. import sys
  25. import base64
  26. from urlparse import urljoin as basejoin
  27. __all__ = ["urlopen", "URLopener", "FancyURLopener", "urlretrieve",
  28. "urlcleanup", "quote", "quote_plus", "unquote", "unquote_plus",
  29. "urlencode", "url2pathname", "pathname2url", "splittag",
  30. "localhost", "thishost", "ftperrors", "basejoin", "unwrap",
  31. "splittype", "splithost", "splituser", "splitpasswd", "splitport",
  32. "splitnport", "splitquery", "splitattr", "splitvalue",
  33. "getproxies"]
  34. __version__ = '1.17' # XXX This version is not always updated :-(
  35. MAXFTPCACHE = 10 # Trim the ftp cache beyond this size
  36. # Helper for non-unix systems
  37. if os.name == 'nt':
  38. from nturl2path import url2pathname, pathname2url
  39. elif os.name == 'riscos':
  40. from rourl2path import url2pathname, pathname2url
  41. else:
  42. def url2pathname(pathname):
  43. """OS-specific conversion from a relative URL of the 'file' scheme
  44. to a file system path; not recommended for general use."""
  45. return unquote(pathname)
  46. def pathname2url(pathname):
  47. """OS-specific conversion from a file system path to a relative URL
  48. of the 'file' scheme; not recommended for general use."""
  49. return quote(pathname)
  50. # This really consists of two pieces:
  51. # (1) a class which handles opening of all sorts of URLs
  52. # (plus assorted utilities etc.)
  53. # (2) a set of functions for parsing URLs
  54. # XXX Should these be separated out into different modules?
  55. # Shortcut for basic usage
  56. _urlopener = None
  57. def urlopen(url, data=None, proxies=None):
  58. """Create a file-like object for the specified URL to read from."""
  59. from warnings import warnpy3k
  60. warnpy3k("urllib.urlopen() has been removed in Python 3.0 in "
  61. "favor of urllib2.urlopen()", stacklevel=2)
  62. global _urlopener
  63. if proxies is not None:
  64. opener = FancyURLopener(proxies=proxies)
  65. elif not _urlopener:
  66. opener = FancyURLopener()
  67. _urlopener = opener
  68. else:
  69. opener = _urlopener
  70. if data is None:
  71. return opener.open(url)
  72. else:
  73. return opener.open(url, data)
  74. def urlretrieve(url, filename=None, reporthook=None, data=None):
  75. global _urlopener
  76. if not _urlopener:
  77. _urlopener = FancyURLopener()
  78. return _urlopener.retrieve(url, filename, reporthook, data)
  79. def urlcleanup():
  80. if _urlopener:
  81. _urlopener.cleanup()
  82. _safe_quoters.clear()
  83. ftpcache.clear()
  84. # check for SSL
  85. try:
  86. import ssl
  87. except:
  88. _have_ssl = False
  89. else:
  90. _have_ssl = True
  91. # exception raised when downloaded size does not match content-length
  92. class ContentTooShortError(IOError):
  93. def __init__(self, message, content):
  94. IOError.__init__(self, message)
  95. self.content = content
  96. ftpcache = {}
  97. class URLopener:
  98. """Class to open URLs.
  99. This is a class rather than just a subroutine because we may need
  100. more than one set of global protocol-specific options.
  101. Note -- this is a base class for those who don't want the
  102. automatic handling of errors type 302 (relocated) and 401
  103. (authorization needed)."""
  104. __tempfiles = None
  105. version = "Python-urllib/%s" % __version__
  106. # Constructor
  107. def __init__(self, proxies=None, **x509):
  108. if proxies is None:
  109. proxies = getproxies()
  110. assert hasattr(proxies, 'has_key'), "proxies must be a mapping"
  111. self.proxies = proxies
  112. self.key_file = x509.get('key_file')
  113. self.cert_file = x509.get('cert_file')
  114. self.addheaders = [('User-Agent', self.version)]
  115. self.__tempfiles = []
  116. self.__unlink = os.unlink # See cleanup()
  117. self.tempcache = None
  118. # Undocumented feature: if you assign {} to tempcache,
  119. # it is used to cache files retrieved with
  120. # self.retrieve(). This is not enabled by default
  121. # since it does not work for changing documents (and I
  122. # haven't got the logic to check expiration headers
  123. # yet).
  124. self.ftpcache = ftpcache
  125. # Undocumented feature: you can use a different
  126. # ftp cache by assigning to the .ftpcache member;
  127. # in case you want logically independent URL openers
  128. # XXX This is not threadsafe. Bah.
  129. def __del__(self):
  130. self.close()
  131. def close(self):
  132. self.cleanup()
  133. def cleanup(self):
  134. # This code sometimes runs when the rest of this module
  135. # has already been deleted, so it can't use any globals
  136. # or import anything.
  137. if self.__tempfiles:
  138. for file in self.__tempfiles:
  139. try:
  140. self.__unlink(file)
  141. except OSError:
  142. pass
  143. del self.__tempfiles[:]
  144. if self.tempcache:
  145. self.tempcache.clear()
  146. def addheader(self, *args):
  147. """Add a header to be used by the HTTP interface only
  148. e.g. u.addheader('Accept', 'sound/basic')"""
  149. self.addheaders.append(args)
  150. # External interface
  151. def open(self, fullurl, data=None):
  152. """Use URLopener().open(file) instead of open(file, 'r')."""
  153. fullurl = unwrap(toBytes(fullurl))
  154. # percent encode url, fixing lame server errors for e.g, like space
  155. # within url paths.
  156. fullurl = quote(fullurl, safe="%/:=&?~#+!$,;'@()*[]|")
  157. if self.tempcache and fullurl in self.tempcache:
  158. filename, headers = self.tempcache[fullurl]
  159. fp = open(filename, 'rb')
  160. return addinfourl(fp, headers, fullurl)
  161. urltype, url = splittype(fullurl)
  162. if not urltype:
  163. urltype = 'file'
  164. if urltype in self.proxies:
  165. proxy = self.proxies[urltype]
  166. urltype, proxyhost = splittype(proxy)
  167. host, selector = splithost(proxyhost)
  168. url = (host, fullurl) # Signal special case to open_*()
  169. else:
  170. proxy = None
  171. name = 'open_' + urltype
  172. self.type = urltype
  173. name = name.replace('-', '_')
  174. if not hasattr(self, name):
  175. if proxy:
  176. return self.open_unknown_proxy(proxy, fullurl, data)
  177. else:
  178. return self.open_unknown(fullurl, data)
  179. try:
  180. if data is None:
  181. return getattr(self, name)(url)
  182. else:
  183. return getattr(self, name)(url, data)
  184. except socket.error, msg:
  185. raise IOError, ('socket error', msg), sys.exc_info()[2]
  186. def open_unknown(self, fullurl, data=None):
  187. """Overridable interface to open unknown URL type."""
  188. type, url = splittype(fullurl)
  189. raise IOError, ('url error', 'unknown url type', type)
  190. def open_unknown_proxy(self, proxy, fullurl, data=None):
  191. """Overridable interface to open unknown URL type."""
  192. type, url = splittype(fullurl)
  193. raise IOError, ('url error', 'invalid proxy for %s' % type, proxy)
  194. # External interface
  195. def retrieve(self, url, filename=None, reporthook=None, data=None):
  196. """retrieve(url) returns (filename, headers) for a local object
  197. or (tempfilename, headers) for a remote object."""
  198. url = unwrap(toBytes(url))
  199. if self.tempcache and url in self.tempcache:
  200. return self.tempcache[url]
  201. type, url1 = splittype(url)
  202. if filename is None and (not type or type == 'file'):
  203. try:
  204. fp = self.open_local_file(url1)
  205. hdrs = fp.info()
  206. fp.close()
  207. return url2pathname(splithost(url1)[1]), hdrs
  208. except IOError:
  209. pass
  210. fp = self.open(url, data)
  211. try:
  212. headers = fp.info()
  213. if filename:
  214. tfp = open(filename, 'wb')
  215. else:
  216. import tempfile
  217. garbage, path = splittype(url)
  218. garbage, path = splithost(path or "")
  219. path, garbage = splitquery(path or "")
  220. path, garbage = splitattr(path or "")
  221. suffix = os.path.splitext(path)[1]
  222. (fd, filename) = tempfile.mkstemp(suffix)
  223. self.__tempfiles.append(filename)
  224. tfp = os.fdopen(fd, 'wb')
  225. try:
  226. result = filename, headers
  227. if self.tempcache is not None:
  228. self.tempcache[url] = result
  229. bs = 1024*8
  230. size = -1
  231. read = 0
  232. blocknum = 0
  233. if "content-length" in headers:
  234. size = int(headers["Content-Length"])
  235. if reporthook:
  236. reporthook(blocknum, bs, size)
  237. while 1:
  238. block = fp.read(bs)
  239. if block == "":
  240. break
  241. read += len(block)
  242. tfp.write(block)
  243. blocknum += 1
  244. if reporthook:
  245. reporthook(blocknum, bs, size)
  246. finally:
  247. tfp.close()
  248. finally:
  249. fp.close()
  250. # raise exception if actual size does not match content-length header
  251. if size >= 0 and read < size:
  252. raise ContentTooShortError("retrieval incomplete: got only %i out "
  253. "of %i bytes" % (read, size), result)
  254. return result
  255. # Each method named open_<type> knows how to open that type of URL
  256. def open_http(self, url, data=None):
  257. """Use HTTP protocol."""
  258. import httplib
  259. user_passwd = None
  260. proxy_passwd= None
  261. if isinstance(url, str):
  262. host, selector = splithost(url)
  263. if host:
  264. user_passwd, host = splituser(host)
  265. host = unquote(host)
  266. realhost = host
  267. else:
  268. host, selector = url
  269. # check whether the proxy contains authorization information
  270. proxy_passwd, host = splituser(host)
  271. # now we proceed with the url we want to obtain
  272. urltype, rest = splittype(selector)
  273. url = rest
  274. user_passwd = None
  275. if urltype.lower() != 'http':
  276. realhost = None
  277. else:
  278. realhost, rest = splithost(rest)
  279. if realhost:
  280. user_passwd, realhost = splituser(realhost)
  281. if user_passwd:
  282. selector = "%s://%s%s" % (urltype, realhost, rest)
  283. if proxy_bypass(realhost):
  284. host = realhost
  285. #print "proxy via http:", host, selector
  286. if not host: raise IOError, ('http error', 'no host given')
  287. if proxy_passwd:
  288. proxy_passwd = unquote(proxy_passwd)
  289. proxy_auth = base64.b64encode(proxy_passwd).strip()
  290. else:
  291. proxy_auth = None
  292. if user_passwd:
  293. user_passwd = unquote(user_passwd)
  294. auth = base64.b64encode(user_passwd).strip()
  295. else:
  296. auth = None
  297. h = httplib.HTTP(host)
  298. if data is not None:
  299. h.putrequest('POST', selector)
  300. h.putheader('Content-Type', 'application/x-www-form-urlencoded')
  301. h.putheader('Content-Length', '%d' % len(data))
  302. else:
  303. h.putrequest('GET', selector)
  304. if proxy_auth: h.putheader('Proxy-Authorization', 'Basic %s' % proxy_auth)
  305. if auth: h.putheader('Authorization', 'Basic %s' % auth)
  306. if realhost: h.putheader('Host', realhost)
  307. for args in self.addheaders: h.putheader(*args)
  308. h.endheaders(data)
  309. errcode, errmsg, headers = h.getreply()
  310. fp = h.getfile()
  311. if errcode == -1:
  312. if fp: fp.close()
  313. # something went wrong with the HTTP status line
  314. raise IOError, ('http protocol error', 0,
  315. 'got a bad status line', None)
  316. # According to RFC 2616, "2xx" code indicates that the client's
  317. # request was successfully received, understood, and accepted.
  318. if (200 <= errcode < 300):
  319. return addinfourl(fp, headers, "http:" + url, errcode)
  320. else:
  321. if data is None:
  322. return self.http_error(url, fp, errcode, errmsg, headers)
  323. else:
  324. return self.http_error(url, fp, errcode, errmsg, headers, data)
  325. def http_error(self, url, fp, errcode, errmsg, headers, data=None):
  326. """Handle http errors.
  327. Derived class can override this, or provide specific handlers
  328. named http_error_DDD where DDD is the 3-digit error code."""
  329. # First check if there's a specific handler for this error
  330. name = 'http_error_%d' % errcode
  331. if hasattr(self, name):
  332. method = getattr(self, name)
  333. if data is None:
  334. result = method(url, fp, errcode, errmsg, headers)
  335. else:
  336. result = method(url, fp, errcode, errmsg, headers, data)
  337. if result: return result
  338. return self.http_error_default(url, fp, errcode, errmsg, headers)
  339. def http_error_default(self, url, fp, errcode, errmsg, headers):
  340. """Default error handler: close the connection and raise IOError."""
  341. fp.close()
  342. raise IOError, ('http error', errcode, errmsg, headers)
  343. if _have_ssl:
  344. def open_https(self, url, data=None):
  345. """Use HTTPS protocol."""
  346. import httplib
  347. user_passwd = None
  348. proxy_passwd = None
  349. if isinstance(url, str):
  350. host, selector = splithost(url)
  351. if host:
  352. user_passwd, host = splituser(host)
  353. host = unquote(host)
  354. realhost = host
  355. else:
  356. host, selector = url
  357. # here, we determine, whether the proxy contains authorization information
  358. proxy_passwd, host = splituser(host)
  359. urltype, rest = splittype(selector)
  360. url = rest
  361. user_passwd = None
  362. if urltype.lower() != 'https':
  363. realhost = None
  364. else:
  365. realhost, rest = splithost(rest)
  366. if realhost:
  367. user_passwd, realhost = splituser(realhost)
  368. if user_passwd:
  369. selector = "%s://%s%s" % (urltype, realhost, rest)
  370. #print "proxy via https:", host, selector
  371. if not host: raise IOError, ('https error', 'no host given')
  372. if proxy_passwd:
  373. proxy_passwd = unquote(proxy_passwd)
  374. proxy_auth = base64.b64encode(proxy_passwd).strip()
  375. else:
  376. proxy_auth = None
  377. if user_passwd:
  378. user_passwd = unquote(user_passwd)
  379. auth = base64.b64encode(user_passwd).strip()
  380. else:
  381. auth = None
  382. h = httplib.HTTPS(host, 0,
  383. key_file=self.key_file,
  384. cert_file=self.cert_file)
  385. if data is not None:
  386. h.putrequest('POST', selector)
  387. h.putheader('Content-Type',
  388. 'application/x-www-form-urlencoded')
  389. h.putheader('Content-Length', '%d' % len(data))
  390. else:
  391. h.putrequest('GET', selector)
  392. if proxy_auth: h.putheader('Proxy-Authorization', 'Basic %s' % proxy_auth)
  393. if auth: h.putheader('Authorization', 'Basic %s' % auth)
  394. if realhost: h.putheader('Host', realhost)
  395. for args in self.addheaders: h.putheader(*args)
  396. h.endheaders(data)
  397. errcode, errmsg, headers = h.getreply()
  398. fp = h.getfile()
  399. if errcode == -1:
  400. if fp: fp.close()
  401. # something went wrong with the HTTP status line
  402. raise IOError, ('http protocol error', 0,
  403. 'got a bad status line', None)
  404. # According to RFC 2616, "2xx" code indicates that the client's
  405. # request was successfully received, understood, and accepted.
  406. if (200 <= errcode < 300):
  407. return addinfourl(fp, headers, "https:" + url, errcode)
  408. else:
  409. if data is None:
  410. return self.http_error(url, fp, errcode, errmsg, headers)
  411. else:
  412. return self.http_error(url, fp, errcode, errmsg, headers,
  413. data)
  414. def open_file(self, url):
  415. """Use local file or FTP depending on form of URL."""
  416. if not isinstance(url, str):
  417. raise IOError, ('file error', 'proxy support for file protocol currently not implemented')
  418. if url[:2] == '//' and url[2:3] != '/' and url[2:12].lower() != 'localhost/':
  419. return self.open_ftp(url)
  420. else:
  421. return self.open_local_file(url)
  422. def open_local_file(self, url):
  423. """Use local file."""
  424. import mimetypes, mimetools, email.utils
  425. try:
  426. from cStringIO import StringIO
  427. except ImportError:
  428. from StringIO import StringIO
  429. host, file = splithost(url)
  430. localname = url2pathname(file)
  431. try:
  432. stats = os.stat(localname)
  433. except OSError, e:
  434. raise IOError(e.errno, e.strerror, e.filename)
  435. size = stats.st_size
  436. modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
  437. mtype = mimetypes.guess_type(url)[0]
  438. headers = mimetools.Message(StringIO(
  439. 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' %
  440. (mtype or 'text/plain', size, modified)))
  441. if not host:
  442. urlfile = file
  443. if file[:1] == '/':
  444. urlfile = 'file://' + file
  445. elif file[:2] == './':
  446. raise ValueError("local file url may start with / or file:. Unknown url of type: %s" % url)
  447. return addinfourl(open(localname, 'rb'),
  448. headers, urlfile)
  449. host, port = splitport(host)
  450. if not port \
  451. and socket.gethostbyname(host) in (localhost(), thishost()):
  452. urlfile = file
  453. if file[:1] == '/':
  454. urlfile = 'file://' + file
  455. return addinfourl(open(localname, 'rb'),
  456. headers, urlfile)
  457. raise IOError, ('local file error', 'not on local host')
  458. def open_ftp(self, url):
  459. """Use FTP protocol."""
  460. if not isinstance(url, str):
  461. raise IOError, ('ftp error', 'proxy support for ftp protocol currently not implemented')
  462. import mimetypes, mimetools
  463. try:
  464. from cStringIO import StringIO
  465. except ImportError:
  466. from StringIO import StringIO
  467. host, path = splithost(url)
  468. if not host: raise IOError, ('ftp error', 'no host given')
  469. host, port = splitport(host)
  470. user, host = splituser(host)
  471. if user: user, passwd = splitpasswd(user)
  472. else: passwd = None
  473. host = unquote(host)
  474. user = user or ''
  475. passwd = passwd or ''
  476. host = socket.gethostbyname(host)
  477. if not port:
  478. import ftplib
  479. port = ftplib.FTP_PORT
  480. else:
  481. port = int(port)
  482. path, attrs = splitattr(path)
  483. path = unquote(path)
  484. dirs = path.split('/')
  485. dirs, file = dirs[:-1], dirs[-1]
  486. if dirs and not dirs[0]: dirs = dirs[1:]
  487. if dirs and not dirs[0]: dirs[0] = '/'
  488. key = user, host, port, '/'.join(dirs)
  489. # XXX thread unsafe!
  490. if len(self.ftpcache) > MAXFTPCACHE:
  491. # Prune the cache, rather arbitrarily
  492. for k in self.ftpcache.keys():
  493. if k != key:
  494. v = self.ftpcache[k]
  495. del self.ftpcache[k]
  496. v.close()
  497. try:
  498. if not key in self.ftpcache:
  499. self.ftpcache[key] = \
  500. ftpwrapper(user, passwd, host, port, dirs)
  501. if not file: type = 'D'
  502. else: type = 'I'
  503. for attr in attrs:
  504. attr, value = splitvalue(attr)
  505. if attr.lower() == 'type' and \
  506. value in ('a', 'A', 'i', 'I', 'd', 'D'):
  507. type = value.upper()
  508. (fp, retrlen) = self.ftpcache[key].retrfile(file, type)
  509. mtype = mimetypes.guess_type("ftp:" + url)[0]
  510. headers = ""
  511. if mtype:
  512. headers += "Content-Type: %s\n" % mtype
  513. if retrlen is not None and retrlen >= 0:
  514. headers += "Content-Length: %d\n" % retrlen
  515. headers = mimetools.Message(StringIO(headers))
  516. return addinfourl(fp, headers, "ftp:" + url)
  517. except ftperrors(), msg:
  518. raise IOError, ('ftp error', msg), sys.exc_info()[2]
  519. def open_data(self, url, data=None):
  520. """Use "data" URL."""
  521. if not isinstance(url, str):
  522. raise IOError, ('data error', 'proxy support for data protocol currently not implemented')
  523. # ignore POSTed data
  524. #
  525. # syntax of data URLs:
  526. # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
  527. # mediatype := [ type "/" subtype ] *( ";" parameter )
  528. # data := *urlchar
  529. # parameter := attribute "=" value
  530. import mimetools
  531. try:
  532. from cStringIO import StringIO
  533. except ImportError:
  534. from StringIO import StringIO
  535. try:
  536. [type, data] = url.split(',', 1)
  537. except ValueError:
  538. raise IOError, ('data error', 'bad data URL')
  539. if not type:
  540. type = 'text/plain;charset=US-ASCII'
  541. semi = type.rfind(';')
  542. if semi >= 0 and '=' not in type[semi:]:
  543. encoding = type[semi+1:]
  544. type = type[:semi]
  545. else:
  546. encoding = ''
  547. msg = []
  548. msg.append('Date: %s'%time.strftime('%a, %d %b %Y %H:%M:%S GMT',
  549. time.gmtime(time.time())))
  550. msg.append('Content-type: %s' % type)
  551. if encoding == 'base64':
  552. data = base64.decodestring(data)
  553. else:
  554. data = unquote(data)
  555. msg.append('Content-Length: %d' % len(data))
  556. msg.append('')
  557. msg.append(data)
  558. msg = '\n'.join(msg)
  559. f = StringIO(msg)
  560. headers = mimetools.Message(f, 0)
  561. #f.fileno = None # needed for addinfourl
  562. return addinfourl(f, headers, url)
  563. class FancyURLopener(URLopener):
  564. """Derived class with handlers for errors we can handle (perhaps)."""
  565. def __init__(self, *args, **kwargs):
  566. URLopener.__init__(self, *args, **kwargs)
  567. self.auth_cache = {}
  568. self.tries = 0
  569. self.maxtries = 10
  570. def http_error_default(self, url, fp, errcode, errmsg, headers):
  571. """Default error handling -- don't raise an exception."""
  572. return addinfourl(fp, headers, "http:" + url, errcode)
  573. def http_error_302(self, url, fp, errcode, errmsg, headers, data=None):
  574. """Error 302 -- relocated (temporarily)."""
  575. self.tries += 1
  576. if self.maxtries and self.tries >= self.maxtries:
  577. if hasattr(self, "http_error_500"):
  578. meth = self.http_error_500
  579. else:
  580. meth = self.http_error_default
  581. self.tries = 0
  582. return meth(url, fp, 500,
  583. "Internal Server Error: Redirect Recursion", headers)
  584. result = self.redirect_internal(url, fp, errcode, errmsg, headers,
  585. data)
  586. self.tries = 0
  587. return result
  588. def redirect_internal(self, url, fp, errcode, errmsg, headers, data):
  589. if 'location' in headers:
  590. newurl = headers['location']
  591. elif 'uri' in headers:
  592. newurl = headers['uri']
  593. else:
  594. return
  595. fp.close()
  596. # In case the server sent a relative URL, join with original:
  597. newurl = basejoin(self.type + ":" + url, newurl)
  598. # For security reasons we do not allow redirects to protocols
  599. # other than HTTP, HTTPS or FTP.
  600. newurl_lower = newurl.lower()
  601. if not (newurl_lower.startswith('http://') or
  602. newurl_lower.startswith('https://') or
  603. newurl_lower.startswith('ftp://')):
  604. raise IOError('redirect error', errcode,
  605. errmsg + " - Redirection to url '%s' is not allowed" %
  606. newurl,
  607. headers)
  608. return self.open(newurl)
  609. def http_error_301(self, url, fp, errcode, errmsg, headers, data=None):
  610. """Error 301 -- also relocated (permanently)."""
  611. return self.http_error_302(url, fp, errcode, errmsg, headers, data)
  612. def http_error_303(self, url, fp, errcode, errmsg, headers, data=None):
  613. """Error 303 -- also relocated (essentially identical to 302)."""
  614. return self.http_error_302(url, fp, errcode, errmsg, headers, data)
  615. def http_error_307(self, url, fp, errcode, errmsg, headers, data=None):
  616. """Error 307 -- relocated, but turn POST into error."""
  617. if data is None:
  618. return self.http_error_302(url, fp, errcode, errmsg, headers, data)
  619. else:
  620. return self.http_error_default(url, fp, errcode, errmsg, headers)
  621. def http_error_401(self, url, fp, errcode, errmsg, headers, data=None):
  622. """Error 401 -- authentication required.
  623. This function supports Basic authentication only."""
  624. if not 'www-authenticate' in headers:
  625. URLopener.http_error_default(self, url, fp,
  626. errcode, errmsg, headers)
  627. stuff = headers['www-authenticate']
  628. import re
  629. match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
  630. if not match:
  631. URLopener.http_error_default(self, url, fp,
  632. errcode, errmsg, headers)
  633. scheme, realm = match.groups()
  634. if scheme.lower() != 'basic':
  635. URLopener.http_error_default(self, url, fp,
  636. errcode, errmsg, headers)
  637. name = 'retry_' + self.type + '_basic_auth'
  638. if data is None:
  639. return getattr(self,name)(url, realm)
  640. else:
  641. return getattr(self,name)(url, realm, data)
  642. def http_error_407(self, url, fp, errcode, errmsg, headers, data=None):
  643. """Error 407 -- proxy authentication required.
  644. This function supports Basic authentication only."""
  645. if not 'proxy-authenticate' in headers:
  646. URLopener.http_error_default(self, url, fp,
  647. errcode, errmsg, headers)
  648. stuff = headers['proxy-authenticate']
  649. import re
  650. match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
  651. if not match:
  652. URLopener.http_error_default(self, url, fp,
  653. errcode, errmsg, headers)
  654. scheme, realm = match.groups()
  655. if scheme.lower() != 'basic':
  656. URLopener.http_error_default(self, url, fp,
  657. errcode, errmsg, headers)
  658. name = 'retry_proxy_' + self.type + '_basic_auth'
  659. if data is None:
  660. return getattr(self,name)(url, realm)
  661. else:
  662. return getattr(self,name)(url, realm, data)
  663. def retry_proxy_http_basic_auth(self, url, realm, data=None):
  664. host, selector = splithost(url)
  665. newurl = 'http://' + host + selector
  666. proxy = self.proxies['http']
  667. urltype, proxyhost = splittype(proxy)
  668. proxyhost, proxyselector = splithost(proxyhost)
  669. i = proxyhost.find('@') + 1
  670. proxyhost = proxyhost[i:]
  671. user, passwd = self.get_user_passwd(proxyhost, realm, i)
  672. if not (user or passwd): return None
  673. proxyhost = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + proxyhost
  674. self.proxies['http'] = 'http://' + proxyhost + proxyselector
  675. if data is None:
  676. return self.open(newurl)
  677. else:
  678. return self.open(newurl, data)
  679. def retry_proxy_https_basic_auth(self, url, realm, data=None):
  680. host, selector = splithost(url)
  681. newurl = 'https://' + host + selector
  682. proxy = self.proxies['https']
  683. urltype, proxyhost = splittype(proxy)
  684. proxyhost, proxyselector = splithost(proxyhost)
  685. i = proxyhost.find('@') + 1
  686. proxyhost = proxyhost[i:]
  687. user, passwd = self.get_user_passwd(proxyhost, realm, i)
  688. if not (user or passwd): return None
  689. proxyhost = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + proxyhost
  690. self.proxies['https'] = 'https://' + proxyhost + proxyselector
  691. if data is None:
  692. return self.open(newurl)
  693. else:
  694. return self.open(newurl, data)
  695. def retry_http_basic_auth(self, url, realm, data=None):
  696. host, selector = splithost(url)
  697. i = host.find('@') + 1
  698. host = host[i:]
  699. user, passwd = self.get_user_passwd(host, realm, i)
  700. if not (user or passwd): return None
  701. host = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + host
  702. newurl = 'http://' + host + selector
  703. if data is None:
  704. return self.open(newurl)
  705. else:
  706. return self.open(newurl, data)
  707. def retry_https_basic_auth(self, url, realm, data=None):
  708. host, selector = splithost(url)
  709. i = host.find('@') + 1
  710. host = host[i:]
  711. user, passwd = self.get_user_passwd(host, realm, i)
  712. if not (user or passwd): return None
  713. host = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + host
  714. newurl = 'https://' + host + selector
  715. if data is None:
  716. return self.open(newurl)
  717. else:
  718. return self.open(newurl, data)
  719. def get_user_passwd(self, host, realm, clear_cache=0):
  720. key = realm + '@' + host.lower()
  721. if key in self.auth_cache:
  722. if clear_cache:
  723. del self.auth_cache[key]
  724. else:
  725. return self.auth_cache[key]
  726. user, passwd = self.prompt_user_passwd(host, realm)
  727. if user or passwd: self.auth_cache[key] = (user, passwd)
  728. return user, passwd
  729. def prompt_user_passwd(self, host, realm):
  730. """Override this in a GUI environment!"""
  731. import getpass
  732. try:
  733. user = raw_input("Enter username for %s at %s: " % (realm,
  734. host))
  735. passwd = getpass.getpass("Enter password for %s in %s at %s: " %
  736. (user, realm, host))
  737. return user, passwd
  738. except KeyboardInterrupt:
  739. print
  740. return None, None
  741. # Utility functions
  742. _localhost = None
  743. def localhost():
  744. """Return the IP address of the magic hostname 'localhost'."""
  745. global _localhost
  746. if _localhost is None:
  747. _localhost = socket.gethostbyname('localhost')
  748. return _localhost
  749. _thishost = None
  750. def thishost():
  751. """Return the IP address of the current host."""
  752. global _thishost
  753. if _thishost is None:
  754. _thishost = socket.gethostbyname(socket.gethostname())
  755. return _thishost
  756. _ftperrors = None
  757. def ftperrors():
  758. """Return the set of errors raised by the FTP class."""
  759. global _ftperrors
  760. if _ftperrors is None:
  761. import ftplib
  762. _ftperrors = ftplib.all_errors
  763. return _ftperrors
  764. _noheaders = None
  765. def noheaders():
  766. """Return an empty mimetools.Message object."""
  767. global _noheaders
  768. if _noheaders is None:
  769. import mimetools
  770. try:
  771. from cStringIO import StringIO
  772. except ImportError:
  773. from StringIO import StringIO
  774. _noheaders = mimetools.Message(StringIO(), 0)
  775. _noheaders.fp.close() # Recycle file descriptor
  776. return _noheaders
  777. # Utility classes
  778. class ftpwrapper:
  779. """Class used by open_ftp() for cache of open FTP connections."""
  780. def __init__(self, user, passwd, host, port, dirs,
  781. timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
  782. persistent=True):
  783. self.user = user
  784. self.passwd = passwd
  785. self.host = host
  786. self.port = port
  787. self.dirs = dirs
  788. self.timeout = timeout
  789. self.refcount = 0
  790. self.keepalive = persistent
  791. self.init()
  792. def init(self):
  793. import ftplib
  794. self.busy = 0
  795. self.ftp = ftplib.FTP()
  796. self.ftp.connect(self.host, self.port, self.timeout)
  797. self.ftp.login(self.user, self.passwd)
  798. for dir in self.dirs:
  799. self.ftp.cwd(dir)
  800. def retrfile(self, file, type):
  801. import ftplib
  802. self.endtransfer()
  803. if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
  804. else: cmd = 'TYPE ' + type; isdir = 0
  805. try:
  806. self.ftp.voidcmd(cmd)
  807. except ftplib.all_errors:
  808. self.init()
  809. self.ftp.voidcmd(cmd)
  810. conn = None
  811. if file and not isdir:
  812. # Try to retrieve as a file
  813. try:
  814. cmd = 'RETR ' + file
  815. conn, retrlen = self.ftp.ntransfercmd(cmd)
  816. except ftplib.error_perm, reason:
  817. if str(reason)[:3] != '550':
  818. raise IOError, ('ftp error', reason), sys.exc_info()[2]
  819. if not conn:
  820. # Set transfer mode to ASCII!
  821. self.ftp.voidcmd('TYPE A')
  822. # Try a directory listing. Verify that directory exists.
  823. if file:
  824. pwd = self.ftp.pwd()
  825. try:
  826. try:
  827. self.ftp.cwd(file)
  828. except ftplib.error_perm, reason:
  829. raise IOError, ('ftp error', reason), sys.exc_info()[2]
  830. finally:
  831. self.ftp.cwd(pwd)
  832. cmd = 'LIST ' + file
  833. else:
  834. cmd = 'LIST'
  835. conn, retrlen = self.ftp.ntransfercmd(cmd)
  836. self.busy = 1
  837. ftpobj = addclosehook(conn.makefile('rb'), self.file_close)
  838. self.refcount += 1
  839. conn.close()
  840. # Pass back both a suitably decorated object and a retrieval length
  841. return (ftpobj, retrlen)
  842. def endtransfer(self):
  843. if not self.busy:
  844. return
  845. self.busy = 0
  846. try:
  847. self.ftp.voidresp()
  848. except ftperrors():
  849. pass
  850. def close(self):
  851. self.keepalive = False
  852. if self.refcount <= 0:
  853. self.real_close()
  854. def file_close(self):
  855. self.endtransfer()
  856. self.refcount -= 1
  857. if self.refcount <= 0 and not self.keepalive:
  858. self.real_close()
  859. def real_close(self):
  860. self.endtransfer()
  861. try:
  862. self.ftp.close()
  863. except ftperrors():
  864. pass
  865. class addbase:
  866. """Base class for addinfo and addclosehook."""
  867. def __init__(self, fp):
  868. self.fp = fp
  869. self.read = self.fp.read
  870. self.readline = self.fp.readline
  871. if hasattr(self.fp, "readlines"): self.readlines = self.fp.readlines
  872. if hasattr(self.fp, "fileno"):
  873. self.fileno = self.fp.fileno
  874. else:
  875. self.fileno = lambda: None
  876. if hasattr(self.fp, "__iter__"):
  877. self.__iter__ = self.fp.__iter__
  878. if hasattr(self.fp, "next"):
  879. self.next = self.fp.next
  880. def __repr__(self):
  881. return '<%s at %r whose fp = %r>' % (self.__class__.__name__,
  882. id(self), self.fp)
  883. def close(self):
  884. self.read = None
  885. self.readline = None
  886. self.readlines = None
  887. self.fileno = None
  888. if self.fp: self.fp.close()
  889. self.fp = None
  890. class addclosehook(addbase):
  891. """Class to add a close hook to an open file."""
  892. def __init__(self, fp, closehook, *hookargs):
  893. addbase.__init__(self, fp)
  894. self.closehook = closehook
  895. self.hookargs = hookargs
  896. def close(self):
  897. addbase.close(self)
  898. if self.closehook:
  899. self.closehook(*self.hookargs)
  900. self.closehook = None
  901. self.hookargs = None
  902. class addinfo(addbase):
  903. """class to add an info() method to an open file."""
  904. def __init__(self, fp, headers):
  905. addbase.__init__(self, fp)
  906. self.headers = headers
  907. def info(self):
  908. return self.headers
  909. class addinfourl(addbase):
  910. """class to add info() and geturl() methods to an open file."""
  911. def __init__(self, fp, headers, url, code=None):
  912. addbase.__init__(self, fp)
  913. self.headers = headers
  914. self.url = url
  915. self.code = code
  916. def info(self):
  917. return self.headers
  918. def getcode(self):
  919. return self.code
  920. def geturl(self):
  921. return self.url
  922. # Utilities to parse URLs (most of these return None for missing parts):
  923. # unwrap('<URL:type://host/path>') --> 'type://host/path'
  924. # splittype('type:opaquestring') --> 'type', 'opaquestring'
  925. # splithost('//host[:port]/path') --> 'host[:port]', '/path'
  926. # splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'
  927. # splitpasswd('user:passwd') -> 'user', 'passwd'
  928. # splitport('host:port') --> 'host', 'port'
  929. # splitquery('/path?query') --> '/path', 'query'
  930. # splittag('/path#tag') --> '/path', 'tag'
  931. # splitattr('/path;attr1=value1;attr2=value2;...') ->
  932. # '/path', ['attr1=value1', 'attr2=value2', ...]
  933. # splitvalue('attr=value') --> 'attr', 'value'
  934. # unquote('abc%20def') -> 'abc def'
  935. # quote('abc def') -> 'abc%20def')
  936. try:
  937. unicode
  938. except NameError:
  939. def _is_unicode(x):
  940. return 0
  941. else:
  942. def _is_unicode(x):
  943. return isinstance(x, unicode)
  944. def toBytes(url):
  945. """toBytes(u"URL") --> 'URL'."""
  946. # Most URL schemes require ASCII. If that changes, the conversion
  947. # can be relaxed
  948. if _is_unicode(url):
  949. try:
  950. url = url.encode("ASCII")
  951. except UnicodeError:
  952. raise UnicodeError("URL " + repr(url) +
  953. " contains non-ASCII characters")
  954. return url
  955. def unwrap(url):
  956. """unwrap('<URL:type://host/path>') --> 'type://host/path'."""
  957. url = url.strip()
  958. if url[:1] == '<' and url[-1:] == '>':
  959. url = url[1:-1].strip()
  960. if url[:4] == 'URL:': url = url[4:].strip()
  961. return url
  962. _typeprog = None
  963. def splittype(url):
  964. """splittype('type:opaquestring') --> 'type', 'opaquestring'."""
  965. global _typeprog
  966. if _typeprog is None:
  967. import re
  968. _typeprog = re.compile('^([^/:]+):')
  969. match = _typeprog.match(url)
  970. if match:
  971. scheme = match.group(1)
  972. return scheme.lower(), url[len(scheme) + 1:]
  973. return None, url
  974. _hostprog = None
  975. def splithost(url):
  976. """splithost('//host[:port]/path') --> 'host[:port]', '/path'."""
  977. global _hostprog
  978. if _hostprog is None:
  979. import re
  980. _hostprog = re.compile('^//([^/?]*)(.*)$')
  981. match = _hostprog.match(url)
  982. if match:
  983. host_port = match.group(1)
  984. path = match.group(2)
  985. if path and not path.startswith('/'):
  986. path = '/' + path
  987. return host_port, path
  988. return None, url
  989. _userprog = None
  990. def splituser(host):
  991. """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'."""
  992. global _userprog
  993. if _userprog is None:
  994. import re
  995. _userprog = re.compile('^(.*)@(.*)$')
  996. match = _userprog.match(host)
  997. if match: return match.group(1, 2)
  998. return None, host
  999. _passwdprog = None
  1000. def splitpasswd(user):
  1001. """splitpasswd('user:passwd') -> 'user', 'passwd'."""
  1002. global _passwdprog
  1003. if _passwdprog is None:
  1004. import re
  1005. _passwdprog = re.compile('^([^:]*):(.*)$',re.S)
  1006. match = _passwdprog.match(user)
  1007. if match: return match.group(1, 2)
  1008. return user, None
  1009. # splittag('/path#tag') --> '/path', 'tag'
  1010. _portprog = None
  1011. def splitport(host):
  1012. """splitport('host:port') --> 'host', 'port'."""
  1013. global _portprog
  1014. if _portprog is None:
  1015. import re
  1016. _portprog = re.compile('^(.*):([0-9]+)$')
  1017. match = _portprog.match(host)
  1018. if match: return match.group(1, 2)
  1019. return host, None
  1020. _nportprog = None
  1021. def splitnport(host, defport=-1):
  1022. """Split host and port, returning numeric port.
  1023. Return given default port if no ':' found; defaults to -1.
  1024. Return numerical port if a valid number are found after ':'.
  1025. Return None if ':' but not a valid number."""
  1026. global _nportprog
  1027. if _nportprog is None:
  1028. import re
  1029. _nportprog = re.compile('^(.*):(.*)$')
  1030. match = _nportprog.match(host)
  1031. if match:
  1032. host, port = match.group(1, 2)
  1033. try:
  1034. if not port: raise ValueError, "no digits"
  1035. nport = int(port)
  1036. except ValueError:
  1037. nport = None
  1038. return host, nport
  1039. return host, defport
  1040. _queryprog = None
  1041. def splitquery(url):
  1042. """splitquery('/path?query') --> '/path', 'query'."""
  1043. global _queryprog
  1044. if _queryprog is None:
  1045. import re
  1046. _queryprog = re.compile('^(.*)\?([^?]*)$')
  1047. match = _queryprog.match(url)
  1048. if match: return match.group(1, 2)
  1049. return url, None
  1050. _tagprog = None
  1051. def splittag(url):
  1052. """splittag('/path#tag') --> '/path', 'tag'."""
  1053. global _tagprog
  1054. if _tagprog is None:
  1055. import re
  1056. _tagprog = re.compile('^(.*)#([^#]*)$')
  1057. match = _tagprog.match(url)
  1058. if match: return match.group(1, 2)
  1059. return url, None
  1060. def splitattr(url):
  1061. """splitattr('/path;attr1=value1;attr2=value2;...') ->
  1062. '/path', ['attr1=value1', 'attr2=value2', ...]."""
  1063. words = url.split(';')
  1064. return words[0], words[1:]
  1065. _valueprog = None
  1066. def splitvalue(attr):
  1067. """splitvalue('attr=value') --> 'attr', 'value'."""
  1068. global _valueprog
  1069. if _valueprog is None:
  1070. import re
  1071. _valueprog = re.compile('^([^=]*)=(.*)$')
  1072. match = _valueprog.match(attr)
  1073. if match: return match.group(1, 2)
  1074. return attr, None
  1075. # urlparse contains a duplicate of this method to avoid a circular import. If
  1076. # you update this method, also update the copy in urlparse. This code
  1077. # duplication does not exist in Python3.
  1078. _hexdig = '0123456789ABCDEFabcdef'
  1079. _hextochr = dict((a + b, chr(int(a + b, 16)))
  1080. for a in _hexdig for b in _hexdig)
  1081. def unquote(s):
  1082. """unquote('abc%20def') -> 'abc def'."""
  1083. res = s.split('%')
  1084. # fastpath
  1085. if len(res) == 1:
  1086. return s
  1087. res_list = [res[0]]
  1088. for j in xrange(1, len(res)):
  1089. item = res[j]
  1090. try:
  1091. x = _hextochr[item[:2]] + item[2:]
  1092. except KeyError:
  1093. x = '%' + item
  1094. except UnicodeDecodeError:
  1095. x = unichr(int(item[:2], 16)) + item[2:]
  1096. res_list.append(x)
  1097. return ''.join(res_list)
  1098. def unquote_plus(s):
  1099. """unquote('%7e/abc+def') -> '~/abc def'"""
  1100. s = s.replace('+', ' ')
  1101. return unquote(s)
  1102. always_safe = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  1103. 'abcdefghijklmnopqrstuvwxyz'
  1104. '0123456789' '_.-')
  1105. _safe_map = {}
  1106. for i, c in zip(xrange(256), str(bytearray(xrange(256)))):
  1107. _safe_map[c] = c if (i < 128 and c in always_safe) else '%{:02X}'.format(i)
  1108. _safe_quoters = {}
  1109. def quote(s, safe='/'):
  1110. """quote('abc def') -> 'abc%20def'
  1111. Each part of a URL, e.g. the path info, the query, etc., has a
  1112. different set of reserved characters that must be quoted.
  1113. RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists
  1114. the following reserved characters.
  1115. reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
  1116. "$" | ","
  1117. Each of these characters is reserved in some component of a URL,
  1118. but not necessarily in all of them.
  1119. By default, the quote function is intended for quoting the path
  1120. section of a URL. Thus, it will not encode '/'. This character
  1121. is reserved, but in typical usage the quote function is being
  1122. called on a path where the existing slash characters are used as
  1123. reserved characters.
  1124. """
  1125. # fastpath
  1126. if not s:
  1127. if s is None:
  1128. raise TypeError('None object cannot be quoted')
  1129. return s
  1130. cachekey = (safe, always_safe)
  1131. try:
  1132. (quoter, safe) = _safe_quoters[cachekey]
  1133. except KeyError:
  1134. safe_map = _safe_map.copy()
  1135. safe_map.update([(c, c) for c in safe])
  1136. quoter = safe_map.__getitem__
  1137. safe = always_safe + safe
  1138. _safe_quoters[cachekey] = (quoter, safe)
  1139. if not s.rstrip(safe):
  1140. return s
  1141. return ''.join(map(quoter, s))
  1142. def quote_plus(s, safe=''):
  1143. """Quote the query fragment of a URL; replacing ' ' with '+'"""
  1144. if ' ' in s:
  1145. s = quote(s, safe + ' ')
  1146. return s.replace(' ', '+')
  1147. return quote(s, safe)
  1148. def urlencode(query, doseq=0):
  1149. """Encode a sequence of two-element tuples or dictionary into a URL query string.
  1150. If any values in the query arg are sequences and doseq is true, each
  1151. sequence element is converted to a separate parameter.
  1152. If the query arg is a sequence of two-element tuples, the order of the
  1153. parameters in the output will match the order of parameters in the
  1154. input.
  1155. """
  1156. if hasattr(query,"items"):
  1157. # mapping objects
  1158. query = query.items()
  1159. else:
  1160. # it's a bother at times that strings and string-like objects are
  1161. # sequences...
  1162. try:
  1163. # non-sequence items should not work with len()
  1164. # non-empty strings will fail this
  1165. if len(query) and not isinstance(query[0], tuple):
  1166. raise TypeError
  1167. # zero-length sequences of all types will get here and succeed,
  1168. # but that's a minor nit - since the original implementation
  1169. # allowed empty dicts that type of behavior probably should be
  1170. # preserved for consistency
  1171. except TypeError:
  1172. ty,va,tb = sys.exc_info()
  1173. raise TypeError, "not a valid non-string sequence or mapping object", tb
  1174. l = []
  1175. if not doseq:
  1176. # preserve old behavior
  1177. for k, v in query:
  1178. k = quote_plus(str(k))
  1179. v = quote_plus(str(v))
  1180. l.append(k + '=' + v)
  1181. else:
  1182. for k, v in query:
  1183. k = quote_plus(str(k))
  1184. if isinstance(v, str):
  1185. v = quote_plus(v)
  1186. l.append(k + '=' + v)
  1187. elif _is_unicode(v):
  1188. # is there a reasonable way to convert to ASCII?
  1189. # encode generates a string, but "replace" or "ignore"
  1190. # lose information and "strict" can raise UnicodeError
  1191. v = quote_plus(v.encode("ASCII","replace"))
  1192. l.append(k + '=' + v)
  1193. else:
  1194. try:
  1195. # is this a sufficient test for sequence-ness?
  1196. len(v)
  1197. except TypeError:
  1198. # not a sequence
  1199. v = quote_plus(str(v))
  1200. l.append(k + '=' + v)
  1201. else:
  1202. # loop over the sequence
  1203. for elt in v:
  1204. l.append(k + '=' + quote_plus(str(elt)))
  1205. return '&'.join(l)
  1206. # Proxy handling
  1207. def getproxies_environment():
  1208. """Return a dictionary of scheme -> proxy server URL mappings.
  1209. Scan the environment for variables named <scheme>_proxy;
  1210. this seems to be the standard convention. If you need a
  1211. different way, you can pass a proxies dictionary to the
  1212. [Fancy]URLopener constructor.
  1213. """
  1214. proxies = {}
  1215. for name, value in os.environ.items():
  1216. name = name.lower()
  1217. if value and name[-6:] == '_proxy':
  1218. proxies[name[:-6]] = value
  1219. return proxies
  1220. def proxy_bypass_environment(host):
  1221. """Test if proxies should not be used for a particular host.
  1222. Checks the environment for a variable named no_proxy, which should
  1223. be a list of DNS suffixes separated by commas, or '*' for all hosts.
  1224. """
  1225. no_proxy = os.environ.get('no_proxy', '') or os.environ.get('NO_PROXY', '')
  1226. # '*' is special case for always bypass
  1227. if no_proxy == '*':
  1228. return 1
  1229. # strip port off host
  1230. hostonly, port = splitport(host)
  1231. # check if the host ends with any of the DNS suffixes
  1232. no_proxy_list = [proxy.strip() for proxy in no_proxy.split(',')]
  1233. for name in no_proxy_list:
  1234. if name and (hostonly.endswith(name) or host.endswith(name)):
  1235. return 1
  1236. # otherwise, don't bypass
  1237. return 0
  1238. if sys.platform == 'darwin':
  1239. from _scproxy import _get_proxy_settings, _get_proxies
  1240. def proxy_bypass_macosx_sysconf(host):
  1241. """
  1242. Retur

Large files files are truncated, but you can click here to view the full file