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

/lib-python/2.7/urllib.py

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

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