utils.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992
  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. if 'application/json' in content_type:
  395. # Assume UTF-8 based on RFC 4627: https://www.ietf.org/rfc/rfc4627.txt since the charset was unset
  396. return 'utf-8'
  397. def stream_decode_response_unicode(iterator, r):
  398. """Stream decodes a iterator."""
  399. if r.encoding is None:
  400. for item in iterator:
  401. yield item
  402. return
  403. decoder = codecs.getincrementaldecoder(r.encoding)(errors='replace')
  404. for chunk in iterator:
  405. rv = decoder.decode(chunk)
  406. if rv:
  407. yield rv
  408. rv = decoder.decode(b'', final=True)
  409. if rv:
  410. yield rv
  411. def iter_slices(string, slice_length):
  412. """Iterate over slices of a string."""
  413. pos = 0
  414. if slice_length is None or slice_length <= 0:
  415. slice_length = len(string)
  416. while pos < len(string):
  417. yield string[pos:pos + slice_length]
  418. pos += slice_length
  419. def get_unicode_from_response(r):
  420. """Returns the requested content back in unicode.
  421. :param r: Response object to get unicode content from.
  422. Tried:
  423. 1. charset from content-type
  424. 2. fall back and replace all unicode characters
  425. :rtype: str
  426. """
  427. warnings.warn((
  428. 'In requests 3.0, get_unicode_from_response will be removed. For '
  429. 'more information, please see the discussion on issue #2266. (This'
  430. ' warning should only appear once.)'),
  431. DeprecationWarning)
  432. tried_encodings = []
  433. # Try charset from content-type
  434. encoding = get_encoding_from_headers(r.headers)
  435. if encoding:
  436. try:
  437. return str(r.content, encoding)
  438. except UnicodeError:
  439. tried_encodings.append(encoding)
  440. # Fall back:
  441. try:
  442. return str(r.content, encoding, errors='replace')
  443. except TypeError:
  444. return r.content
  445. # The unreserved URI characters (RFC 3986)
  446. UNRESERVED_SET = frozenset(
  447. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789-._~")
  448. def unquote_unreserved(uri):
  449. """Un-escape any percent-escape sequences in a URI that are unreserved
  450. characters. This leaves all reserved, illegal and non-ASCII bytes encoded.
  451. :rtype: str
  452. """
  453. parts = uri.split('%')
  454. for i in range(1, len(parts)):
  455. h = parts[i][0:2]
  456. if len(h) == 2 and h.isalnum():
  457. try:
  458. c = chr(int(h, 16))
  459. except ValueError:
  460. raise InvalidURL("Invalid percent-escape sequence: '%s'" % h)
  461. if c in UNRESERVED_SET:
  462. parts[i] = c + parts[i][2:]
  463. else:
  464. parts[i] = '%' + parts[i]
  465. else:
  466. parts[i] = '%' + parts[i]
  467. return ''.join(parts)
  468. def requote_uri(uri):
  469. """Re-quote the given URI.
  470. This function passes the given URI through an unquote/quote cycle to
  471. ensure that it is fully and consistently quoted.
  472. :rtype: str
  473. """
  474. safe_with_percent = "!#$%&'()*+,/:;=?@[]~"
  475. safe_without_percent = "!#$&'()*+,/:;=?@[]~"
  476. try:
  477. # Unquote only the unreserved characters
  478. # Then quote only illegal characters (do not quote reserved,
  479. # unreserved, or '%')
  480. return quote(unquote_unreserved(uri), safe=safe_with_percent)
  481. except InvalidURL:
  482. # We couldn't unquote the given URI, so let's try quoting it, but
  483. # there may be unquoted '%'s in the URI. We need to make sure they're
  484. # properly quoted so they do not cause issues elsewhere.
  485. return quote(uri, safe=safe_without_percent)
  486. def address_in_network(ip, net):
  487. """This function allows you to check if an IP belongs to a network subnet
  488. Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24
  489. returns False if ip = 192.168.1.1 and net = 192.168.100.0/24
  490. :rtype: bool
  491. """
  492. ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0]
  493. netaddr, bits = net.split('/')
  494. netmask = struct.unpack('=L', socket.inet_aton(dotted_netmask(int(bits))))[0]
  495. network = struct.unpack('=L', socket.inet_aton(netaddr))[0] & netmask
  496. return (ipaddr & netmask) == (network & netmask)
  497. def dotted_netmask(mask):
  498. """Converts mask from /xx format to xxx.xxx.xxx.xxx
  499. Example: if mask is 24 function returns 255.255.255.0
  500. :rtype: str
  501. """
  502. bits = 0xffffffff ^ (1 << 32 - mask) - 1
  503. return socket.inet_ntoa(struct.pack('>I', bits))
  504. def is_ipv4_address(string_ip):
  505. """
  506. :rtype: bool
  507. """
  508. try:
  509. socket.inet_aton(string_ip)
  510. except socket.error:
  511. return False
  512. return True
  513. def is_valid_cidr(string_network):
  514. """
  515. Very simple check of the cidr format in no_proxy variable.
  516. :rtype: bool
  517. """
  518. if string_network.count('/') == 1:
  519. try:
  520. mask = int(string_network.split('/')[1])
  521. except ValueError:
  522. return False
  523. if mask < 1 or mask > 32:
  524. return False
  525. try:
  526. socket.inet_aton(string_network.split('/')[0])
  527. except socket.error:
  528. return False
  529. else:
  530. return False
  531. return True
  532. @contextlib.contextmanager
  533. def set_environ(env_name, value):
  534. """Set the environment variable 'env_name' to 'value'
  535. Save previous value, yield, and then restore the previous value stored in
  536. the environment variable 'env_name'.
  537. If 'value' is None, do nothing"""
  538. value_changed = value is not None
  539. if value_changed:
  540. old_value = os.environ.get(env_name)
  541. os.environ[env_name] = value
  542. try:
  543. yield
  544. finally:
  545. if value_changed:
  546. if old_value is None:
  547. del os.environ[env_name]
  548. else:
  549. os.environ[env_name] = old_value
  550. def should_bypass_proxies(url, no_proxy):
  551. """
  552. Returns whether we should bypass proxies or not.
  553. :rtype: bool
  554. """
  555. # Prioritize lowercase environment variables over uppercase
  556. # to keep a consistent behaviour with other http projects (curl, wget).
  557. get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper())
  558. # First check whether no_proxy is defined. If it is, check that the URL
  559. # we're getting isn't in the no_proxy list.
  560. no_proxy_arg = no_proxy
  561. if no_proxy is None:
  562. no_proxy = get_proxy('no_proxy')
  563. parsed = urlparse(url)
  564. if parsed.hostname is None:
  565. # URLs don't always have hostnames, e.g. file:/// urls.
  566. return True
  567. if no_proxy:
  568. # We need to check whether we match here. We need to see if we match
  569. # the end of the hostname, both with and without the port.
  570. no_proxy = (
  571. host for host in no_proxy.replace(' ', '').split(',') if host
  572. )
  573. if is_ipv4_address(parsed.hostname):
  574. for proxy_ip in no_proxy:
  575. if is_valid_cidr(proxy_ip):
  576. if address_in_network(parsed.hostname, proxy_ip):
  577. return True
  578. elif parsed.hostname == proxy_ip:
  579. # If no_proxy ip was defined in plain IP notation instead of cidr notation &
  580. # matches the IP of the index
  581. return True
  582. else:
  583. host_with_port = parsed.hostname
  584. if parsed.port:
  585. host_with_port += ':{}'.format(parsed.port)
  586. for host in no_proxy:
  587. if parsed.hostname.endswith(host) or host_with_port.endswith(host):
  588. # The URL does match something in no_proxy, so we don't want
  589. # to apply the proxies on this URL.
  590. return True
  591. with set_environ('no_proxy', no_proxy_arg):
  592. # parsed.hostname can be `None` in cases such as a file URI.
  593. try:
  594. bypass = proxy_bypass(parsed.hostname)
  595. except (TypeError, socket.gaierror):
  596. bypass = False
  597. if bypass:
  598. return True
  599. return False
  600. def get_environ_proxies(url, no_proxy=None):
  601. """
  602. Return a dict of environment proxies.
  603. :rtype: dict
  604. """
  605. if should_bypass_proxies(url, no_proxy=no_proxy):
  606. return {}
  607. else:
  608. return getproxies()
  609. def select_proxy(url, proxies):
  610. """Select a proxy for the url, if applicable.
  611. :param url: The url being for the request
  612. :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs
  613. """
  614. proxies = proxies or {}
  615. urlparts = urlparse(url)
  616. if urlparts.hostname is None:
  617. return proxies.get(urlparts.scheme, proxies.get('all'))
  618. proxy_keys = [
  619. urlparts.scheme + '://' + urlparts.hostname,
  620. urlparts.scheme,
  621. 'all://' + urlparts.hostname,
  622. 'all',
  623. ]
  624. proxy = None
  625. for proxy_key in proxy_keys:
  626. if proxy_key in proxies:
  627. proxy = proxies[proxy_key]
  628. break
  629. return proxy
  630. def default_user_agent(name="python-requests"):
  631. """
  632. Return a string representing the default user agent.
  633. :rtype: str
  634. """
  635. return '%s/%s' % (name, __version__)
  636. def default_headers():
  637. """
  638. :rtype: requests.structures.CaseInsensitiveDict
  639. """
  640. return CaseInsensitiveDict({
  641. 'User-Agent': default_user_agent(),
  642. 'Accept-Encoding': ', '.join(('gzip', 'deflate')),
  643. 'Accept': '*/*',
  644. 'Connection': 'keep-alive',
  645. })
  646. def parse_header_links(value):
  647. """Return a list of parsed link headers proxies.
  648. i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg"
  649. :rtype: list
  650. """
  651. links = []
  652. replace_chars = ' \'"'
  653. value = value.strip(replace_chars)
  654. if not value:
  655. return links
  656. for val in re.split(', *<', value):
  657. try:
  658. url, params = val.split(';', 1)
  659. except ValueError:
  660. url, params = val, ''
  661. link = {'url': url.strip('<> \'"')}
  662. for param in params.split(';'):
  663. try:
  664. key, value = param.split('=')
  665. except ValueError:
  666. break
  667. link[key.strip(replace_chars)] = value.strip(replace_chars)
  668. links.append(link)
  669. return links
  670. # Null bytes; no need to recreate these on each call to guess_json_utf
  671. _null = '\x00'.encode('ascii') # encoding to ASCII for Python 3
  672. _null2 = _null * 2
  673. _null3 = _null * 3
  674. def guess_json_utf(data):
  675. """
  676. :rtype: str
  677. """
  678. # JSON always starts with two ASCII characters, so detection is as
  679. # easy as counting the nulls and from their location and count
  680. # determine the encoding. Also detect a BOM, if present.
  681. sample = data[:4]
  682. if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE):
  683. return 'utf-32' # BOM included
  684. if sample[:3] == codecs.BOM_UTF8:
  685. return 'utf-8-sig' # BOM included, MS style (discouraged)
  686. if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):
  687. return 'utf-16' # BOM included
  688. nullcount = sample.count(_null)
  689. if nullcount == 0:
  690. return 'utf-8'
  691. if nullcount == 2:
  692. if sample[::2] == _null2: # 1st and 3rd are null
  693. return 'utf-16-be'
  694. if sample[1::2] == _null2: # 2nd and 4th are null
  695. return 'utf-16-le'
  696. # Did not detect 2 valid UTF-16 ascii-range characters
  697. if nullcount == 3:
  698. if sample[:3] == _null3:
  699. return 'utf-32-be'
  700. if sample[1:] == _null3:
  701. return 'utf-32-le'
  702. # Did not detect a valid UTF-32 ascii-range character
  703. return None
  704. def prepend_scheme_if_needed(url, new_scheme):
  705. """Given a URL that may or may not have a scheme, prepend the given scheme.
  706. Does not replace a present scheme with the one provided as an argument.
  707. :rtype: str
  708. """
  709. scheme, netloc, path, params, query, fragment = urlparse(url, new_scheme)
  710. # urlparse is a finicky beast, and sometimes decides that there isn't a
  711. # netloc present. Assume that it's being over-cautious, and switch netloc
  712. # and path if urlparse decided there was no netloc.
  713. if not netloc:
  714. netloc, path = path, netloc
  715. return urlunparse((scheme, netloc, path, params, query, fragment))
  716. def get_auth_from_url(url):
  717. """Given a url with authentication components, extract them into a tuple of
  718. username,password.
  719. :rtype: (str,str)
  720. """
  721. parsed = urlparse(url)
  722. try:
  723. auth = (unquote(parsed.username), unquote(parsed.password))
  724. except (AttributeError, TypeError):
  725. auth = ('', '')
  726. return auth
  727. # Moved outside of function to avoid recompile every call
  728. _CLEAN_HEADER_REGEX_BYTE = re.compile(b'^\\S[^\\r\\n]*$|^$')
  729. _CLEAN_HEADER_REGEX_STR = re.compile(r'^\S[^\r\n]*$|^$')
  730. def check_header_validity(header):
  731. """Verifies that header value is a string which doesn't contain
  732. leading whitespace or return characters. This prevents unintended
  733. header injection.
  734. :param header: tuple, in the format (name, value).
  735. """
  736. name, value = header
  737. if isinstance(value, bytes):
  738. pat = _CLEAN_HEADER_REGEX_BYTE
  739. else:
  740. pat = _CLEAN_HEADER_REGEX_STR
  741. try:
  742. if not pat.match(value):
  743. raise InvalidHeader("Invalid return character or leading space in header: %s" % name)
  744. except TypeError:
  745. raise InvalidHeader("Value for header {%s: %s} must be of type str or "
  746. "bytes, not %s" % (name, value, type(value)))
  747. def urldefragauth(url):
  748. """
  749. Given a url remove the fragment and the authentication part.
  750. :rtype: str
  751. """
  752. scheme, netloc, path, params, query, fragment = urlparse(url)
  753. # see func:`prepend_scheme_if_needed`
  754. if not netloc:
  755. netloc, path = path, netloc
  756. netloc = netloc.rsplit('@', 1)[-1]
  757. return urlunparse((scheme, netloc, path, params, query, ''))
  758. def rewind_body(prepared_request):
  759. """Move file pointer back to its recorded starting position
  760. so it can be read again on redirect.
  761. """
  762. body_seek = getattr(prepared_request.body, 'seek', None)
  763. if body_seek is not None and isinstance(prepared_request._body_position, integer_types):
  764. try:
  765. body_seek(prepared_request._body_position)
  766. except (IOError, OSError):
  767. raise UnrewindableBodyError("An error occurred when rewinding request "
  768. "body for redirect.")
  769. else:
  770. raise UnrewindableBodyError("Unable to rewind request body for redirect.")