utils.py 27 KB

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