Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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.

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