utils.py 27 KB

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