utils.py 21 KB

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