utils.py 17 KB

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