PageRenderTime 48ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/pip/_vendor/requests/utils.py

https://github.com/ptthiem/pip
Python | 643 lines | 548 code | 48 blank | 47 comment | 39 complexity | 50940834773678fbbd56408cb0d114c6 MD5 | raw file
  1. # -*- coding: utf-8 -*-
  2. """
  3. requests.utils
  4. ~~~~~~~~~~~~~~
  5. This module provides utility functions that are used within Requests
  6. that are also useful for external consumption.
  7. """
  8. import cgi
  9. import codecs
  10. import collections
  11. import io
  12. import os
  13. import platform
  14. import re
  15. import sys
  16. import socket
  17. import struct
  18. from . import __version__
  19. from . import certs
  20. from .compat import parse_http_list as _parse_list_header
  21. from .compat import (quote, urlparse, bytes, str, OrderedDict, unquote, is_py2,
  22. builtin_str, getproxies, proxy_bypass)
  23. from .cookies import RequestsCookieJar, cookiejar_from_dict
  24. from .structures import CaseInsensitiveDict
  25. from .exceptions import MissingSchema, InvalidURL
  26. _hush_pyflakes = (RequestsCookieJar,)
  27. NETRC_FILES = ('.netrc', '_netrc')
  28. DEFAULT_CA_BUNDLE_PATH = certs.where()
  29. def dict_to_sequence(d):
  30. """Returns an internal sequence dictionary update."""
  31. if hasattr(d, 'items'):
  32. d = d.items()
  33. return d
  34. def super_len(o):
  35. if hasattr(o, '__len__'):
  36. return len(o)
  37. if hasattr(o, 'len'):
  38. return o.len
  39. if hasattr(o, 'fileno'):
  40. try:
  41. fileno = o.fileno()
  42. except io.UnsupportedOperation:
  43. pass
  44. else:
  45. return os.fstat(fileno).st_size
  46. if hasattr(o, 'getvalue'):
  47. # e.g. BytesIO, cStringIO.StringI
  48. return len(o.getvalue())
  49. def get_netrc_auth(url):
  50. """Returns the Requests tuple auth for a given url from netrc."""
  51. try:
  52. from netrc import netrc, NetrcParseError
  53. locations = (os.path.expanduser('~/{0}'.format(f)) for f in NETRC_FILES)
  54. netrc_path = None
  55. for loc in locations:
  56. if os.path.exists(loc) and not netrc_path:
  57. netrc_path = loc
  58. # Abort early if there isn't one.
  59. if netrc_path is None:
  60. return netrc_path
  61. ri = urlparse(url)
  62. # Strip port numbers from netloc
  63. host = ri.netloc.split(':')[0]
  64. try:
  65. _netrc = netrc(netrc_path).authenticators(host)
  66. if _netrc:
  67. # Return with login / password
  68. login_i = (0 if _netrc[0] else 1)
  69. return (_netrc[login_i], _netrc[2])
  70. except (NetrcParseError, IOError):
  71. # If there was a parsing error or a permissions issue reading the file,
  72. # we'll just skip netrc auth
  73. pass
  74. # AppEngine hackiness.
  75. except (ImportError, AttributeError):
  76. pass
  77. def guess_filename(obj):
  78. """Tries to guess the filename of the given object."""
  79. name = getattr(obj, 'name', None)
  80. if name and name[0] != '<' and name[-1] != '>':
  81. return os.path.basename(name)
  82. def from_key_val_list(value):
  83. """Take an object and test to see if it can be represented as a
  84. dictionary. Unless it can not be represented as such, return an
  85. OrderedDict, e.g.,
  86. ::
  87. >>> from_key_val_list([('key', 'val')])
  88. OrderedDict([('key', 'val')])
  89. >>> from_key_val_list('string')
  90. ValueError: need more than 1 value to unpack
  91. >>> from_key_val_list({'key': 'val'})
  92. OrderedDict([('key', 'val')])
  93. """
  94. if value is None:
  95. return None
  96. if isinstance(value, (str, bytes, bool, int)):
  97. raise ValueError('cannot encode objects that are not 2-tuples')
  98. return OrderedDict(value)
  99. def to_key_val_list(value):
  100. """Take an object and test to see if it can be represented as a
  101. dictionary. If it can be, return a list of tuples, e.g.,
  102. ::
  103. >>> to_key_val_list([('key', 'val')])
  104. [('key', 'val')]
  105. >>> to_key_val_list({'key': 'val'})
  106. [('key', 'val')]
  107. >>> to_key_val_list('string')
  108. ValueError: cannot encode objects that are not 2-tuples.
  109. """
  110. if value is None:
  111. return None
  112. if isinstance(value, (str, bytes, bool, int)):
  113. raise ValueError('cannot encode objects that are not 2-tuples')
  114. if isinstance(value, collections.Mapping):
  115. value = value.items()
  116. return list(value)
  117. # From mitsuhiko/werkzeug (used with permission).
  118. def parse_list_header(value):
  119. """Parse lists as described by RFC 2068 Section 2.
  120. In particular, parse comma-separated lists where the elements of
  121. the list may include quoted-strings. A quoted-string could
  122. contain a comma. A non-quoted string could have quotes in the
  123. middle. Quotes are removed automatically after parsing.
  124. It basically works like :func:`parse_set_header` just that items
  125. may appear multiple times and case sensitivity is preserved.
  126. The return value is a standard :class:`list`:
  127. >>> parse_list_header('token, "quoted value"')
  128. ['token', 'quoted value']
  129. To create a header from the :class:`list` again, use the
  130. :func:`dump_header` function.
  131. :param value: a string with a list header.
  132. :return: :class:`list`
  133. """
  134. result = []
  135. for item in _parse_list_header(value):
  136. if item[:1] == item[-1:] == '"':
  137. item = unquote_header_value(item[1:-1])
  138. result.append(item)
  139. return result
  140. # From mitsuhiko/werkzeug (used with permission).
  141. def parse_dict_header(value):
  142. """Parse lists of key, value pairs as described by RFC 2068 Section 2 and
  143. convert them into a python dict:
  144. >>> d = parse_dict_header('foo="is a fish", bar="as well"')
  145. >>> type(d) is dict
  146. True
  147. >>> sorted(d.items())
  148. [('bar', 'as well'), ('foo', 'is a fish')]
  149. If there is no value for a key it will be `None`:
  150. >>> parse_dict_header('key_without_value')
  151. {'key_without_value': None}
  152. To create a header from the :class:`dict` again, use the
  153. :func:`dump_header` function.
  154. :param value: a string with a dict header.
  155. :return: :class:`dict`
  156. """
  157. result = {}
  158. for item in _parse_list_header(value):
  159. if '=' not in item:
  160. result[item] = None
  161. continue
  162. name, value = item.split('=', 1)
  163. if value[:1] == value[-1:] == '"':
  164. value = unquote_header_value(value[1:-1])
  165. result[name] = value
  166. return result
  167. # From mitsuhiko/werkzeug (used with permission).
  168. def unquote_header_value(value, is_filename=False):
  169. r"""Unquotes a header value. (Reversal of :func:`quote_header_value`).
  170. This does not use the real unquoting but what browsers are actually
  171. using for quoting.
  172. :param value: the header value to unquote.
  173. """
  174. if value and value[0] == value[-1] == '"':
  175. # this is not the real unquoting, but fixing this so that the
  176. # RFC is met will result in bugs with internet explorer and
  177. # probably some other browsers as well. IE for example is
  178. # uploading files with "C:\foo\bar.txt" as filename
  179. value = value[1:-1]
  180. # if this is a filename and the starting characters look like
  181. # a UNC path, then just return the value without quotes. Using the
  182. # replace sequence below on a UNC path has the effect of turning
  183. # the leading double slash into a single slash and then
  184. # _fix_ie_filename() doesn't work correctly. See #458.
  185. if not is_filename or value[:2] != '\\\\':
  186. return value.replace('\\\\', '\\').replace('\\"', '"')
  187. return value
  188. def dict_from_cookiejar(cj):
  189. """Returns a key/value dictionary from a CookieJar.
  190. :param cj: CookieJar object to extract cookies from.
  191. """
  192. cookie_dict = {}
  193. for cookie in cj:
  194. cookie_dict[cookie.name] = cookie.value
  195. return cookie_dict
  196. def add_dict_to_cookiejar(cj, cookie_dict):
  197. """Returns a CookieJar from a key/value dictionary.
  198. :param cj: CookieJar to insert cookies into.
  199. :param cookie_dict: Dict of key/values to insert into CookieJar.
  200. """
  201. cj2 = cookiejar_from_dict(cookie_dict)
  202. cj.update(cj2)
  203. return cj
  204. def get_encodings_from_content(content):
  205. """Returns encodings from given content string.
  206. :param content: bytestring to extract encodings from.
  207. """
  208. charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I)
  209. pragma_re = re.compile(r'<meta.*?content=["\']*;?charset=(.+?)["\'>]', flags=re.I)
  210. xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]')
  211. return (charset_re.findall(content) +
  212. pragma_re.findall(content) +
  213. xml_re.findall(content))
  214. def get_encoding_from_headers(headers):
  215. """Returns encodings from given HTTP Header Dict.
  216. :param headers: dictionary to extract encoding from.
  217. """
  218. content_type = headers.get('content-type')
  219. if not content_type:
  220. return None
  221. content_type, params = cgi.parse_header(content_type)
  222. if 'charset' in params:
  223. return params['charset'].strip("'\"")
  224. if 'text' in content_type:
  225. return 'ISO-8859-1'
  226. def stream_decode_response_unicode(iterator, r):
  227. """Stream decodes a iterator."""
  228. if r.encoding is None:
  229. for item in iterator:
  230. yield item
  231. return
  232. decoder = codecs.getincrementaldecoder(r.encoding)(errors='replace')
  233. for chunk in iterator:
  234. rv = decoder.decode(chunk)
  235. if rv:
  236. yield rv
  237. rv = decoder.decode(b'', final=True)
  238. if rv:
  239. yield rv
  240. def iter_slices(string, slice_length):
  241. """Iterate over slices of a string."""
  242. pos = 0
  243. while pos < len(string):
  244. yield string[pos:pos + slice_length]
  245. pos += slice_length
  246. def get_unicode_from_response(r):
  247. """Returns the requested content back in unicode.
  248. :param r: Response object to get unicode content from.
  249. Tried:
  250. 1. charset from content-type
  251. 2. every encodings from ``<meta ... charset=XXX>``
  252. 3. fall back and replace all unicode characters
  253. """
  254. tried_encodings = []
  255. # Try charset from content-type
  256. encoding = get_encoding_from_headers(r.headers)
  257. if encoding:
  258. try:
  259. return str(r.content, encoding)
  260. except UnicodeError:
  261. tried_encodings.append(encoding)
  262. # Fall back:
  263. try:
  264. return str(r.content, encoding, errors='replace')
  265. except TypeError:
  266. return r.content
  267. # The unreserved URI characters (RFC 3986)
  268. UNRESERVED_SET = frozenset(
  269. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  270. + "0123456789-._~")
  271. def unquote_unreserved(uri):
  272. """Un-escape any percent-escape sequences in a URI that are unreserved
  273. characters. This leaves all reserved, illegal and non-ASCII bytes encoded.
  274. """
  275. parts = uri.split('%')
  276. for i in range(1, len(parts)):
  277. h = parts[i][0:2]
  278. if len(h) == 2 and h.isalnum():
  279. try:
  280. c = chr(int(h, 16))
  281. except ValueError:
  282. raise InvalidURL("Invalid percent-escape sequence: '%s'" % h)
  283. if c in UNRESERVED_SET:
  284. parts[i] = c + parts[i][2:]
  285. else:
  286. parts[i] = '%' + parts[i]
  287. else:
  288. parts[i] = '%' + parts[i]
  289. return ''.join(parts)
  290. def requote_uri(uri):
  291. """Re-quote the given URI.
  292. This function passes the given URI through an unquote/quote cycle to
  293. ensure that it is fully and consistently quoted.
  294. """
  295. # Unquote only the unreserved characters
  296. # Then quote only illegal characters (do not quote reserved, unreserved,
  297. # or '%')
  298. return quote(unquote_unreserved(uri), safe="!#$%&'()*+,/:;=?@[]~")
  299. def address_in_network(ip, net):
  300. """
  301. This function allows you to check if on IP belongs to a network subnet
  302. Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24
  303. returns False if ip = 192.168.1.1 and net = 192.168.100.0/24
  304. """
  305. ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0]
  306. netaddr, bits = net.split('/')
  307. netmask = struct.unpack('=L', socket.inet_aton(dotted_netmask(int(bits))))[0]
  308. network = struct.unpack('=L', socket.inet_aton(netaddr))[0] & netmask
  309. return (ipaddr & netmask) == (network & netmask)
  310. def dotted_netmask(mask):
  311. """
  312. Converts mask from /xx format to xxx.xxx.xxx.xxx
  313. Example: if mask is 24 function returns 255.255.255.0
  314. """
  315. bits = 0xffffffff ^ (1 << 32 - mask) - 1
  316. return socket.inet_ntoa(struct.pack('>I', bits))
  317. def is_ipv4_address(string_ip):
  318. try:
  319. socket.inet_aton(string_ip)
  320. except socket.error:
  321. return False
  322. return True
  323. def is_valid_cidr(string_network):
  324. """Very simple check of the cidr format in no_proxy variable"""
  325. if string_network.count('/') == 1:
  326. try:
  327. mask = int(string_network.split('/')[1])
  328. except ValueError:
  329. return False
  330. if mask < 1 or mask > 32:
  331. return False
  332. try:
  333. socket.inet_aton(string_network.split('/')[0])
  334. except socket.error:
  335. return False
  336. else:
  337. return False
  338. return True
  339. def get_environ_proxies(url):
  340. """Return a dict of environment proxies."""
  341. get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper())
  342. # First check whether no_proxy is defined. If it is, check that the URL
  343. # we're getting isn't in the no_proxy list.
  344. no_proxy = get_proxy('no_proxy')
  345. netloc = urlparse(url).netloc
  346. if no_proxy:
  347. # We need to check whether we match here. We need to see if we match
  348. # the end of the netloc, both with and without the port.
  349. no_proxy = no_proxy.replace(' ', '').split(',')
  350. ip = netloc.split(':')[0]
  351. if is_ipv4_address(ip):
  352. for proxy_ip in no_proxy:
  353. if is_valid_cidr(proxy_ip):
  354. if address_in_network(ip, proxy_ip):
  355. return {}
  356. else:
  357. for host in no_proxy:
  358. if netloc.endswith(host) or netloc.split(':')[0].endswith(host):
  359. # The URL does match something in no_proxy, so we don't want
  360. # to apply the proxies on this URL.
  361. return {}
  362. # If the system proxy settings indicate that this URL should be bypassed,
  363. # don't proxy.
  364. if proxy_bypass(netloc):
  365. return {}
  366. # If we get here, we either didn't have no_proxy set or we're not going
  367. # anywhere that no_proxy applies to, and the system settings don't require
  368. # bypassing the proxy for the current URL.
  369. return getproxies()
  370. def default_user_agent(name="python-requests"):
  371. """Return a string representing the default user agent."""
  372. _implementation = platform.python_implementation()
  373. if _implementation == 'CPython':
  374. _implementation_version = platform.python_version()
  375. elif _implementation == 'PyPy':
  376. _implementation_version = '%s.%s.%s' % (sys.pypy_version_info.major,
  377. sys.pypy_version_info.minor,
  378. sys.pypy_version_info.micro)
  379. if sys.pypy_version_info.releaselevel != 'final':
  380. _implementation_version = ''.join([_implementation_version, sys.pypy_version_info.releaselevel])
  381. elif _implementation == 'Jython':
  382. _implementation_version = platform.python_version() # Complete Guess
  383. elif _implementation == 'IronPython':
  384. _implementation_version = platform.python_version() # Complete Guess
  385. else:
  386. _implementation_version = 'Unknown'
  387. try:
  388. p_system = platform.system()
  389. p_release = platform.release()
  390. except IOError:
  391. p_system = 'Unknown'
  392. p_release = 'Unknown'
  393. return " ".join(['%s/%s' % (name, __version__),
  394. '%s/%s' % (_implementation, _implementation_version),
  395. '%s/%s' % (p_system, p_release)])
  396. def default_headers():
  397. return CaseInsensitiveDict({
  398. 'User-Agent': default_user_agent(),
  399. 'Accept-Encoding': ', '.join(('gzip', 'deflate', 'compress')),
  400. 'Accept': '*/*'
  401. })
  402. def parse_header_links(value):
  403. """Return a dict of parsed link headers proxies.
  404. i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg"
  405. """
  406. links = []
  407. replace_chars = " '\""
  408. for val in value.split(","):
  409. try:
  410. url, params = val.split(";", 1)
  411. except ValueError:
  412. url, params = val, ''
  413. link = {}
  414. link["url"] = url.strip("<> '\"")
  415. for param in params.split(";"):
  416. try:
  417. key, value = param.split("=")
  418. except ValueError:
  419. break
  420. link[key.strip(replace_chars)] = value.strip(replace_chars)
  421. links.append(link)
  422. return links
  423. # Null bytes; no need to recreate these on each call to guess_json_utf
  424. _null = '\x00'.encode('ascii') # encoding to ASCII for Python 3
  425. _null2 = _null * 2
  426. _null3 = _null * 3
  427. def guess_json_utf(data):
  428. # JSON always starts with two ASCII characters, so detection is as
  429. # easy as counting the nulls and from their location and count
  430. # determine the encoding. Also detect a BOM, if present.
  431. sample = data[:4]
  432. if sample in (codecs.BOM_UTF32_LE, codecs.BOM32_BE):
  433. return 'utf-32' # BOM included
  434. if sample[:3] == codecs.BOM_UTF8:
  435. return 'utf-8-sig' # BOM included, MS style (discouraged)
  436. if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):
  437. return 'utf-16' # BOM included
  438. nullcount = sample.count(_null)
  439. if nullcount == 0:
  440. return 'utf-8'
  441. if nullcount == 2:
  442. if sample[::2] == _null2: # 1st and 3rd are null
  443. return 'utf-16-be'
  444. if sample[1::2] == _null2: # 2nd and 4th are null
  445. return 'utf-16-le'
  446. # Did not detect 2 valid UTF-16 ascii-range characters
  447. if nullcount == 3:
  448. if sample[:3] == _null3:
  449. return 'utf-32-be'
  450. if sample[1:] == _null3:
  451. return 'utf-32-le'
  452. # Did not detect a valid UTF-32 ascii-range character
  453. return None
  454. def except_on_missing_scheme(url):
  455. """Given a URL, raise a MissingSchema exception if the scheme is missing.
  456. """
  457. scheme, netloc, path, params, query, fragment = urlparse(url)
  458. if not scheme:
  459. raise MissingSchema('Proxy URLs must have explicit schemes.')
  460. def get_auth_from_url(url):
  461. """Given a url with authentication components, extract them into a tuple of
  462. username,password."""
  463. if url:
  464. url = unquote(url)
  465. parsed = urlparse(url)
  466. return (parsed.username, parsed.password)
  467. else:
  468. return ('', '')
  469. def to_native_string(string, encoding='ascii'):
  470. """
  471. Given a string object, regardless of type, returns a representation of that
  472. string in the native string type, encoding and decoding where necessary.
  473. This assumes ASCII unless told otherwise.
  474. """
  475. out = None
  476. if isinstance(string, builtin_str):
  477. out = string
  478. else:
  479. if is_py2:
  480. out = string.encode(encoding)
  481. else:
  482. out = string.decode(encoding)
  483. return out