Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 

1087 rader
32 KiB

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