Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

utils.py 29KB

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