Skip to content
Myr

utils.py

This file

Path

requests/utils.py

976 lines · 29.4 KiB · Python

Last changed by

Separate collections from collections.abcRaymond Hettingerbefore adoption7e297ed

History of this file

Take it

1# -*- coding: utf-8 -*-23"""4requests.utils5~~~~~~~~~~~~~~67This module provides utility functions that are used within Requests8that are also useful for external consumption.9"""1011import codecs12import contextlib13import io14import os15import re16import socket17import struct18import sys19import tempfile20import warnings21import zipfile2223from .__version__ import __version__24from . import certs25# to_native_string is unused here, but imported here for backwards compatibility26from ._internal_utils import to_native_string27from .compat import parse_http_list as _parse_list_header28from .compat import (29    quote, urlparse, bytes, str, OrderedDict, unquote, getproxies,30    proxy_bypass, urlunparse, basestring, integer_types, is_py3,31    proxy_bypass_environment, getproxies_environment, Mapping)32from .cookies import cookiejar_from_dict33from .structures import CaseInsensitiveDict34from .exceptions import (35    InvalidURL, InvalidHeader, FileModeWarning, UnrewindableBodyError)3637NETRC_FILES = ('.netrc', '_netrc')3839DEFAULT_CA_BUNDLE_PATH = certs.where()404142if sys.platform == 'win32':43    # provide a proxy_bypass version on Windows without DNS lookups4445    def proxy_bypass_registry(host):46        try:47            if is_py3:48                import winreg49            else:50                import _winreg as winreg51        except ImportError:52            return False5354        try:55            internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,56                r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')57            # ProxyEnable could be REG_SZ or REG_DWORD, normalizing it58            proxyEnable = int(winreg.QueryValueEx(internetSettings,59                                              'ProxyEnable')[0])60            # ProxyOverride is almost always a string61            proxyOverride = winreg.QueryValueEx(internetSettings,62                                                'ProxyOverride')[0]63        except OSError:64            return False65        if not proxyEnable or not proxyOverride:66            return False6768        # make a check value list from the registry entry: replace the69        # '<local>' string by the localhost entry and the corresponding70        # canonical entry.71        proxyOverride = proxyOverride.split(';')72        # now check if we match one of the registry values.73        for test in proxyOverride:74            if test == '<local>':75                if '.' not in host:76                    return True77            test = test.replace(".", r"\.")     # mask dots78            test = test.replace("*", r".*")     # change glob sequence79            test = test.replace("?", r".")      # change glob char80            if re.match(test, host, re.I):81                return True82        return False8384    def proxy_bypass(host):  # noqa85        """Return True, if the host should be bypassed.8687        Checks proxy settings gathered from the environment, if specified,88        or the registry.89        """90        if getproxies_environment():91            return proxy_bypass_environment(host)92        else:93            return proxy_bypass_registry(host)949596def dict_to_sequence(d):97    """Returns an internal sequence dictionary update."""9899    if hasattr(d, 'items'):100        d = d.items()101102    return d103104105def super_len(o):106    total_length = None107    current_position = 0108109    if hasattr(o, '__len__'):110        total_length = len(o)111112    elif hasattr(o, 'len'):113        total_length = o.len114115    elif hasattr(o, 'fileno'):116        try:117            fileno = o.fileno()118        except io.UnsupportedOperation:119            pass120        else:121            total_length = os.fstat(fileno).st_size122123            # Having used fstat to determine the file length, we need to124            # confirm that this file was opened up in binary mode.125            if 'b' not in o.mode:126                warnings.warn((127                    "Requests has determined the content-length for this "128                    "request using the binary size of the file: however, the "129                    "file has been opened in text mode (i.e. without the 'b' "130                    "flag in the mode). This may lead to an incorrect "131                    "content-length. In Requests 3.0, support will be removed "132                    "for files in text mode."),133                    FileModeWarning134                )135136    if hasattr(o, 'tell'):137        try:138            current_position = o.tell()139        except (OSError, IOError):140            # This can happen in some weird situations, such as when the file141            # is actually a special file descriptor like stdin. In this142            # instance, we don't know what the length is, so set it to zero and143            # let requests chunk it instead.144            if total_length is not None:145                current_position = total_length146        else:147            if hasattr(o, 'seek') and total_length is None:148                # StringIO and BytesIO have seek but no useable fileno149                try:150                    # seek to end of file151                    o.seek(0, 2)152                    total_length = o.tell()153154                    # seek back to current position to support155                    # partially read file-like objects156                    o.seek(current_position or 0)157                except (OSError, IOError):158                    total_length = 0159160    if total_length is None:161        total_length = 0162163    return max(0, total_length - current_position)164165166def get_netrc_auth(url, raise_errors=False):167    """Returns the Requests tuple auth for a given url from netrc."""168169    try:170        from netrc import netrc, NetrcParseError171172        netrc_path = None173174        for f in NETRC_FILES:175            try:176                loc = os.path.expanduser('~/{0}'.format(f))177            except KeyError:178                # os.path.expanduser can fail when $HOME is undefined and179                # getpwuid fails. See http://bugs.python.org/issue20164 &180                # https://github.com/requests/requests/issues/1846181                return182183            if os.path.exists(loc):184                netrc_path = loc185                break186187        # Abort early if there isn't one.188        if netrc_path is None:189            return190191        ri = urlparse(url)192193        # Strip port numbers from netloc. This weird `if...encode`` dance is194        # used for Python 3.2, which doesn't support unicode literals.195        splitstr = b':'196        if isinstance(url, str):197            splitstr = splitstr.decode('ascii')198        host = ri.netloc.split(splitstr)[0]199200        try:201            _netrc = netrc(netrc_path).authenticators(host)202            if _netrc:203                # Return with login / password204                login_i = (0 if _netrc[0] else 1)205                return (_netrc[login_i], _netrc[2])206        except (NetrcParseError, IOError):207            # If there was a parsing error or a permissions issue reading the file,208            # we'll just skip netrc auth unless explicitly asked to raise errors.209            if raise_errors:210                raise211212    # AppEngine hackiness.213    except (ImportError, AttributeError):214        pass215216217def guess_filename(obj):218    """Tries to guess the filename of the given object."""219    name = getattr(obj, 'name', None)220    if (name and isinstance(name, basestring) and name[0] != '<' and221            name[-1] != '>'):222        return os.path.basename(name)223224225def extract_zipped_paths(path):226    """Replace nonexistent paths that look like they refer to a member of a zip227    archive with the location of an extracted copy of the target, or else228    just return the provided path unchanged.229    """230    if os.path.exists(path):231        # this is already a valid path, no need to do anything further232        return path233234    # find the first valid part of the provided path and treat that as a zip archive235    # assume the rest of the path is the name of a member in the archive236    archive, member = os.path.split(path)237    while archive and not os.path.exists(archive):238        archive, prefix = os.path.split(archive)239        member = '/'.join([prefix, member])240241    if not zipfile.is_zipfile(archive):242        return path243244    zip_file = zipfile.ZipFile(archive)245    if member not in zip_file.namelist():246        return path247248    # we have a valid zip archive and a valid member of that archive249    tmp = tempfile.gettempdir()250    extracted_path = os.path.join(tmp, *member.split('/'))251    if not os.path.exists(extracted_path):252        extracted_path = zip_file.extract(member, path=tmp)253254    return extracted_path255256257def from_key_val_list(value):258    """Take an object and test to see if it can be represented as a259    dictionary. Unless it can not be represented as such, return an260    OrderedDict, e.g.,261262    ::263264        >>> from_key_val_list([('key', 'val')])265        OrderedDict([('key', 'val')])266        >>> from_key_val_list('string')267        ValueError: need more than 1 value to unpack268        >>> from_key_val_list({'key': 'val'})269        OrderedDict([('key', 'val')])270271    :rtype: OrderedDict272    """273    if value is None:274        return None275276    if isinstance(value, (str, bytes, bool, int)):277        raise ValueError('cannot encode objects that are not 2-tuples')278279    return OrderedDict(value)280281282def to_key_val_list(value):283    """Take an object and test to see if it can be represented as a284    dictionary. If it can be, return a list of tuples, e.g.,285286    ::287288        >>> to_key_val_list([('key', 'val')])289        [('key', 'val')]290        >>> to_key_val_list({'key': 'val'})291        [('key', 'val')]292        >>> to_key_val_list('string')293        ValueError: cannot encode objects that are not 2-tuples.294295    :rtype: list296    """297    if value is None:298        return None299300    if isinstance(value, (str, bytes, bool, int)):301        raise ValueError('cannot encode objects that are not 2-tuples')302303    if isinstance(value, Mapping):304        value = value.items()305306    return list(value)307308309# From mitsuhiko/werkzeug (used with permission).310def parse_list_header(value):311    """Parse lists as described by RFC 2068 Section 2.312313    In particular, parse comma-separated lists where the elements of314    the list may include quoted-strings.  A quoted-string could315    contain a comma.  A non-quoted string could have quotes in the316    middle.  Quotes are removed automatically after parsing.317318    It basically works like :func:`parse_set_header` just that items319    may appear multiple times and case sensitivity is preserved.320321    The return value is a standard :class:`list`:322323    >>> parse_list_header('token, "quoted value"')324    ['token', 'quoted value']325326    To create a header from the :class:`list` again, use the327    :func:`dump_header` function.328329    :param value: a string with a list header.330    :return: :class:`list`331    :rtype: list332    """333    result = []334    for item in _parse_list_header(value):335        if item[:1] == item[-1:] == '"':336            item = unquote_header_value(item[1:-1])337        result.append(item)338    return result339340341# From mitsuhiko/werkzeug (used with permission).342def parse_dict_header(value):343    """Parse lists of key, value pairs as described by RFC 2068 Section 2 and344    convert them into a python dict:345346    >>> d = parse_dict_header('foo="is a fish", bar="as well"')347    >>> type(d) is dict348    True349    >>> sorted(d.items())350    [('bar', 'as well'), ('foo', 'is a fish')]351352    If there is no value for a key it will be `None`:353354    >>> parse_dict_header('key_without_value')355    {'key_without_value': None}356357    To create a header from the :class:`dict` again, use the358    :func:`dump_header` function.359360    :param value: a string with a dict header.361    :return: :class:`dict`362    :rtype: dict363    """364    result = {}365    for item in _parse_list_header(value):366        if '=' not in item:367            result[item] = None368            continue369        name, value = item.split('=', 1)370        if value[:1] == value[-1:] == '"':371            value = unquote_header_value(value[1:-1])372        result[name] = value373    return result374375376# From mitsuhiko/werkzeug (used with permission).377def unquote_header_value(value, is_filename=False):378    r"""Unquotes a header value.  (Reversal of :func:`quote_header_value`).379    This does not use the real unquoting but what browsers are actually380    using for quoting.381382    :param value: the header value to unquote.383    :rtype: str384    """385    if value and value[0] == value[-1] == '"':386        # this is not the real unquoting, but fixing this so that the387        # RFC is met will result in bugs with internet explorer and388        # probably some other browsers as well.  IE for example is389        # uploading files with "C:\foo\bar.txt" as filename390        value = value[1:-1]391392        # if this is a filename and the starting characters look like393        # a UNC path, then just return the value without quotes.  Using the394        # replace sequence below on a UNC path has the effect of turning395        # the leading double slash into a single slash and then396        # _fix_ie_filename() doesn't work correctly.  See #458.397        if not is_filename or value[:2] != '\\\\':398            return value.replace('\\\\', '\\').replace('\\"', '"')399    return value400401402def dict_from_cookiejar(cj):403    """Returns a key/value dictionary from a CookieJar.404405    :param cj: CookieJar object to extract cookies from.406    :rtype: dict407    """408409    cookie_dict = {}410411    for cookie in cj:412        cookie_dict[cookie.name] = cookie.value413414    return cookie_dict415416417def add_dict_to_cookiejar(cj, cookie_dict):418    """Returns a CookieJar from a key/value dictionary.419420    :param cj: CookieJar to insert cookies into.421    :param cookie_dict: Dict of key/values to insert into CookieJar.422    :rtype: CookieJar423    """424425    return cookiejar_from_dict(cookie_dict, cj)426427428def get_encodings_from_content(content):429    """Returns encodings from given content string.430431    :param content: bytestring to extract encodings from.432    """433    warnings.warn((434        'In requests 3.0, get_encodings_from_content will be removed. For '435        'more information, please see the discussion on issue #2266. (This'436        ' warning should only appear once.)'),437        DeprecationWarning)438439    charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I)440    pragma_re = re.compile(r'<meta.*?content=["\']*;?charset=(.+?)["\'>]', flags=re.I)441    xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]')442443    return (charset_re.findall(content) +444            pragma_re.findall(content) +445            xml_re.findall(content))446447448def _parse_content_type_header(header):449    """Returns content type and parameters from given header450451    :param header: string452    :return: tuple containing content type and dictionary of453         parameters454    """455456    tokens = header.split(';')457    content_type, params = tokens[0].strip(), tokens[1:]458    params_dict = {}459    items_to_strip = "\"' "460461    for param in params:462        param = param.strip()463        if param:464            key, value = param, True465            index_of_equals = param.find("=")466            if index_of_equals != -1:467                key = param[:index_of_equals].strip(items_to_strip)468                value = param[index_of_equals + 1:].strip(items_to_strip)469            params_dict[key] = value470    return content_type, params_dict471472473def get_encoding_from_headers(headers):474    """Returns encodings from given HTTP Header Dict.475476    :param headers: dictionary to extract encoding from.477    :rtype: str478    """479480    content_type = headers.get('content-type')481482    if not content_type:483        return None484485    content_type, params = _parse_content_type_header(content_type)486487    if 'charset' in params:488        return params['charset'].strip("'\"")489490    if 'text' in content_type:491        return 'ISO-8859-1'492493494def stream_decode_response_unicode(iterator, r):495    """Stream decodes a iterator."""496497    if r.encoding is None:498        for item in iterator:499            yield item500        return501502    decoder = codecs.getincrementaldecoder(r.encoding)(errors='replace')503    for chunk in iterator:504        rv = decoder.decode(chunk)505        if rv:506            yield rv507    rv = decoder.decode(b'', final=True)508    if rv:509        yield rv510511512def iter_slices(string, slice_length):513    """Iterate over slices of a string."""514    pos = 0515    if slice_length is None or slice_length <= 0:516        slice_length = len(string)517    while pos < len(string):518        yield string[pos:pos + slice_length]519        pos += slice_length520521522def get_unicode_from_response(r):523    """Returns the requested content back in unicode.524525    :param r: Response object to get unicode content from.526527    Tried:528529    1. charset from content-type530    2. fall back and replace all unicode characters531532    :rtype: str533    """534    warnings.warn((535        'In requests 3.0, get_unicode_from_response will be removed. For '536        'more information, please see the discussion on issue #2266. (This'537        ' warning should only appear once.)'),538        DeprecationWarning)539540    tried_encodings = []541542    # Try charset from content-type543    encoding = get_encoding_from_headers(r.headers)544545    if encoding:546        try:547            return str(r.content, encoding)548        except UnicodeError:549            tried_encodings.append(encoding)550551    # Fall back:552    try:553        return str(r.content, encoding, errors='replace')554    except TypeError:555        return r.content556557558# The unreserved URI characters (RFC 3986)559UNRESERVED_SET = frozenset(560    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789-._~")561562563def unquote_unreserved(uri):564    """Un-escape any percent-escape sequences in a URI that are unreserved565    characters. This leaves all reserved, illegal and non-ASCII bytes encoded.566567    :rtype: str568    """569    parts = uri.split('%')570    for i in range(1, len(parts)):571        h = parts[i][0:2]572        if len(h) == 2 and h.isalnum():573            try:574                c = chr(int(h, 16))575            except ValueError:576                raise InvalidURL("Invalid percent-escape sequence: '%s'" % h)577578            if c in UNRESERVED_SET:579                parts[i] = c + parts[i][2:]580            else:581                parts[i] = '%' + parts[i]582        else:583            parts[i] = '%' + parts[i]584    return ''.join(parts)585586587def requote_uri(uri):588    """Re-quote the given URI.589590    This function passes the given URI through an unquote/quote cycle to591    ensure that it is fully and consistently quoted.592593    :rtype: str594    """595    safe_with_percent = "!#$%&'()*+,/:;=?@[]~"596    safe_without_percent = "!#$&'()*+,/:;=?@[]~"597    try:598        # Unquote only the unreserved characters599        # Then quote only illegal characters (do not quote reserved,600        # unreserved, or '%')601        return quote(unquote_unreserved(uri), safe=safe_with_percent)602    except InvalidURL:603        # We couldn't unquote the given URI, so let's try quoting it, but604        # there may be unquoted '%'s in the URI. We need to make sure they're605        # properly quoted so they do not cause issues elsewhere.606        return quote(uri, safe=safe_without_percent)607608609def address_in_network(ip, net):610    """This function allows you to check if an IP belongs to a network subnet611612    Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24613             returns False if ip = 192.168.1.1 and net = 192.168.100.0/24614615    :rtype: bool616    """617    ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0]618    netaddr, bits = net.split('/')619    netmask = struct.unpack('=L', socket.inet_aton(dotted_netmask(int(bits))))[0]620    network = struct.unpack('=L', socket.inet_aton(netaddr))[0] & netmask621    return (ipaddr & netmask) == (network & netmask)622623624def dotted_netmask(mask):625    """Converts mask from /xx format to xxx.xxx.xxx.xxx626627    Example: if mask is 24 function returns 255.255.255.0628629    :rtype: str630    """631    bits = 0xffffffff ^ (1 << 32 - mask) - 1632    return socket.inet_ntoa(struct.pack('>I', bits))633634635def is_ipv4_address(string_ip):636    """637    :rtype: bool638    """639    try:640        socket.inet_aton(string_ip)641    except socket.error:642        return False643    return True644645646def is_valid_cidr(string_network):647    """648    Very simple check of the cidr format in no_proxy variable.649650    :rtype: bool651    """652    if string_network.count('/') == 1:653        try:654            mask = int(string_network.split('/')[1])655        except ValueError:656            return False657658        if mask < 1 or mask > 32:659            return False660661        try:662            socket.inet_aton(string_network.split('/')[0])663        except socket.error:664            return False665    else:666        return False667    return True668669670@contextlib.contextmanager671def set_environ(env_name, value):672    """Set the environment variable 'env_name' to 'value'673674    Save previous value, yield, and then restore the previous value stored in675    the environment variable 'env_name'.676677    If 'value' is None, do nothing"""678    value_changed = value is not None679    if value_changed:680        old_value = os.environ.get(env_name)681        os.environ[env_name] = value682    try:683        yield684    finally:685        if value_changed:686            if old_value is None:687                del os.environ[env_name]688            else:689                os.environ[env_name] = old_value690691692def should_bypass_proxies(url, no_proxy):693    """694    Returns whether we should bypass proxies or not.695696    :rtype: bool697    """698    # Prioritize lowercase environment variables over uppercase699    # to keep a consistent behaviour with other http projects (curl, wget).700    get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper())701702    # First check whether no_proxy is defined. If it is, check that the URL703    # we're getting isn't in the no_proxy list.704    no_proxy_arg = no_proxy705    if no_proxy is None:706        no_proxy = get_proxy('no_proxy')707    parsed = urlparse(url)708709    if no_proxy:710        # We need to check whether we match here. We need to see if we match711        # the end of the hostname, both with and without the port.712        no_proxy = (713            host for host in no_proxy.replace(' ', '').split(',') if host714        )715716        if is_ipv4_address(parsed.hostname):717            for proxy_ip in no_proxy:718                if is_valid_cidr(proxy_ip):719                    if address_in_network(parsed.hostname, proxy_ip):720                        return True721                elif parsed.hostname == proxy_ip:722                    # If no_proxy ip was defined in plain IP notation instead of cidr notation &723                    # matches the IP of the index724                    return True725        else:726            host_with_port = parsed.hostname727            if parsed.port:728                host_with_port += ':{0}'.format(parsed.port)729730            for host in no_proxy:731                if parsed.hostname.endswith(host) or host_with_port.endswith(host):732                    # The URL does match something in no_proxy, so we don't want733                    # to apply the proxies on this URL.734                    return True735736    # If the system proxy settings indicate that this URL should be bypassed,737    # don't proxy.738    # The proxy_bypass function is incredibly buggy on OS X in early versions739    # of Python 2.6, so allow this call to fail. Only catch the specific740    # exceptions we've seen, though: this call failing in other ways can reveal741    # legitimate problems.742    with set_environ('no_proxy', no_proxy_arg):743        try:744            bypass = proxy_bypass(parsed.hostname)745        except (TypeError, socket.gaierror):746            bypass = False747748    if bypass:749        return True750751    return False752753754def get_environ_proxies(url, no_proxy=None):755    """756    Return a dict of environment proxies.757758    :rtype: dict759    """760    if should_bypass_proxies(url, no_proxy=no_proxy):761        return {}762    else:763        return getproxies()764765766def select_proxy(url, proxies):767    """Select a proxy for the url, if applicable.768769    :param url: The url being for the request770    :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs771    """772    proxies = proxies or {}773    urlparts = urlparse(url)774    if urlparts.hostname is None:775        return proxies.get(urlparts.scheme, proxies.get('all'))776777    proxy_keys = [778        urlparts.scheme + '://' + urlparts.hostname,779        urlparts.scheme,780        'all://' + urlparts.hostname,781        'all',782    ]783    proxy = None784    for proxy_key in proxy_keys:785        if proxy_key in proxies:786            proxy = proxies[proxy_key]787            break788789    return proxy790791792def default_user_agent(name="python-requests"):793    """794    Return a string representing the default user agent.795796    :rtype: str797    """798    return '%s/%s' % (name, __version__)799800801def default_headers():802    """803    :rtype: requests.structures.CaseInsensitiveDict804    """805    return CaseInsensitiveDict({806        'User-Agent': default_user_agent(),807        'Accept-Encoding': ', '.join(('gzip', 'deflate')),808        'Accept': '*/*',809        'Connection': 'keep-alive',810    })811812813def parse_header_links(value):814    """Return a list of parsed link headers proxies.815816    i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg"817818    :rtype: list819    """820821    links = []822823    replace_chars = ' \'"'824825    value = value.strip(replace_chars)826    if not value:827        return links828829    for val in re.split(', *<', value):830        try:831            url, params = val.split(';', 1)832        except ValueError:833            url, params = val, ''834835        link = {'url': url.strip('<> \'"')}836837        for param in params.split(';'):838            try:839                key, value = param.split('=')840            except ValueError:841                break842843            link[key.strip(replace_chars)] = value.strip(replace_chars)844845        links.append(link)846847    return links848849850# Null bytes; no need to recreate these on each call to guess_json_utf851_null = '\x00'.encode('ascii')  # encoding to ASCII for Python 3852_null2 = _null * 2853_null3 = _null * 3854855856def guess_json_utf(data):857    """858    :rtype: str859    """860    # JSON always starts with two ASCII characters, so detection is as861    # easy as counting the nulls and from their location and count862    # determine the encoding. Also detect a BOM, if present.863    sample = data[:4]864    if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE):865        return 'utf-32'     # BOM included866    if sample[:3] == codecs.BOM_UTF8:867        return 'utf-8-sig'  # BOM included, MS style (discouraged)868    if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):869        return 'utf-16'     # BOM included870    nullcount = sample.count(_null)871    if nullcount == 0:872        return 'utf-8'873    if nullcount == 2:874        if sample[::2] == _null2:   # 1st and 3rd are null875            return 'utf-16-be'876        if sample[1::2] == _null2:  # 2nd and 4th are null877            return 'utf-16-le'878        # Did not detect 2 valid UTF-16 ascii-range characters879    if nullcount == 3:880        if sample[:3] == _null3:881            return 'utf-32-be'882        if sample[1:] == _null3:883            return 'utf-32-le'884        # Did not detect a valid UTF-32 ascii-range character885    return None886887888def prepend_scheme_if_needed(url, new_scheme):889    """Given a URL that may or may not have a scheme, prepend the given scheme.890    Does not replace a present scheme with the one provided as an argument.891892    :rtype: str893    """894    scheme, netloc, path, params, query, fragment = urlparse(url, new_scheme)895896    # urlparse is a finicky beast, and sometimes decides that there isn't a897    # netloc present. Assume that it's being over-cautious, and switch netloc898    # and path if urlparse decided there was no netloc.899    if not netloc:900        netloc, path = path, netloc901902    return urlunparse((scheme, netloc, path, params, query, fragment))903904905def get_auth_from_url(url):906    """Given a url with authentication components, extract them into a tuple of907    username,password.908909    :rtype: (str,str)910    """911    parsed = urlparse(url)912913    try:914        auth = (unquote(parsed.username), unquote(parsed.password))915    except (AttributeError, TypeError):916        auth = ('', '')917918    return auth919920921# Moved outside of function to avoid recompile every call922_CLEAN_HEADER_REGEX_BYTE = re.compile(b'^\\S[^\\r\\n]*$|^$')923_CLEAN_HEADER_REGEX_STR = re.compile(r'^\S[^\r\n]*$|^$')924925926def check_header_validity(header):927    """Verifies that header value is a string which doesn't contain928    leading whitespace or return characters. This prevents unintended929    header injection.930931    :param header: tuple, in the format (name, value).932    """933    name, value = header934935    if isinstance(value, bytes):936        pat = _CLEAN_HEADER_REGEX_BYTE937    else:938        pat = _CLEAN_HEADER_REGEX_STR939    try:940        if not pat.match(value):941            raise InvalidHeader("Invalid return character or leading space in header: %s" % name)942    except TypeError:943        raise InvalidHeader("Value for header {%s: %s} must be of type str or "944                            "bytes, not %s" % (name, value, type(value)))945946947def urldefragauth(url):948    """949    Given a url remove the fragment and the authentication part.950951    :rtype: str952    """953    scheme, netloc, path, params, query, fragment = urlparse(url)954955    # see func:`prepend_scheme_if_needed`956    if not netloc:957        netloc, path = path, netloc958959    netloc = netloc.rsplit('@', 1)[-1]960961    return urlunparse((scheme, netloc, path, params, query, ''))962963964def rewind_body(prepared_request):965    """Move file pointer back to its recorded starting position966    so it can be read again on redirect.967    """968    body_seek = getattr(prepared_request.body, 'seek', None)969    if body_seek is not None and isinstance(prepared_request._body_position, integer_types):970        try:971            body_seek(prepared_request._body_position)972        except (IOError, OSError):973            raise UnrewindableBodyError("An error occurred when rewinding request "974                                        "body for redirect.")975    else:976        raise UnrewindableBodyError("Unable to rewind request body for redirect.")