utils.py 30 KB

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