You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

977 lines
29 KiB

4 years ago
  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 codecs
  9. import contextlib
  10. import io
  11. import os
  12. import re
  13. import socket
  14. import struct
  15. import sys
  16. import tempfile
  17. import warnings
  18. import zipfile
  19. from .__version__ import __version__
  20. from . import certs
  21. # to_native_string is unused here, but imported here for backwards compatibility
  22. from ._internal_utils import to_native_string
  23. from .compat import parse_http_list as _parse_list_header
  24. from .compat import (
  25. quote, urlparse, bytes, str, OrderedDict, unquote, getproxies,
  26. proxy_bypass, urlunparse, basestring, integer_types, is_py3,
  27. proxy_bypass_environment, getproxies_environment, Mapping)
  28. from .cookies import cookiejar_from_dict
  29. from .structures import CaseInsensitiveDict
  30. from .exceptions import (
  31. InvalidURL, InvalidHeader, FileModeWarning, UnrewindableBodyError)
  32. NETRC_FILES = ('.netrc', '_netrc')
  33. DEFAULT_CA_BUNDLE_PATH = certs.where()
  34. DEFAULT_PORTS = {'http': 80, 'https': 443}
  35. if sys.platform == 'win32':
  36. # provide a proxy_bypass version on Windows without DNS lookups
  37. def proxy_bypass_registry(host):
  38. try:
  39. if is_py3:
  40. import winreg
  41. else:
  42. import _winreg as winreg
  43. except ImportError:
  44. return False
  45. try:
  46. internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
  47. r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
  48. # ProxyEnable could be REG_SZ or REG_DWORD, normalizing it
  49. proxyEnable = int(winreg.QueryValueEx(internetSettings,
  50. 'ProxyEnable')[0])
  51. # ProxyOverride is almost always a string
  52. proxyOverride = winreg.QueryValueEx(internetSettings,
  53. 'ProxyOverride')[0]
  54. except OSError:
  55. return False
  56. if not proxyEnable or not proxyOverride:
  57. return False
  58. # make a check value list from the registry entry: replace the
  59. # '<local>' string by the localhost entry and the corresponding
  60. # canonical entry.
  61. proxyOverride = proxyOverride.split(';')
  62. # now check if we match one of the registry values.
  63. for test in proxyOverride:
  64. if test == '<local>':
  65. if '.' not in host:
  66. return True
  67. test = test.replace(".", r"\.") # mask dots
  68. test = test.replace("*", r".*") # change glob sequence
  69. test = test.replace("?", r".") # change glob char
  70. if re.match(test, host, re.I):
  71. return True
  72. return False
  73. def proxy_bypass(host): # noqa
  74. """Return True, if the host should be bypassed.
  75. Checks proxy settings gathered from the environment, if specified,
  76. or the registry.
  77. """
  78. if getproxies_environment():
  79. return proxy_bypass_environment(host)
  80. else:
  81. return proxy_bypass_registry(host)
  82. def dict_to_sequence(d):
  83. """Returns an internal sequence dictionary update."""
  84. if hasattr(d, 'items'):
  85. d = d.items()
  86. return d
  87. def super_len(o):
  88. total_length = None
  89. current_position = 0
  90. if hasattr(o, '__len__'):
  91. total_length = len(o)
  92. elif hasattr(o, 'len'):
  93. total_length = o.len
  94. elif hasattr(o, 'fileno'):
  95. try:
  96. fileno = o.fileno()
  97. except io.UnsupportedOperation:
  98. pass
  99. else:
  100. total_length = os.fstat(fileno).st_size
  101. # Having used fstat to determine the file length, we need to
  102. # confirm that this file was opened up in binary mode.
  103. if 'b' not in o.mode:
  104. warnings.warn((
  105. "Requests has determined the content-length for this "
  106. "request using the binary size of the file: however, the "
  107. "file has been opened in text mode (i.e. without the 'b' "
  108. "flag in the mode). This may lead to an incorrect "
  109. "content-length. In Requests 3.0, support will be removed "
  110. "for files in text mode."),
  111. FileModeWarning
  112. )
  113. if hasattr(o, 'tell'):
  114. try:
  115. current_position = o.tell()
  116. except (OSError, IOError):
  117. # This can happen in some weird situations, such as when the file
  118. # is actually a special file descriptor like stdin. In this
  119. # instance, we don't know what the length is, so set it to zero and
  120. # let requests chunk it instead.
  121. if total_length is not None:
  122. current_position = total_length
  123. else:
  124. if hasattr(o, 'seek') and total_length is None:
  125. # StringIO and BytesIO have seek but no useable fileno
  126. try:
  127. # seek to end of file
  128. o.seek(0, 2)
  129. total_length = o.tell()
  130. # seek back to current position to support
  131. # partially read file-like objects
  132. o.seek(current_position or 0)
  133. except (OSError, IOError):
  134. total_length = 0
  135. if total_length is None:
  136. total_length = 0
  137. return max(0, total_length - current_position)
  138. def get_netrc_auth(url, raise_errors=False):
  139. """Returns the Requests tuple auth for a given url from netrc."""
  140. try:
  141. from netrc import netrc, NetrcParseError
  142. netrc_path = None
  143. for f in NETRC_FILES:
  144. try:
  145. loc = os.path.expanduser('~/{}'.format(f))
  146. except KeyError:
  147. # os.path.expanduser can fail when $HOME is undefined and
  148. # getpwuid fails. See https://bugs.python.org/issue20164 &
  149. # https://github.com/requests/requests/issues/1846
  150. return
  151. if os.path.exists(loc):
  152. netrc_path = loc
  153. break
  154. # Abort early if there isn't one.
  155. if netrc_path is None:
  156. return
  157. ri = urlparse(url)
  158. # Strip port numbers from netloc. This weird `if...encode`` dance is
  159. # used for Python 3.2, which doesn't support unicode literals.
  160. splitstr = b':'
  161. if isinstance(url, str):
  162. splitstr = splitstr.decode('ascii')
  163. host = ri.netloc.split(splitstr)[0]
  164. try:
  165. _netrc = netrc(netrc_path).authenticators(host)
  166. if _netrc:
  167. # Return with login / password
  168. login_i = (0 if _netrc[0] else 1)
  169. return (_netrc[login_i], _netrc[2])
  170. except (NetrcParseError, IOError):
  171. # If there was a parsing error or a permissions issue reading the file,
  172. # we'll just skip netrc auth unless explicitly asked to raise errors.
  173. if raise_errors:
  174. raise
  175. # AppEngine hackiness.
  176. except (ImportError, AttributeError):
  177. pass
  178. def guess_filename(obj):
  179. """Tries to guess the filename of the given object."""
  180. name = getattr(obj, 'name', None)
  181. if (name and isinstance(name, basestring) and name[0] != '<' and
  182. name[-1] != '>'):
  183. return os.path.basename(name)
  184. def extract_zipped_paths(path):
  185. """Replace nonexistent paths that look like they refer to a member of a zip
  186. archive with the location of an extracted copy of the target, or else
  187. just return the provided path unchanged.
  188. """
  189. if os.path.exists(path):
  190. # this is already a valid path, no need to do anything further
  191. return path
  192. # find the first valid part of the provided path and treat that as a zip archive
  193. # assume the rest of the path is the name of a member in the archive
  194. archive, member = os.path.split(path)
  195. while archive and not os.path.exists(archive):
  196. archive, prefix = os.path.split(archive)
  197. member = '/'.join([prefix, member])
  198. if not zipfile.is_zipfile(archive):
  199. return path
  200. zip_file = zipfile.ZipFile(archive)
  201. if member not in zip_file.namelist():
  202. return path
  203. # we have a valid zip archive and a valid member of that archive
  204. tmp = tempfile.gettempdir()
  205. extracted_path = os.path.join(tmp, *member.split('/'))
  206. if not os.path.exists(extracted_path):
  207. extracted_path = zip_file.extract(member, path=tmp)
  208. return extracted_path
  209. def from_key_val_list(value):
  210. """Take an object and test to see if it can be represented as a
  211. dictionary. Unless it can not be represented as such, return an
  212. OrderedDict, e.g.,
  213. ::
  214. >>> from_key_val_list([('key', 'val')])
  215. OrderedDict([('key', 'val')])
  216. >>> from_key_val_list('string')
  217. ValueError: cannot encode objects that are not 2-tuples
  218. >>> from_key_val_list({'key': 'val'})
  219. OrderedDict([('key', 'val')])
  220. :rtype: OrderedDict
  221. """
  222. if value is None:
  223. return None
  224. if isinstance(value, (str, bytes, bool, int)):
  225. raise ValueError('cannot encode objects that are not 2-tuples')
  226. return OrderedDict(value)
  227. def to_key_val_list(value):
  228. """Take an object and test to see if it can be represented as a
  229. dictionary. If it can be, return a list of tuples, e.g.,
  230. ::
  231. >>> to_key_val_list([('key', 'val')])
  232. [('key', 'val')]
  233. >>> to_key_val_list({'key': 'val'})
  234. [('key', 'val')]
  235. >>> to_key_val_list('string')
  236. ValueError: cannot encode objects that are not 2-tuples.
  237. :rtype: list
  238. """
  239. if value is None:
  240. return None
  241. if isinstance(value, (str, bytes, bool, int)):
  242. raise ValueError('cannot encode objects that are not 2-tuples')
  243. if isinstance(value, Mapping):
  244. value = value.items()
  245. return list(value)
  246. # From mitsuhiko/werkzeug (used with permission).
  247. def parse_list_header(value):
  248. """Parse lists as described by RFC 2068 Section 2.
  249. In particular, parse comma-separated lists where the elements of
  250. the list may include quoted-strings. A quoted-string could
  251. contain a comma. A non-quoted string could have quotes in the
  252. middle. Quotes are removed automatically after parsing.
  253. It basically works like :func:`parse_set_header` just that items
  254. may appear multiple times and case sensitivity is preserved.
  255. The return value is a standard :class:`list`:
  256. >>> parse_list_header('token, "quoted value"')
  257. ['token', 'quoted value']
  258. To create a header from the :class:`list` again, use the
  259. :func:`dump_header` function.
  260. :param value: a string with a list header.
  261. :return: :class:`list`
  262. :rtype: list
  263. """
  264. result = []
  265. for item in _parse_list_header(value):
  266. if item[:1] == item[-1:] == '"':
  267. item = unquote_header_value(item[1:-1])
  268. result.append(item)
  269. return result
  270. # From mitsuhiko/werkzeug (used with permission).
  271. def parse_dict_header(value):
  272. """Parse lists of key, value pairs as described by RFC 2068 Section 2 and
  273. convert them into a python dict:
  274. >>> d = parse_dict_header('foo="is a fish", bar="as well"')
  275. >>> type(d) is dict
  276. True
  277. >>> sorted(d.items())
  278. [('bar', 'as well'), ('foo', 'is a fish')]
  279. If there is no value for a key it will be `None`:
  280. >>> parse_dict_header('key_without_value')
  281. {'key_without_value': None}
  282. To create a header from the :class:`dict` again, use the
  283. :func:`dump_header` function.
  284. :param value: a string with a dict header.
  285. :return: :class:`dict`
  286. :rtype: dict
  287. """
  288. result = {}
  289. for item in _parse_list_header(value):
  290. if '=' not in item:
  291. result[item] = None
  292. continue
  293. name, value = item.split('=', 1)
  294. if value[:1] == value[-1:] == '"':
  295. value = unquote_header_value(value[1:-1])
  296. result[name] = value
  297. return result
  298. # From mitsuhiko/werkzeug (used with permission).
  299. def unquote_header_value(value, is_filename=False):
  300. r"""Unquotes a header value. (Reversal of :func:`quote_header_value`).
  301. This does not use the real unquoting but what browsers are actually
  302. using for quoting.
  303. :param value: the header value to unquote.
  304. :rtype: str
  305. """
  306. if value and value[0] == value[-1] == '"':
  307. # this is not the real unquoting, but fixing this so that the
  308. # RFC is met will result in bugs with internet explorer and
  309. # probably some other browsers as well. IE for example is
  310. # uploading files with "C:\foo\bar.txt" as filename
  311. value = value[1:-1]
  312. # if this is a filename and the starting characters look like
  313. # a UNC path, then just return the value without quotes. Using the
  314. # replace sequence below on a UNC path has the effect of turning
  315. # the leading double slash into a single slash and then
  316. # _fix_ie_filename() doesn't work correctly. See #458.
  317. if not is_filename or value[:2] != '\\\\':
  318. return value.replace('\\\\', '\\').replace('\\"', '"')
  319. return value
  320. def dict_from_cookiejar(cj):
  321. """Returns a key/value dictionary from a CookieJar.
  322. :param cj: CookieJar object to extract cookies from.
  323. :rtype: dict
  324. """
  325. cookie_dict = {}
  326. for cookie in cj:
  327. cookie_dict[cookie.name] = cookie.value
  328. return cookie_dict
  329. def add_dict_to_cookiejar(cj, cookie_dict):
  330. """Returns a CookieJar from a key/value dictionary.
  331. :param cj: CookieJar to insert cookies into.
  332. :param cookie_dict: Dict of key/values to insert into CookieJar.
  333. :rtype: CookieJar
  334. """
  335. return cookiejar_from_dict(cookie_dict, cj)
  336. def get_encodings_from_content(content):
  337. """Returns encodings from given content string.
  338. :param content: bytestring to extract encodings from.
  339. """
  340. warnings.warn((
  341. 'In requests 3.0, get_encodings_from_content will be removed. For '
  342. 'more information, please see the discussion on issue #2266. (This'
  343. ' warning should only appear once.)'),
  344. DeprecationWarning)
  345. charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I)
  346. pragma_re = re.compile(r'<meta.*?content=["\']*;?charset=(.+?)["\'>]', flags=re.I)
  347. xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]')
  348. return (charset_re.findall(content) +
  349. pragma_re.findall(content) +
  350. xml_re.findall(content))
  351. def _parse_content_type_header(header):
  352. """Returns content type and parameters from given header
  353. :param header: string
  354. :return: tuple containing content type and dictionary of
  355. parameters
  356. """
  357. tokens = header.split(';')
  358. content_type, params = tokens[0].strip(), tokens[1:]
  359. params_dict = {}
  360. items_to_strip = "\"' "
  361. for param in params:
  362. param = param.strip()
  363. if param:
  364. key, value = param, True
  365. index_of_equals = param.find("=")
  366. if index_of_equals != -1:
  367. key = param[:index_of_equals].strip(items_to_strip)
  368. value = param[index_of_equals + 1:].strip(items_to_strip)
  369. params_dict[key.lower()] = value
  370. return content_type, params_dict
  371. def get_encoding_from_headers(headers):
  372. """Returns encodings from given HTTP Header Dict.
  373. :param headers: dictionary to extract encoding from.
  374. :rtype: str
  375. """
  376. content_type = headers.get('content-type')
  377. if not content_type:
  378. return None
  379. content_type, params = _parse_content_type_header(content_type)
  380. if 'charset' in params:
  381. return params['charset'].strip("'\"")
  382. if 'text' in content_type:
  383. return 'ISO-8859-1'
  384. def stream_decode_response_unicode(iterator, r):
  385. """Stream decodes a iterator."""
  386. if r.encoding is None:
  387. for item in iterator:
  388. yield item
  389. return
  390. decoder = codecs.getincrementaldecoder(r.encoding)(errors='replace')
  391. for chunk in iterator:
  392. rv = decoder.decode(chunk)
  393. if rv:
  394. yield rv
  395. rv = decoder.decode(b'', final=True)
  396. if rv:
  397. yield rv
  398. def iter_slices(string, slice_length):
  399. """Iterate over slices of a string."""
  400. pos = 0
  401. if slice_length is None or slice_length <= 0:
  402. slice_length = len(string)
  403. while pos < len(string):
  404. yield string[pos:pos + slice_length]
  405. pos += slice_length
  406. def get_unicode_from_response(r):
  407. """Returns the requested content back in unicode.
  408. :param r: Response object to get unicode content from.
  409. Tried:
  410. 1. charset from content-type
  411. 2. fall back and replace all unicode characters
  412. :rtype: str
  413. """
  414. warnings.warn((
  415. 'In requests 3.0, get_unicode_from_response will be removed. For '
  416. 'more information, please see the discussion on issue #2266. (This'
  417. ' warning should only appear once.)'),
  418. DeprecationWarning)
  419. tried_encodings = []
  420. # Try charset from content-type
  421. encoding = get_encoding_from_headers(r.headers)
  422. if encoding:
  423. try:
  424. return str(r.content, encoding)
  425. except UnicodeError:
  426. tried_encodings.append(encoding)
  427. # Fall back:
  428. try:
  429. return str(r.content, encoding, errors='replace')
  430. except TypeError:
  431. return r.content
  432. # The unreserved URI characters (RFC 3986)
  433. UNRESERVED_SET = frozenset(
  434. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789-._~")
  435. def unquote_unreserved(uri):
  436. """Un-escape any percent-escape sequences in a URI that are unreserved
  437. characters. This leaves all reserved, illegal and non-ASCII bytes encoded.
  438. :rtype: str
  439. """
  440. parts = uri.split('%')
  441. for i in range(1, len(parts)):
  442. h = parts[i][0:2]
  443. if len(h) == 2 and h.isalnum():
  444. try:
  445. c = chr(int(h, 16))
  446. except ValueError:
  447. raise InvalidURL("Invalid percent-escape sequence: '%s'" % h)
  448. if c in UNRESERVED_SET:
  449. parts[i] = c + parts[i][2:]
  450. else:
  451. parts[i] = '%' + parts[i]
  452. else:
  453. parts[i] = '%' + parts[i]
  454. return ''.join(parts)
  455. def requote_uri(uri):
  456. """Re-quote the given URI.
  457. This function passes the given URI through an unquote/quote cycle to
  458. ensure that it is fully and consistently quoted.
  459. :rtype: str
  460. """
  461. safe_with_percent = "!#$%&'()*+,/:;=?@[]~"
  462. safe_without_percent = "!#$&'()*+,/:;=?@[]~"
  463. try:
  464. # Unquote only the unreserved characters
  465. # Then quote only illegal characters (do not quote reserved,
  466. # unreserved, or '%')
  467. return quote(unquote_unreserved(uri), safe=safe_with_percent)
  468. except InvalidURL:
  469. # We couldn't unquote the given URI, so let's try quoting it, but
  470. # there may be unquoted '%'s in the URI. We need to make sure they're
  471. # properly quoted so they do not cause issues elsewhere.
  472. return quote(uri, safe=safe_without_percent)
  473. def address_in_network(ip, net):
  474. """This function allows you to check if an IP belongs to a network subnet
  475. Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24
  476. returns False if ip = 192.168.1.1 and net = 192.168.100.0/24
  477. :rtype: bool
  478. """
  479. ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0]
  480. netaddr, bits = net.split('/')
  481. netmask = struct.unpack('=L', socket.inet_aton(dotted_netmask(int(bits))))[0]
  482. network = struct.unpack('=L', socket.inet_aton(netaddr))[0] & netmask
  483. return (ipaddr & netmask) == (network & netmask)
  484. def dotted_netmask(mask):
  485. """Converts mask from /xx format to xxx.xxx.xxx.xxx
  486. Example: if mask is 24 function returns 255.255.255.0
  487. :rtype: str
  488. """
  489. bits = 0xffffffff ^ (1 << 32 - mask) - 1
  490. return socket.inet_ntoa(struct.pack('>I', bits))
  491. def is_ipv4_address(string_ip):
  492. """
  493. :rtype: bool
  494. """
  495. try:
  496. socket.inet_aton(string_ip)
  497. except socket.error:
  498. return False
  499. return True
  500. def is_valid_cidr(string_network):
  501. """
  502. Very simple check of the cidr format in no_proxy variable.
  503. :rtype: bool
  504. """
  505. if string_network.count('/') == 1:
  506. try:
  507. mask = int(string_network.split('/')[1])
  508. except ValueError:
  509. return False
  510. if mask < 1 or mask > 32:
  511. return False
  512. try:
  513. socket.inet_aton(string_network.split('/')[0])
  514. except socket.error:
  515. return False
  516. else:
  517. return False
  518. return True
  519. @contextlib.contextmanager
  520. def set_environ(env_name, value):
  521. """Set the environment variable 'env_name' to 'value'
  522. Save previous value, yield, and then restore the previous value stored in
  523. the environment variable 'env_name'.
  524. If 'value' is None, do nothing"""
  525. value_changed = value is not None
  526. if value_changed:
  527. old_value = os.environ.get(env_name)
  528. os.environ[env_name] = value
  529. try:
  530. yield
  531. finally:
  532. if value_changed:
  533. if old_value is None:
  534. del os.environ[env_name]
  535. else:
  536. os.environ[env_name] = old_value
  537. def should_bypass_proxies(url, no_proxy):
  538. """
  539. Returns whether we should bypass proxies or not.
  540. :rtype: bool
  541. """
  542. # Prioritize lowercase environment variables over uppercase
  543. # to keep a consistent behaviour with other http projects (curl, wget).
  544. get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper())
  545. # First check whether no_proxy is defined. If it is, check that the URL
  546. # we're getting isn't in the no_proxy list.
  547. no_proxy_arg = no_proxy
  548. if no_proxy is None:
  549. no_proxy = get_proxy('no_proxy')
  550. parsed = urlparse(url)
  551. if parsed.hostname is None:
  552. # URLs don't always have hostnames, e.g. file:/// urls.
  553. return True
  554. if no_proxy:
  555. # We need to check whether we match here. We need to see if we match
  556. # the end of the hostname, both with and without the port.
  557. no_proxy = (
  558. host for host in no_proxy.replace(' ', '').split(',') if host
  559. )
  560. if is_ipv4_address(parsed.hostname):
  561. for proxy_ip in no_proxy:
  562. if is_valid_cidr(proxy_ip):
  563. if address_in_network(parsed.hostname, proxy_ip):
  564. return True
  565. elif parsed.hostname == proxy_ip:
  566. # If no_proxy ip was defined in plain IP notation instead of cidr notation &
  567. # matches the IP of the index
  568. return True
  569. else:
  570. host_with_port = parsed.hostname
  571. if parsed.port:
  572. host_with_port += ':{}'.format(parsed.port)
  573. for host in no_proxy:
  574. if parsed.hostname.endswith(host) or host_with_port.endswith(host):
  575. # The URL does match something in no_proxy, so we don't want
  576. # to apply the proxies on this URL.
  577. return True
  578. with set_environ('no_proxy', no_proxy_arg):
  579. # parsed.hostname can be `None` in cases such as a file URI.
  580. try:
  581. bypass = proxy_bypass(parsed.hostname)
  582. except (TypeError, socket.gaierror):
  583. bypass = False
  584. if bypass:
  585. return True
  586. return False
  587. def get_environ_proxies(url, no_proxy=None):
  588. """
  589. Return a dict of environment proxies.
  590. :rtype: dict
  591. """
  592. if should_bypass_proxies(url, no_proxy=no_proxy):
  593. return {}
  594. else:
  595. return getproxies()
  596. def select_proxy(url, proxies):
  597. """Select a proxy for the url, if applicable.
  598. :param url: The url being for the request
  599. :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs
  600. """
  601. proxies = proxies or {}
  602. urlparts = urlparse(url)
  603. if urlparts.hostname is None:
  604. return proxies.get(urlparts.scheme, proxies.get('all'))
  605. proxy_keys = [
  606. urlparts.scheme + '://' + urlparts.hostname,
  607. urlparts.scheme,
  608. 'all://' + urlparts.hostname,
  609. 'all',
  610. ]
  611. proxy = None
  612. for proxy_key in proxy_keys:
  613. if proxy_key in proxies:
  614. proxy = proxies[proxy_key]
  615. break
  616. return proxy
  617. def default_user_agent(name="python-requests"):
  618. """
  619. Return a string representing the default user agent.
  620. :rtype: str
  621. """
  622. return '%s/%s' % (name, __version__)
  623. def default_headers():
  624. """
  625. :rtype: requests.structures.CaseInsensitiveDict
  626. """
  627. return CaseInsensitiveDict({
  628. 'User-Agent': default_user_agent(),
  629. 'Accept-Encoding': ', '.join(('gzip', 'deflate')),
  630. 'Accept': '*/*',
  631. 'Connection': 'keep-alive',
  632. })
  633. def parse_header_links(value):
  634. """Return a list of parsed link headers proxies.
  635. i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg"
  636. :rtype: list
  637. """
  638. links = []
  639. replace_chars = ' \'"'
  640. value = value.strip(replace_chars)
  641. if not value:
  642. return links
  643. for val in re.split(', *<', value):
  644. try:
  645. url, params = val.split(';', 1)
  646. except ValueError:
  647. url, params = val, ''
  648. link = {'url': url.strip('<> \'"')}
  649. for param in params.split(';'):
  650. try:
  651. key, value = param.split('=')
  652. except ValueError:
  653. break
  654. link[key.strip(replace_chars)] = value.strip(replace_chars)
  655. links.append(link)
  656. return links
  657. # Null bytes; no need to recreate these on each call to guess_json_utf
  658. _null = '\x00'.encode('ascii') # encoding to ASCII for Python 3
  659. _null2 = _null * 2
  660. _null3 = _null * 3
  661. def guess_json_utf(data):
  662. """
  663. :rtype: str
  664. """
  665. # JSON always starts with two ASCII characters, so detection is as
  666. # easy as counting the nulls and from their location and count
  667. # determine the encoding. Also detect a BOM, if present.
  668. sample = data[:4]
  669. if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE):
  670. return 'utf-32' # BOM included
  671. if sample[:3] == codecs.BOM_UTF8:
  672. return 'utf-8-sig' # BOM included, MS style (discouraged)
  673. if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):
  674. return 'utf-16' # BOM included
  675. nullcount = sample.count(_null)
  676. if nullcount == 0:
  677. return 'utf-8'
  678. if nullcount == 2:
  679. if sample[::2] == _null2: # 1st and 3rd are null
  680. return 'utf-16-be'
  681. if sample[1::2] == _null2: # 2nd and 4th are null
  682. return 'utf-16-le'
  683. # Did not detect 2 valid UTF-16 ascii-range characters
  684. if nullcount == 3:
  685. if sample[:3] == _null3:
  686. return 'utf-32-be'
  687. if sample[1:] == _null3:
  688. return 'utf-32-le'
  689. # Did not detect a valid UTF-32 ascii-range character
  690. return None
  691. def prepend_scheme_if_needed(url, new_scheme):
  692. """Given a URL that may or may not have a scheme, prepend the given scheme.
  693. Does not replace a present scheme with the one provided as an argument.
  694. :rtype: str
  695. """
  696. scheme, netloc, path, params, query, fragment = urlparse(url, new_scheme)
  697. # urlparse is a finicky beast, and sometimes decides that there isn't a
  698. # netloc present. Assume that it's being over-cautious, and switch netloc
  699. # and path if urlparse decided there was no netloc.
  700. if not netloc:
  701. netloc, path = path, netloc
  702. return urlunparse((scheme, netloc, path, params, query, fragment))
  703. def get_auth_from_url(url):
  704. """Given a url with authentication components, extract them into a tuple of
  705. username,password.
  706. :rtype: (str,str)
  707. """
  708. parsed = urlparse(url)
  709. try:
  710. auth = (unquote(parsed.username), unquote(parsed.password))
  711. except (AttributeError, TypeError):
  712. auth = ('', '')
  713. return auth
  714. # Moved outside of function to avoid recompile every call
  715. _CLEAN_HEADER_REGEX_BYTE = re.compile(b'^\\S[^\\r\\n]*$|^$')
  716. _CLEAN_HEADER_REGEX_STR = re.compile(r'^\S[^\r\n]*$|^$')
  717. def check_header_validity(header):
  718. """Verifies that header value is a string which doesn't contain
  719. leading whitespace or return characters. This prevents unintended
  720. header injection.
  721. :param header: tuple, in the format (name, value).
  722. """
  723. name, value = header
  724. if isinstance(value, bytes):
  725. pat = _CLEAN_HEADER_REGEX_BYTE
  726. else:
  727. pat = _CLEAN_HEADER_REGEX_STR
  728. try:
  729. if not pat.match(value):
  730. raise InvalidHeader("Invalid return character or leading space in header: %s" % name)
  731. except TypeError:
  732. raise InvalidHeader("Value for header {%s: %s} must be of type str or "
  733. "bytes, not %s" % (name, value, type(value)))
  734. def urldefragauth(url):
  735. """
  736. Given a url remove the fragment and the authentication part.
  737. :rtype: str
  738. """
  739. scheme, netloc, path, params, query, fragment = urlparse(url)
  740. # see func:`prepend_scheme_if_needed`
  741. if not netloc:
  742. netloc, path = path, netloc
  743. netloc = netloc.rsplit('@', 1)[-1]
  744. return urlunparse((scheme, netloc, path, params, query, ''))
  745. def rewind_body(prepared_request):
  746. """Move file pointer back to its recorded starting position
  747. so it can be read again on redirect.
  748. """
  749. body_seek = getattr(prepared_request.body, 'seek', None)
  750. if body_seek is not None and isinstance(prepared_request._body_position, integer_types):
  751. try:
  752. body_seek(prepared_request._body_position)
  753. except (IOError, OSError):
  754. raise UnrewindableBodyError("An error occurred when rewinding request "
  755. "body for redirect.")
  756. else:
  757. raise UnrewindableBodyError("Unable to rewind request body for redirect.")