PageRenderTime 64ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/urllib.py

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

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