utils.py 20 KB

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