utils.py 22 KB

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