jpayne@69: """ jpayne@69: requests.utils jpayne@69: ~~~~~~~~~~~~~~ jpayne@69: jpayne@69: This module provides utility functions that are used within Requests jpayne@69: that are also useful for external consumption. jpayne@69: """ jpayne@69: jpayne@69: import codecs jpayne@69: import contextlib jpayne@69: import io jpayne@69: import os jpayne@69: import re jpayne@69: import socket jpayne@69: import struct jpayne@69: import sys jpayne@69: import tempfile jpayne@69: import warnings jpayne@69: import zipfile jpayne@69: from collections import OrderedDict jpayne@69: jpayne@69: from urllib3.util import make_headers, parse_url jpayne@69: jpayne@69: from . import certs jpayne@69: from .__version__ import __version__ jpayne@69: jpayne@69: # to_native_string is unused here, but imported here for backwards compatibility jpayne@69: from ._internal_utils import ( # noqa: F401 jpayne@69: _HEADER_VALIDATORS_BYTE, jpayne@69: _HEADER_VALIDATORS_STR, jpayne@69: HEADER_VALIDATORS, jpayne@69: to_native_string, jpayne@69: ) jpayne@69: from .compat import ( jpayne@69: Mapping, jpayne@69: basestring, jpayne@69: bytes, jpayne@69: getproxies, jpayne@69: getproxies_environment, jpayne@69: integer_types, jpayne@69: ) jpayne@69: from .compat import parse_http_list as _parse_list_header jpayne@69: from .compat import ( jpayne@69: proxy_bypass, jpayne@69: proxy_bypass_environment, jpayne@69: quote, jpayne@69: str, jpayne@69: unquote, jpayne@69: urlparse, jpayne@69: urlunparse, jpayne@69: ) jpayne@69: from .cookies import cookiejar_from_dict jpayne@69: from .exceptions import ( jpayne@69: FileModeWarning, jpayne@69: InvalidHeader, jpayne@69: InvalidURL, jpayne@69: UnrewindableBodyError, jpayne@69: ) jpayne@69: from .structures import CaseInsensitiveDict jpayne@69: jpayne@69: NETRC_FILES = (".netrc", "_netrc") jpayne@69: jpayne@69: DEFAULT_CA_BUNDLE_PATH = certs.where() jpayne@69: jpayne@69: DEFAULT_PORTS = {"http": 80, "https": 443} jpayne@69: jpayne@69: # Ensure that ', ' is used to preserve previous delimiter behavior. jpayne@69: DEFAULT_ACCEPT_ENCODING = ", ".join( jpayne@69: re.split(r",\s*", make_headers(accept_encoding=True)["accept-encoding"]) jpayne@69: ) jpayne@69: jpayne@69: jpayne@69: if sys.platform == "win32": jpayne@69: # provide a proxy_bypass version on Windows without DNS lookups jpayne@69: jpayne@69: def proxy_bypass_registry(host): jpayne@69: try: jpayne@69: import winreg jpayne@69: except ImportError: jpayne@69: return False jpayne@69: jpayne@69: try: jpayne@69: internetSettings = winreg.OpenKey( jpayne@69: winreg.HKEY_CURRENT_USER, jpayne@69: r"Software\Microsoft\Windows\CurrentVersion\Internet Settings", jpayne@69: ) jpayne@69: # ProxyEnable could be REG_SZ or REG_DWORD, normalizing it jpayne@69: proxyEnable = int(winreg.QueryValueEx(internetSettings, "ProxyEnable")[0]) jpayne@69: # ProxyOverride is almost always a string jpayne@69: proxyOverride = winreg.QueryValueEx(internetSettings, "ProxyOverride")[0] jpayne@69: except (OSError, ValueError): jpayne@69: return False jpayne@69: if not proxyEnable or not proxyOverride: jpayne@69: return False jpayne@69: jpayne@69: # make a check value list from the registry entry: replace the jpayne@69: # '' string by the localhost entry and the corresponding jpayne@69: # canonical entry. jpayne@69: proxyOverride = proxyOverride.split(";") jpayne@69: # filter out empty strings to avoid re.match return true in the following code. jpayne@69: proxyOverride = filter(None, proxyOverride) jpayne@69: # now check if we match one of the registry values. jpayne@69: for test in proxyOverride: jpayne@69: if test == "": jpayne@69: if "." not in host: jpayne@69: return True jpayne@69: test = test.replace(".", r"\.") # mask dots jpayne@69: test = test.replace("*", r".*") # change glob sequence jpayne@69: test = test.replace("?", r".") # change glob char jpayne@69: if re.match(test, host, re.I): jpayne@69: return True jpayne@69: return False jpayne@69: jpayne@69: def proxy_bypass(host): # noqa jpayne@69: """Return True, if the host should be bypassed. jpayne@69: jpayne@69: Checks proxy settings gathered from the environment, if specified, jpayne@69: or the registry. jpayne@69: """ jpayne@69: if getproxies_environment(): jpayne@69: return proxy_bypass_environment(host) jpayne@69: else: jpayne@69: return proxy_bypass_registry(host) jpayne@69: jpayne@69: jpayne@69: def dict_to_sequence(d): jpayne@69: """Returns an internal sequence dictionary update.""" jpayne@69: jpayne@69: if hasattr(d, "items"): jpayne@69: d = d.items() jpayne@69: jpayne@69: return d jpayne@69: jpayne@69: jpayne@69: def super_len(o): jpayne@69: total_length = None jpayne@69: current_position = 0 jpayne@69: jpayne@69: if isinstance(o, str): jpayne@69: o = o.encode("utf-8") jpayne@69: jpayne@69: if hasattr(o, "__len__"): jpayne@69: total_length = len(o) jpayne@69: jpayne@69: elif hasattr(o, "len"): jpayne@69: total_length = o.len jpayne@69: jpayne@69: elif hasattr(o, "fileno"): jpayne@69: try: jpayne@69: fileno = o.fileno() jpayne@69: except (io.UnsupportedOperation, AttributeError): jpayne@69: # AttributeError is a surprising exception, seeing as how we've just checked jpayne@69: # that `hasattr(o, 'fileno')`. It happens for objects obtained via jpayne@69: # `Tarfile.extractfile()`, per issue 5229. jpayne@69: pass jpayne@69: else: jpayne@69: total_length = os.fstat(fileno).st_size jpayne@69: jpayne@69: # Having used fstat to determine the file length, we need to jpayne@69: # confirm that this file was opened up in binary mode. jpayne@69: if "b" not in o.mode: jpayne@69: warnings.warn( jpayne@69: ( jpayne@69: "Requests has determined the content-length for this " jpayne@69: "request using the binary size of the file: however, the " jpayne@69: "file has been opened in text mode (i.e. without the 'b' " jpayne@69: "flag in the mode). This may lead to an incorrect " jpayne@69: "content-length. In Requests 3.0, support will be removed " jpayne@69: "for files in text mode." jpayne@69: ), jpayne@69: FileModeWarning, jpayne@69: ) jpayne@69: jpayne@69: if hasattr(o, "tell"): jpayne@69: try: jpayne@69: current_position = o.tell() jpayne@69: except OSError: jpayne@69: # This can happen in some weird situations, such as when the file jpayne@69: # is actually a special file descriptor like stdin. In this jpayne@69: # instance, we don't know what the length is, so set it to zero and jpayne@69: # let requests chunk it instead. jpayne@69: if total_length is not None: jpayne@69: current_position = total_length jpayne@69: else: jpayne@69: if hasattr(o, "seek") and total_length is None: jpayne@69: # StringIO and BytesIO have seek but no usable fileno jpayne@69: try: jpayne@69: # seek to end of file jpayne@69: o.seek(0, 2) jpayne@69: total_length = o.tell() jpayne@69: jpayne@69: # seek back to current position to support jpayne@69: # partially read file-like objects jpayne@69: o.seek(current_position or 0) jpayne@69: except OSError: jpayne@69: total_length = 0 jpayne@69: jpayne@69: if total_length is None: jpayne@69: total_length = 0 jpayne@69: jpayne@69: return max(0, total_length - current_position) jpayne@69: jpayne@69: jpayne@69: def get_netrc_auth(url, raise_errors=False): jpayne@69: """Returns the Requests tuple auth for a given url from netrc.""" jpayne@69: jpayne@69: netrc_file = os.environ.get("NETRC") jpayne@69: if netrc_file is not None: jpayne@69: netrc_locations = (netrc_file,) jpayne@69: else: jpayne@69: netrc_locations = (f"~/{f}" for f in NETRC_FILES) jpayne@69: jpayne@69: try: jpayne@69: from netrc import NetrcParseError, netrc jpayne@69: jpayne@69: netrc_path = None jpayne@69: jpayne@69: for f in netrc_locations: jpayne@69: try: jpayne@69: loc = os.path.expanduser(f) jpayne@69: except KeyError: jpayne@69: # os.path.expanduser can fail when $HOME is undefined and jpayne@69: # getpwuid fails. See https://bugs.python.org/issue20164 & jpayne@69: # https://github.com/psf/requests/issues/1846 jpayne@69: return jpayne@69: jpayne@69: if os.path.exists(loc): jpayne@69: netrc_path = loc jpayne@69: break jpayne@69: jpayne@69: # Abort early if there isn't one. jpayne@69: if netrc_path is None: jpayne@69: return jpayne@69: jpayne@69: ri = urlparse(url) jpayne@69: jpayne@69: # Strip port numbers from netloc. This weird `if...encode`` dance is jpayne@69: # used for Python 3.2, which doesn't support unicode literals. jpayne@69: splitstr = b":" jpayne@69: if isinstance(url, str): jpayne@69: splitstr = splitstr.decode("ascii") jpayne@69: host = ri.netloc.split(splitstr)[0] jpayne@69: jpayne@69: try: jpayne@69: _netrc = netrc(netrc_path).authenticators(host) jpayne@69: if _netrc: jpayne@69: # Return with login / password jpayne@69: login_i = 0 if _netrc[0] else 1 jpayne@69: return (_netrc[login_i], _netrc[2]) jpayne@69: except (NetrcParseError, OSError): jpayne@69: # If there was a parsing error or a permissions issue reading the file, jpayne@69: # we'll just skip netrc auth unless explicitly asked to raise errors. jpayne@69: if raise_errors: jpayne@69: raise jpayne@69: jpayne@69: # App Engine hackiness. jpayne@69: except (ImportError, AttributeError): jpayne@69: pass jpayne@69: jpayne@69: jpayne@69: def guess_filename(obj): jpayne@69: """Tries to guess the filename of the given object.""" jpayne@69: name = getattr(obj, "name", None) jpayne@69: if name and isinstance(name, basestring) and name[0] != "<" and name[-1] != ">": jpayne@69: return os.path.basename(name) jpayne@69: jpayne@69: jpayne@69: def extract_zipped_paths(path): jpayne@69: """Replace nonexistent paths that look like they refer to a member of a zip jpayne@69: archive with the location of an extracted copy of the target, or else jpayne@69: just return the provided path unchanged. jpayne@69: """ jpayne@69: if os.path.exists(path): jpayne@69: # this is already a valid path, no need to do anything further jpayne@69: return path jpayne@69: jpayne@69: # find the first valid part of the provided path and treat that as a zip archive jpayne@69: # assume the rest of the path is the name of a member in the archive jpayne@69: archive, member = os.path.split(path) jpayne@69: while archive and not os.path.exists(archive): jpayne@69: archive, prefix = os.path.split(archive) jpayne@69: if not prefix: jpayne@69: # If we don't check for an empty prefix after the split (in other words, archive remains unchanged after the split), jpayne@69: # we _can_ end up in an infinite loop on a rare corner case affecting a small number of users jpayne@69: break jpayne@69: member = "/".join([prefix, member]) jpayne@69: jpayne@69: if not zipfile.is_zipfile(archive): jpayne@69: return path jpayne@69: jpayne@69: zip_file = zipfile.ZipFile(archive) jpayne@69: if member not in zip_file.namelist(): jpayne@69: return path jpayne@69: jpayne@69: # we have a valid zip archive and a valid member of that archive jpayne@69: tmp = tempfile.gettempdir() jpayne@69: extracted_path = os.path.join(tmp, member.split("/")[-1]) jpayne@69: if not os.path.exists(extracted_path): jpayne@69: # use read + write to avoid the creating nested folders, we only want the file, avoids mkdir racing condition jpayne@69: with atomic_open(extracted_path) as file_handler: jpayne@69: file_handler.write(zip_file.read(member)) jpayne@69: return extracted_path jpayne@69: jpayne@69: jpayne@69: @contextlib.contextmanager jpayne@69: def atomic_open(filename): jpayne@69: """Write a file to the disk in an atomic fashion""" jpayne@69: tmp_descriptor, tmp_name = tempfile.mkstemp(dir=os.path.dirname(filename)) jpayne@69: try: jpayne@69: with os.fdopen(tmp_descriptor, "wb") as tmp_handler: jpayne@69: yield tmp_handler jpayne@69: os.replace(tmp_name, filename) jpayne@69: except BaseException: jpayne@69: os.remove(tmp_name) jpayne@69: raise jpayne@69: jpayne@69: jpayne@69: def from_key_val_list(value): jpayne@69: """Take an object and test to see if it can be represented as a jpayne@69: dictionary. Unless it can not be represented as such, return an jpayne@69: OrderedDict, e.g., jpayne@69: jpayne@69: :: jpayne@69: jpayne@69: >>> from_key_val_list([('key', 'val')]) jpayne@69: OrderedDict([('key', 'val')]) jpayne@69: >>> from_key_val_list('string') jpayne@69: Traceback (most recent call last): jpayne@69: ... jpayne@69: ValueError: cannot encode objects that are not 2-tuples jpayne@69: >>> from_key_val_list({'key': 'val'}) jpayne@69: OrderedDict([('key', 'val')]) jpayne@69: jpayne@69: :rtype: OrderedDict jpayne@69: """ jpayne@69: if value is None: jpayne@69: return None jpayne@69: jpayne@69: if isinstance(value, (str, bytes, bool, int)): jpayne@69: raise ValueError("cannot encode objects that are not 2-tuples") jpayne@69: jpayne@69: return OrderedDict(value) jpayne@69: jpayne@69: jpayne@69: def to_key_val_list(value): jpayne@69: """Take an object and test to see if it can be represented as a jpayne@69: dictionary. If it can be, return a list of tuples, e.g., jpayne@69: jpayne@69: :: jpayne@69: jpayne@69: >>> to_key_val_list([('key', 'val')]) jpayne@69: [('key', 'val')] jpayne@69: >>> to_key_val_list({'key': 'val'}) jpayne@69: [('key', 'val')] jpayne@69: >>> to_key_val_list('string') jpayne@69: Traceback (most recent call last): jpayne@69: ... jpayne@69: ValueError: cannot encode objects that are not 2-tuples jpayne@69: jpayne@69: :rtype: list jpayne@69: """ jpayne@69: if value is None: jpayne@69: return None jpayne@69: jpayne@69: if isinstance(value, (str, bytes, bool, int)): jpayne@69: raise ValueError("cannot encode objects that are not 2-tuples") jpayne@69: jpayne@69: if isinstance(value, Mapping): jpayne@69: value = value.items() jpayne@69: jpayne@69: return list(value) jpayne@69: jpayne@69: jpayne@69: # From mitsuhiko/werkzeug (used with permission). jpayne@69: def parse_list_header(value): jpayne@69: """Parse lists as described by RFC 2068 Section 2. jpayne@69: jpayne@69: In particular, parse comma-separated lists where the elements of jpayne@69: the list may include quoted-strings. A quoted-string could jpayne@69: contain a comma. A non-quoted string could have quotes in the jpayne@69: middle. Quotes are removed automatically after parsing. jpayne@69: jpayne@69: It basically works like :func:`parse_set_header` just that items jpayne@69: may appear multiple times and case sensitivity is preserved. jpayne@69: jpayne@69: The return value is a standard :class:`list`: jpayne@69: jpayne@69: >>> parse_list_header('token, "quoted value"') jpayne@69: ['token', 'quoted value'] jpayne@69: jpayne@69: To create a header from the :class:`list` again, use the jpayne@69: :func:`dump_header` function. jpayne@69: jpayne@69: :param value: a string with a list header. jpayne@69: :return: :class:`list` jpayne@69: :rtype: list jpayne@69: """ jpayne@69: result = [] jpayne@69: for item in _parse_list_header(value): jpayne@69: if item[:1] == item[-1:] == '"': jpayne@69: item = unquote_header_value(item[1:-1]) jpayne@69: result.append(item) jpayne@69: return result jpayne@69: jpayne@69: jpayne@69: # From mitsuhiko/werkzeug (used with permission). jpayne@69: def parse_dict_header(value): jpayne@69: """Parse lists of key, value pairs as described by RFC 2068 Section 2 and jpayne@69: convert them into a python dict: jpayne@69: jpayne@69: >>> d = parse_dict_header('foo="is a fish", bar="as well"') jpayne@69: >>> type(d) is dict jpayne@69: True jpayne@69: >>> sorted(d.items()) jpayne@69: [('bar', 'as well'), ('foo', 'is a fish')] jpayne@69: jpayne@69: If there is no value for a key it will be `None`: jpayne@69: jpayne@69: >>> parse_dict_header('key_without_value') jpayne@69: {'key_without_value': None} jpayne@69: jpayne@69: To create a header from the :class:`dict` again, use the jpayne@69: :func:`dump_header` function. jpayne@69: jpayne@69: :param value: a string with a dict header. jpayne@69: :return: :class:`dict` jpayne@69: :rtype: dict jpayne@69: """ jpayne@69: result = {} jpayne@69: for item in _parse_list_header(value): jpayne@69: if "=" not in item: jpayne@69: result[item] = None jpayne@69: continue jpayne@69: name, value = item.split("=", 1) jpayne@69: if value[:1] == value[-1:] == '"': jpayne@69: value = unquote_header_value(value[1:-1]) jpayne@69: result[name] = value jpayne@69: return result jpayne@69: jpayne@69: jpayne@69: # From mitsuhiko/werkzeug (used with permission). jpayne@69: def unquote_header_value(value, is_filename=False): jpayne@69: r"""Unquotes a header value. (Reversal of :func:`quote_header_value`). jpayne@69: This does not use the real unquoting but what browsers are actually jpayne@69: using for quoting. jpayne@69: jpayne@69: :param value: the header value to unquote. jpayne@69: :rtype: str jpayne@69: """ jpayne@69: if value and value[0] == value[-1] == '"': jpayne@69: # this is not the real unquoting, but fixing this so that the jpayne@69: # RFC is met will result in bugs with internet explorer and jpayne@69: # probably some other browsers as well. IE for example is jpayne@69: # uploading files with "C:\foo\bar.txt" as filename jpayne@69: value = value[1:-1] jpayne@69: jpayne@69: # if this is a filename and the starting characters look like jpayne@69: # a UNC path, then just return the value without quotes. Using the jpayne@69: # replace sequence below on a UNC path has the effect of turning jpayne@69: # the leading double slash into a single slash and then jpayne@69: # _fix_ie_filename() doesn't work correctly. See #458. jpayne@69: if not is_filename or value[:2] != "\\\\": jpayne@69: return value.replace("\\\\", "\\").replace('\\"', '"') jpayne@69: return value jpayne@69: jpayne@69: jpayne@69: def dict_from_cookiejar(cj): jpayne@69: """Returns a key/value dictionary from a CookieJar. jpayne@69: jpayne@69: :param cj: CookieJar object to extract cookies from. jpayne@69: :rtype: dict jpayne@69: """ jpayne@69: jpayne@69: cookie_dict = {cookie.name: cookie.value for cookie in cj} jpayne@69: return cookie_dict jpayne@69: jpayne@69: jpayne@69: def add_dict_to_cookiejar(cj, cookie_dict): jpayne@69: """Returns a CookieJar from a key/value dictionary. jpayne@69: jpayne@69: :param cj: CookieJar to insert cookies into. jpayne@69: :param cookie_dict: Dict of key/values to insert into CookieJar. jpayne@69: :rtype: CookieJar jpayne@69: """ jpayne@69: jpayne@69: return cookiejar_from_dict(cookie_dict, cj) jpayne@69: jpayne@69: jpayne@69: def get_encodings_from_content(content): jpayne@69: """Returns encodings from given content string. jpayne@69: jpayne@69: :param content: bytestring to extract encodings from. jpayne@69: """ jpayne@69: warnings.warn( jpayne@69: ( jpayne@69: "In requests 3.0, get_encodings_from_content will be removed. For " jpayne@69: "more information, please see the discussion on issue #2266. (This" jpayne@69: " warning should only appear once.)" jpayne@69: ), jpayne@69: DeprecationWarning, jpayne@69: ) jpayne@69: jpayne@69: charset_re = re.compile(r']', flags=re.I) jpayne@69: pragma_re = re.compile(r']', flags=re.I) jpayne@69: xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]') jpayne@69: jpayne@69: return ( jpayne@69: charset_re.findall(content) jpayne@69: + pragma_re.findall(content) jpayne@69: + xml_re.findall(content) jpayne@69: ) jpayne@69: jpayne@69: jpayne@69: def _parse_content_type_header(header): jpayne@69: """Returns content type and parameters from given header jpayne@69: jpayne@69: :param header: string jpayne@69: :return: tuple containing content type and dictionary of jpayne@69: parameters jpayne@69: """ jpayne@69: jpayne@69: tokens = header.split(";") jpayne@69: content_type, params = tokens[0].strip(), tokens[1:] jpayne@69: params_dict = {} jpayne@69: items_to_strip = "\"' " jpayne@69: jpayne@69: for param in params: jpayne@69: param = param.strip() jpayne@69: if param: jpayne@69: key, value = param, True jpayne@69: index_of_equals = param.find("=") jpayne@69: if index_of_equals != -1: jpayne@69: key = param[:index_of_equals].strip(items_to_strip) jpayne@69: value = param[index_of_equals + 1 :].strip(items_to_strip) jpayne@69: params_dict[key.lower()] = value jpayne@69: return content_type, params_dict jpayne@69: jpayne@69: jpayne@69: def get_encoding_from_headers(headers): jpayne@69: """Returns encodings from given HTTP Header Dict. jpayne@69: jpayne@69: :param headers: dictionary to extract encoding from. jpayne@69: :rtype: str jpayne@69: """ jpayne@69: jpayne@69: content_type = headers.get("content-type") jpayne@69: jpayne@69: if not content_type: jpayne@69: return None jpayne@69: jpayne@69: content_type, params = _parse_content_type_header(content_type) jpayne@69: jpayne@69: if "charset" in params: jpayne@69: return params["charset"].strip("'\"") jpayne@69: jpayne@69: if "text" in content_type: jpayne@69: return "ISO-8859-1" jpayne@69: jpayne@69: if "application/json" in content_type: jpayne@69: # Assume UTF-8 based on RFC 4627: https://www.ietf.org/rfc/rfc4627.txt since the charset was unset jpayne@69: return "utf-8" jpayne@69: jpayne@69: jpayne@69: def stream_decode_response_unicode(iterator, r): jpayne@69: """Stream decodes an iterator.""" jpayne@69: jpayne@69: if r.encoding is None: jpayne@69: yield from iterator jpayne@69: return jpayne@69: jpayne@69: decoder = codecs.getincrementaldecoder(r.encoding)(errors="replace") jpayne@69: for chunk in iterator: jpayne@69: rv = decoder.decode(chunk) jpayne@69: if rv: jpayne@69: yield rv jpayne@69: rv = decoder.decode(b"", final=True) jpayne@69: if rv: jpayne@69: yield rv jpayne@69: jpayne@69: jpayne@69: def iter_slices(string, slice_length): jpayne@69: """Iterate over slices of a string.""" jpayne@69: pos = 0 jpayne@69: if slice_length is None or slice_length <= 0: jpayne@69: slice_length = len(string) jpayne@69: while pos < len(string): jpayne@69: yield string[pos : pos + slice_length] jpayne@69: pos += slice_length jpayne@69: jpayne@69: jpayne@69: def get_unicode_from_response(r): jpayne@69: """Returns the requested content back in unicode. jpayne@69: jpayne@69: :param r: Response object to get unicode content from. jpayne@69: jpayne@69: Tried: jpayne@69: jpayne@69: 1. charset from content-type jpayne@69: 2. fall back and replace all unicode characters jpayne@69: jpayne@69: :rtype: str jpayne@69: """ jpayne@69: warnings.warn( jpayne@69: ( jpayne@69: "In requests 3.0, get_unicode_from_response will be removed. For " jpayne@69: "more information, please see the discussion on issue #2266. (This" jpayne@69: " warning should only appear once.)" jpayne@69: ), jpayne@69: DeprecationWarning, jpayne@69: ) jpayne@69: jpayne@69: tried_encodings = [] jpayne@69: jpayne@69: # Try charset from content-type jpayne@69: encoding = get_encoding_from_headers(r.headers) jpayne@69: jpayne@69: if encoding: jpayne@69: try: jpayne@69: return str(r.content, encoding) jpayne@69: except UnicodeError: jpayne@69: tried_encodings.append(encoding) jpayne@69: jpayne@69: # Fall back: jpayne@69: try: jpayne@69: return str(r.content, encoding, errors="replace") jpayne@69: except TypeError: jpayne@69: return r.content jpayne@69: jpayne@69: jpayne@69: # The unreserved URI characters (RFC 3986) jpayne@69: UNRESERVED_SET = frozenset( jpayne@69: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789-._~" jpayne@69: ) jpayne@69: jpayne@69: jpayne@69: def unquote_unreserved(uri): jpayne@69: """Un-escape any percent-escape sequences in a URI that are unreserved jpayne@69: characters. This leaves all reserved, illegal and non-ASCII bytes encoded. jpayne@69: jpayne@69: :rtype: str jpayne@69: """ jpayne@69: parts = uri.split("%") jpayne@69: for i in range(1, len(parts)): jpayne@69: h = parts[i][0:2] jpayne@69: if len(h) == 2 and h.isalnum(): jpayne@69: try: jpayne@69: c = chr(int(h, 16)) jpayne@69: except ValueError: jpayne@69: raise InvalidURL(f"Invalid percent-escape sequence: '{h}'") jpayne@69: jpayne@69: if c in UNRESERVED_SET: jpayne@69: parts[i] = c + parts[i][2:] jpayne@69: else: jpayne@69: parts[i] = f"%{parts[i]}" jpayne@69: else: jpayne@69: parts[i] = f"%{parts[i]}" jpayne@69: return "".join(parts) jpayne@69: jpayne@69: jpayne@69: def requote_uri(uri): jpayne@69: """Re-quote the given URI. jpayne@69: jpayne@69: This function passes the given URI through an unquote/quote cycle to jpayne@69: ensure that it is fully and consistently quoted. jpayne@69: jpayne@69: :rtype: str jpayne@69: """ jpayne@69: safe_with_percent = "!#$%&'()*+,/:;=?@[]~" jpayne@69: safe_without_percent = "!#$&'()*+,/:;=?@[]~" jpayne@69: try: jpayne@69: # Unquote only the unreserved characters jpayne@69: # Then quote only illegal characters (do not quote reserved, jpayne@69: # unreserved, or '%') jpayne@69: return quote(unquote_unreserved(uri), safe=safe_with_percent) jpayne@69: except InvalidURL: jpayne@69: # We couldn't unquote the given URI, so let's try quoting it, but jpayne@69: # there may be unquoted '%'s in the URI. We need to make sure they're jpayne@69: # properly quoted so they do not cause issues elsewhere. jpayne@69: return quote(uri, safe=safe_without_percent) jpayne@69: jpayne@69: jpayne@69: def address_in_network(ip, net): jpayne@69: """This function allows you to check if an IP belongs to a network subnet jpayne@69: jpayne@69: Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24 jpayne@69: returns False if ip = 192.168.1.1 and net = 192.168.100.0/24 jpayne@69: jpayne@69: :rtype: bool jpayne@69: """ jpayne@69: ipaddr = struct.unpack("=L", socket.inet_aton(ip))[0] jpayne@69: netaddr, bits = net.split("/") jpayne@69: netmask = struct.unpack("=L", socket.inet_aton(dotted_netmask(int(bits))))[0] jpayne@69: network = struct.unpack("=L", socket.inet_aton(netaddr))[0] & netmask jpayne@69: return (ipaddr & netmask) == (network & netmask) jpayne@69: jpayne@69: jpayne@69: def dotted_netmask(mask): jpayne@69: """Converts mask from /xx format to xxx.xxx.xxx.xxx jpayne@69: jpayne@69: Example: if mask is 24 function returns 255.255.255.0 jpayne@69: jpayne@69: :rtype: str jpayne@69: """ jpayne@69: bits = 0xFFFFFFFF ^ (1 << 32 - mask) - 1 jpayne@69: return socket.inet_ntoa(struct.pack(">I", bits)) jpayne@69: jpayne@69: jpayne@69: def is_ipv4_address(string_ip): jpayne@69: """ jpayne@69: :rtype: bool jpayne@69: """ jpayne@69: try: jpayne@69: socket.inet_aton(string_ip) jpayne@69: except OSError: jpayne@69: return False jpayne@69: return True jpayne@69: jpayne@69: jpayne@69: def is_valid_cidr(string_network): jpayne@69: """ jpayne@69: Very simple check of the cidr format in no_proxy variable. jpayne@69: jpayne@69: :rtype: bool jpayne@69: """ jpayne@69: if string_network.count("/") == 1: jpayne@69: try: jpayne@69: mask = int(string_network.split("/")[1]) jpayne@69: except ValueError: jpayne@69: return False jpayne@69: jpayne@69: if mask < 1 or mask > 32: jpayne@69: return False jpayne@69: jpayne@69: try: jpayne@69: socket.inet_aton(string_network.split("/")[0]) jpayne@69: except OSError: jpayne@69: return False jpayne@69: else: jpayne@69: return False jpayne@69: return True jpayne@69: jpayne@69: jpayne@69: @contextlib.contextmanager jpayne@69: def set_environ(env_name, value): jpayne@69: """Set the environment variable 'env_name' to 'value' jpayne@69: jpayne@69: Save previous value, yield, and then restore the previous value stored in jpayne@69: the environment variable 'env_name'. jpayne@69: jpayne@69: If 'value' is None, do nothing""" jpayne@69: value_changed = value is not None jpayne@69: if value_changed: jpayne@69: old_value = os.environ.get(env_name) jpayne@69: os.environ[env_name] = value jpayne@69: try: jpayne@69: yield jpayne@69: finally: jpayne@69: if value_changed: jpayne@69: if old_value is None: jpayne@69: del os.environ[env_name] jpayne@69: else: jpayne@69: os.environ[env_name] = old_value jpayne@69: jpayne@69: jpayne@69: def should_bypass_proxies(url, no_proxy): jpayne@69: """ jpayne@69: Returns whether we should bypass proxies or not. jpayne@69: jpayne@69: :rtype: bool jpayne@69: """ jpayne@69: jpayne@69: # Prioritize lowercase environment variables over uppercase jpayne@69: # to keep a consistent behaviour with other http projects (curl, wget). jpayne@69: def get_proxy(key): jpayne@69: return os.environ.get(key) or os.environ.get(key.upper()) jpayne@69: jpayne@69: # First check whether no_proxy is defined. If it is, check that the URL jpayne@69: # we're getting isn't in the no_proxy list. jpayne@69: no_proxy_arg = no_proxy jpayne@69: if no_proxy is None: jpayne@69: no_proxy = get_proxy("no_proxy") jpayne@69: parsed = urlparse(url) jpayne@69: jpayne@69: if parsed.hostname is None: jpayne@69: # URLs don't always have hostnames, e.g. file:/// urls. jpayne@69: return True jpayne@69: jpayne@69: if no_proxy: jpayne@69: # We need to check whether we match here. We need to see if we match jpayne@69: # the end of the hostname, both with and without the port. jpayne@69: no_proxy = (host for host in no_proxy.replace(" ", "").split(",") if host) jpayne@69: jpayne@69: if is_ipv4_address(parsed.hostname): jpayne@69: for proxy_ip in no_proxy: jpayne@69: if is_valid_cidr(proxy_ip): jpayne@69: if address_in_network(parsed.hostname, proxy_ip): jpayne@69: return True jpayne@69: elif parsed.hostname == proxy_ip: jpayne@69: # If no_proxy ip was defined in plain IP notation instead of cidr notation & jpayne@69: # matches the IP of the index jpayne@69: return True jpayne@69: else: jpayne@69: host_with_port = parsed.hostname jpayne@69: if parsed.port: jpayne@69: host_with_port += f":{parsed.port}" jpayne@69: jpayne@69: for host in no_proxy: jpayne@69: if parsed.hostname.endswith(host) or host_with_port.endswith(host): jpayne@69: # The URL does match something in no_proxy, so we don't want jpayne@69: # to apply the proxies on this URL. jpayne@69: return True jpayne@69: jpayne@69: with set_environ("no_proxy", no_proxy_arg): jpayne@69: # parsed.hostname can be `None` in cases such as a file URI. jpayne@69: try: jpayne@69: bypass = proxy_bypass(parsed.hostname) jpayne@69: except (TypeError, socket.gaierror): jpayne@69: bypass = False jpayne@69: jpayne@69: if bypass: jpayne@69: return True jpayne@69: jpayne@69: return False jpayne@69: jpayne@69: jpayne@69: def get_environ_proxies(url, no_proxy=None): jpayne@69: """ jpayne@69: Return a dict of environment proxies. jpayne@69: jpayne@69: :rtype: dict jpayne@69: """ jpayne@69: if should_bypass_proxies(url, no_proxy=no_proxy): jpayne@69: return {} jpayne@69: else: jpayne@69: return getproxies() jpayne@69: jpayne@69: jpayne@69: def select_proxy(url, proxies): jpayne@69: """Select a proxy for the url, if applicable. jpayne@69: jpayne@69: :param url: The url being for the request jpayne@69: :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs jpayne@69: """ jpayne@69: proxies = proxies or {} jpayne@69: urlparts = urlparse(url) jpayne@69: if urlparts.hostname is None: jpayne@69: return proxies.get(urlparts.scheme, proxies.get("all")) jpayne@69: jpayne@69: proxy_keys = [ jpayne@69: urlparts.scheme + "://" + urlparts.hostname, jpayne@69: urlparts.scheme, jpayne@69: "all://" + urlparts.hostname, jpayne@69: "all", jpayne@69: ] jpayne@69: proxy = None jpayne@69: for proxy_key in proxy_keys: jpayne@69: if proxy_key in proxies: jpayne@69: proxy = proxies[proxy_key] jpayne@69: break jpayne@69: jpayne@69: return proxy jpayne@69: jpayne@69: jpayne@69: def resolve_proxies(request, proxies, trust_env=True): jpayne@69: """This method takes proxy information from a request and configuration jpayne@69: input to resolve a mapping of target proxies. This will consider settings jpayne@69: such as NO_PROXY to strip proxy configurations. jpayne@69: jpayne@69: :param request: Request or PreparedRequest jpayne@69: :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs jpayne@69: :param trust_env: Boolean declaring whether to trust environment configs jpayne@69: jpayne@69: :rtype: dict jpayne@69: """ jpayne@69: proxies = proxies if proxies is not None else {} jpayne@69: url = request.url jpayne@69: scheme = urlparse(url).scheme jpayne@69: no_proxy = proxies.get("no_proxy") jpayne@69: new_proxies = proxies.copy() jpayne@69: jpayne@69: if trust_env and not should_bypass_proxies(url, no_proxy=no_proxy): jpayne@69: environ_proxies = get_environ_proxies(url, no_proxy=no_proxy) jpayne@69: jpayne@69: proxy = environ_proxies.get(scheme, environ_proxies.get("all")) jpayne@69: jpayne@69: if proxy: jpayne@69: new_proxies.setdefault(scheme, proxy) jpayne@69: return new_proxies jpayne@69: jpayne@69: jpayne@69: def default_user_agent(name="python-requests"): jpayne@69: """ jpayne@69: Return a string representing the default user agent. jpayne@69: jpayne@69: :rtype: str jpayne@69: """ jpayne@69: return f"{name}/{__version__}" jpayne@69: jpayne@69: jpayne@69: def default_headers(): jpayne@69: """ jpayne@69: :rtype: requests.structures.CaseInsensitiveDict jpayne@69: """ jpayne@69: return CaseInsensitiveDict( jpayne@69: { jpayne@69: "User-Agent": default_user_agent(), jpayne@69: "Accept-Encoding": DEFAULT_ACCEPT_ENCODING, jpayne@69: "Accept": "*/*", jpayne@69: "Connection": "keep-alive", jpayne@69: } jpayne@69: ) jpayne@69: jpayne@69: jpayne@69: def parse_header_links(value): jpayne@69: """Return a list of parsed link headers proxies. jpayne@69: jpayne@69: i.e. Link: ; rel=front; type="image/jpeg",; rel=back;type="image/jpeg" jpayne@69: jpayne@69: :rtype: list jpayne@69: """ jpayne@69: jpayne@69: links = [] jpayne@69: jpayne@69: replace_chars = " '\"" jpayne@69: jpayne@69: value = value.strip(replace_chars) jpayne@69: if not value: jpayne@69: return links jpayne@69: jpayne@69: for val in re.split(", *<", value): jpayne@69: try: jpayne@69: url, params = val.split(";", 1) jpayne@69: except ValueError: jpayne@69: url, params = val, "" jpayne@69: jpayne@69: link = {"url": url.strip("<> '\"")} jpayne@69: jpayne@69: for param in params.split(";"): jpayne@69: try: jpayne@69: key, value = param.split("=") jpayne@69: except ValueError: jpayne@69: break jpayne@69: jpayne@69: link[key.strip(replace_chars)] = value.strip(replace_chars) jpayne@69: jpayne@69: links.append(link) jpayne@69: jpayne@69: return links jpayne@69: jpayne@69: jpayne@69: # Null bytes; no need to recreate these on each call to guess_json_utf jpayne@69: _null = "\x00".encode("ascii") # encoding to ASCII for Python 3 jpayne@69: _null2 = _null * 2 jpayne@69: _null3 = _null * 3 jpayne@69: jpayne@69: jpayne@69: def guess_json_utf(data): jpayne@69: """ jpayne@69: :rtype: str jpayne@69: """ jpayne@69: # JSON always starts with two ASCII characters, so detection is as jpayne@69: # easy as counting the nulls and from their location and count jpayne@69: # determine the encoding. Also detect a BOM, if present. jpayne@69: sample = data[:4] jpayne@69: if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE): jpayne@69: return "utf-32" # BOM included jpayne@69: if sample[:3] == codecs.BOM_UTF8: jpayne@69: return "utf-8-sig" # BOM included, MS style (discouraged) jpayne@69: if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE): jpayne@69: return "utf-16" # BOM included jpayne@69: nullcount = sample.count(_null) jpayne@69: if nullcount == 0: jpayne@69: return "utf-8" jpayne@69: if nullcount == 2: jpayne@69: if sample[::2] == _null2: # 1st and 3rd are null jpayne@69: return "utf-16-be" jpayne@69: if sample[1::2] == _null2: # 2nd and 4th are null jpayne@69: return "utf-16-le" jpayne@69: # Did not detect 2 valid UTF-16 ascii-range characters jpayne@69: if nullcount == 3: jpayne@69: if sample[:3] == _null3: jpayne@69: return "utf-32-be" jpayne@69: if sample[1:] == _null3: jpayne@69: return "utf-32-le" jpayne@69: # Did not detect a valid UTF-32 ascii-range character jpayne@69: return None jpayne@69: jpayne@69: jpayne@69: def prepend_scheme_if_needed(url, new_scheme): jpayne@69: """Given a URL that may or may not have a scheme, prepend the given scheme. jpayne@69: Does not replace a present scheme with the one provided as an argument. jpayne@69: jpayne@69: :rtype: str jpayne@69: """ jpayne@69: parsed = parse_url(url) jpayne@69: scheme, auth, host, port, path, query, fragment = parsed jpayne@69: jpayne@69: # A defect in urlparse determines that there isn't a netloc present in some jpayne@69: # urls. We previously assumed parsing was overly cautious, and swapped the jpayne@69: # netloc and path. Due to a lack of tests on the original defect, this is jpayne@69: # maintained with parse_url for backwards compatibility. jpayne@69: netloc = parsed.netloc jpayne@69: if not netloc: jpayne@69: netloc, path = path, netloc jpayne@69: jpayne@69: if auth: jpayne@69: # parse_url doesn't provide the netloc with auth jpayne@69: # so we'll add it ourselves. jpayne@69: netloc = "@".join([auth, netloc]) jpayne@69: if scheme is None: jpayne@69: scheme = new_scheme jpayne@69: if path is None: jpayne@69: path = "" jpayne@69: jpayne@69: return urlunparse((scheme, netloc, path, "", query, fragment)) jpayne@69: jpayne@69: jpayne@69: def get_auth_from_url(url): jpayne@69: """Given a url with authentication components, extract them into a tuple of jpayne@69: username,password. jpayne@69: jpayne@69: :rtype: (str,str) jpayne@69: """ jpayne@69: parsed = urlparse(url) jpayne@69: jpayne@69: try: jpayne@69: auth = (unquote(parsed.username), unquote(parsed.password)) jpayne@69: except (AttributeError, TypeError): jpayne@69: auth = ("", "") jpayne@69: jpayne@69: return auth jpayne@69: jpayne@69: jpayne@69: def check_header_validity(header): jpayne@69: """Verifies that header parts don't contain leading whitespace jpayne@69: reserved characters, or return characters. jpayne@69: jpayne@69: :param header: tuple, in the format (name, value). jpayne@69: """ jpayne@69: name, value = header jpayne@69: _validate_header_part(header, name, 0) jpayne@69: _validate_header_part(header, value, 1) jpayne@69: jpayne@69: jpayne@69: def _validate_header_part(header, header_part, header_validator_index): jpayne@69: if isinstance(header_part, str): jpayne@69: validator = _HEADER_VALIDATORS_STR[header_validator_index] jpayne@69: elif isinstance(header_part, bytes): jpayne@69: validator = _HEADER_VALIDATORS_BYTE[header_validator_index] jpayne@69: else: jpayne@69: raise InvalidHeader( jpayne@69: f"Header part ({header_part!r}) from {header} " jpayne@69: f"must be of type str or bytes, not {type(header_part)}" jpayne@69: ) jpayne@69: jpayne@69: if not validator.match(header_part): jpayne@69: header_kind = "name" if header_validator_index == 0 else "value" jpayne@69: raise InvalidHeader( jpayne@69: f"Invalid leading whitespace, reserved character(s), or return " jpayne@69: f"character(s) in header {header_kind}: {header_part!r}" jpayne@69: ) jpayne@69: jpayne@69: jpayne@69: def urldefragauth(url): jpayne@69: """ jpayne@69: Given a url remove the fragment and the authentication part. jpayne@69: jpayne@69: :rtype: str jpayne@69: """ jpayne@69: scheme, netloc, path, params, query, fragment = urlparse(url) jpayne@69: jpayne@69: # see func:`prepend_scheme_if_needed` jpayne@69: if not netloc: jpayne@69: netloc, path = path, netloc jpayne@69: jpayne@69: netloc = netloc.rsplit("@", 1)[-1] jpayne@69: jpayne@69: return urlunparse((scheme, netloc, path, params, query, "")) jpayne@69: jpayne@69: jpayne@69: def rewind_body(prepared_request): jpayne@69: """Move file pointer back to its recorded starting position jpayne@69: so it can be read again on redirect. jpayne@69: """ jpayne@69: body_seek = getattr(prepared_request.body, "seek", None) jpayne@69: if body_seek is not None and isinstance( jpayne@69: prepared_request._body_position, integer_types jpayne@69: ): jpayne@69: try: jpayne@69: body_seek(prepared_request._body_position) jpayne@69: except OSError: jpayne@69: raise UnrewindableBodyError( jpayne@69: "An error occurred when rewinding request body for redirect." jpayne@69: ) jpayne@69: else: jpayne@69: raise UnrewindableBodyError("Unable to rewind request body for redirect.")