utils.py 22 KB

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