"""
requests.sessions
~~~~~~~~~~~~~~~~~

This module provides a Session object to manage and persist settings across
requests (cookies, auth, proxies).
"""

# formerly defined here, reexposed here for backward compatibility

# Preferred clock, based on which one is more accurate on a given system.

"""Determines appropriate setting for a given request, taking into account
    the explicit setting on that request, and the setting in the session. If a
    setting is a dictionary, they will be merged together using `dict_class`
    """

    # Remove keys that are set to None. Extract keys first to avoid altering
    # the dictionary during iteration.
    
"""Properly merges both requests and session hooks.

    This is necessary because when request_hooks == {'response': []}, the
    merge breaks Session hooks entirely.
    """

        # Due to the nature of how requests processes redirects this method will
        # be called at least once upon the original response and at least twice
        # on each subsequent redirect response (if any).
        # If a custom mixin is used to handle this logic, it may be advantageous
        # to cache the redirect location onto the response object as a private
        # attribute.
        
            # Currently the underlying http module on py3 decode headers
            # in latin1, but empirical evidence suggests that latin1 is very
            # rarely used with non-ASCII characters in HTTP headers.
            # It is more likely to get UTF8 header rather than latin1.
            # This causes incorrect handling of UTF8 encoded location headers.
            # To solve this, we re-encode the location in latin1.
            
"""Decide whether Authorization header should be removed when redirecting"""

        # Special case: allow http -> https redirect when using the standard
        # ports. This isn't specified by RFC 7235, but is kept to avoid
        # breaking backwards compatibility with older versions of requests
        # that allowed any redirects on the same host.
        
        # Handle default port usage corresponding to scheme.
        
"""Receives a Response. Returns a generator of Responses or Requests."""

            # Update history and keep track of redirects.
            # resp.history must ignore the original request in this loop
            
            # Release the connection back into the pool.
            
            # Handle redirection without scheme (see: RFC 1808 Section 4)
            
            # Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2)
            
            # Facilitate relative 'location' headers, as allowed by RFC 7231.
            # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')
            # Compliant with RFC3986, we percent encode the url.
            
            # https://github.com/psf/requests/issues/1084
            
                # https://github.com/psf/requests/issues/3490
                
            # Extract any cookies sent on the response to the cookiejar
            # in the new request. Because we've mutated our copied prepared
            # request, use the old one that we haven't yet touched.
            
            # A failed tell() sets `_body_position` to `object()`. This non-None
            # value ensures `rewindable` will be True, allowing us to raise an
            # UnrewindableBodyError, instead of hanging the connection.
            
            # Attempt to rewind consumed file-like object.
            
                # extract redirect url, if any, for the next loop
                
"""When being redirected we may want to strip authentication from the
        request to avoid leaking credentials. This method intelligently removes
        and reapplies authentication where possible to avoid credential loss.
        """

            # If we get redirected to a new host, we should strip out any
            # authentication headers.
            
        # .netrc might have more auth for us on our new host.
        
"""This method re-evaluates the proxy configuration by considering the
        environment variables. If we are redirected to a URL covered by
        NO_PROXY, we strip the proxy configuration. Otherwise, we set missing
        proxy keys for this URL (in case they were stripped by a previous
        redirect).

        This method also replaces the Proxy-Authorization header where
        necessary.

        :rtype: dict
        """

        # urllib3 handles proxy authorization for us in the standard adapter.
        # Avoid appending this to TLS tunneled requests where it may be leaked.
        
"""When being redirected we may want to change the method of the request
        based on certain specs or browser behavior.
        """

        # https://tools.ietf.org/html/rfc7231#section-6.4.4
        
        # Do what the browsers do, despite standards...
        # First, turn 302s into GETs.
        
        # Second, if a POST is responded to with a 301, turn it into a GET.
        # This bizarre behaviour is explained in Issue 1704.
        
"""A Requests session.

    Provides cookie persistence, connection-pooling, and configuration.

    Basic Usage::

      >>> import requests
      >>> s = requests.Session()
      >>> s.get('https://httpbin.org/get')
      <Response [200]>

    Or as a context manager::

      >>> with requests.Session() as s:
      ...     s.get('https://httpbin.org/get')
    """

        #: A case-insensitive dictionary of headers to be sent on each
        #: :class:`Request <Request>` sent from this
        #: :class:`Session <Session>`.
        
        #: Default Authentication tuple or object to attach to
        #: :class:`Request <Request>`.
        
        #: Dictionary mapping protocol or protocol and host to the URL of the proxy
        #: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to
        #: be used on each :class:`Request <Request>`.
        
        #: Dictionary of querystring data to attach to each
        #: :class:`Request <Request>`. The dictionary values may be lists for
        #: representing multivalued query parameters.
        
        #: SSL Verification default.
        #: Defaults to `True`, requiring requests to verify the TLS certificate at the
        #: remote end.
        #: If verify is set to `False`, requests will accept any TLS certificate
        #: presented by the server, and will ignore hostname mismatches and/or
        #: expired certificates, which will make your application vulnerable to
        #: man-in-the-middle (MitM) attacks.
        #: Only set this to `False` for testing.
        
        #: SSL client certificate default, if String, path to ssl client
        #: cert file (.pem). If Tuple, ('cert', 'key') pair.
        
        #: Maximum number of redirects allowed. If the request exceeds this
        #: limit, a :class:`TooManyRedirects` exception is raised.
        #: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is
        #: 30.
        
        #: Trust environment settings for proxy configuration, default
        #: authentication and similar.
        
        #: A CookieJar containing all currently outstanding cookies set on this
        #: session. By default it is a
        #: :class:`RequestsCookieJar <requests.cookies.RequestsCookieJar>`, but
        #: may be any other ``cookielib.CookieJar`` compatible object.
        
"""Constructs a :class:`PreparedRequest <PreparedRequest>` for
        transmission and returns it. The :class:`PreparedRequest` has settings
        merged from the :class:`Request <Request>` instance and those of the
        :class:`Session`.

        :param request: :class:`Request` instance to prepare with this
            session's settings.
        :rtype: requests.PreparedRequest
        """

        # Set environment's basic authentication if not explicitly set.
        
"""Constructs a :class:`Request <Request>`, prepares it and sends it.
        Returns :class:`Response <Response>` object.

        :param method: method for the new :class:`Request` object.
        :param url: URL for the new :class:`Request` object.
        :param params: (optional) Dictionary or bytes to be sent in the query
            string for the :class:`Request`.
        :param data: (optional) Dictionary, list of tuples, bytes, or file-like
            object to send in the body of the :class:`Request`.
        :param json: (optional) json to send in the body of the
            :class:`Request`.
        :param headers: (optional) Dictionary of HTTP Headers to send with the
        :param cookies: (optional) Dict or CookieJar object to send with the
        :param files: (optional) Dictionary of ``'filename': file-like-objects``
            for multipart encoding upload.
        :param auth: (optional) Auth tuple or callable to enable
            Basic/Digest/Custom HTTP Auth.
        :param timeout: (optional) How long to wait for the server to send
            data before giving up, as a float, or a :ref:`(connect timeout,
            read timeout) <timeouts>` tuple.
        :type timeout: float or tuple
        :param allow_redirects: (optional) Set to True by default.
        :type allow_redirects: bool
        :param proxies: (optional) Dictionary mapping protocol or protocol and
            hostname to the URL of the proxy.
        :param stream: (optional) whether to immediately download the response
            content. Defaults to ``False``.
        :param verify: (optional) Either a boolean, in which case it controls whether we verify
            the server's TLS certificate, or a string, in which case it must be a path
            to a CA bundle to use. Defaults to ``True``. When set to
            ``False``, requests will accept any TLS certificate presented by
            the server, and will ignore hostname mismatches and/or expired
            certificates, which will make your application vulnerable to
            man-in-the-middle (MitM) attacks. Setting verify to ``False``
            may be useful during local development or testing.
        :param cert: (optional) if String, path to ssl client cert file (.pem).
            If Tuple, ('cert', 'key') pair.
        :rtype: requests.Response
        """

r"""Sends a GET request. Returns :class:`Response` object.

        :param \*\*kwargs: Optional arguments that ``request`` takes.
        """

r"""Sends a OPTIONS request. Returns :class:`Response` object.

        """

r"""Sends a HEAD request. Returns :class:`Response` object.

        """

r"""Sends a POST request. Returns :class:`Response` object.

        :param json: (optional) json to send in the body of the :class:`Request`.
        """

r"""Sends a PUT request. Returns :class:`Response` object.

        """

r"""Sends a PATCH request. Returns :class:`Response` object.

        """

r"""Sends a DELETE request. Returns :class:`Response` object.

        """

"""Send a given PreparedRequest.

        """

        # Set defaults that the hooks can utilize to ensure they always have
        # the correct parameters to reproduce the previous request.
        
        # It's possible that users might accidentally send a Request object.
        # Guard against that specific failure case.
        
        # Set up variables needed for resolve_redirects and dispatching of hooks
        
        # Total elapsed time of the request (approximately)
        
            # If the hooks create history then we want those cookies too
            
            # Insert the first (original) request at the start
            
        # If redirects aren't being followed, store the response on the Request for Response.next().
        
"""
        Check the environment and merge it with some settings.

        """

        # Gather clues from the surrounding environment.
        
            # Look for requests environment configuration
            # and be compatible with cURL.
            
"""
        Returns the appropriate connection adapter for the given URL.

        :rtype: requests.adapters.BaseAdapter
        """

"""Registers a connection adapter to a prefix.

        Adapters are sorted in descending order by prefix length.
        """

"""
    Returns a :class:`Session` for context-management.

    .. deprecated:: 1.0.0

        This method has been deprecated since version 1.0.0 and is only kept for
        backwards compatibility. New code should use :class:`~requests.sessions.Session`
        to create a session. This may be removed at a future date.

    :rtype: Session
    """

def merge_setting(request_setting, session_setting, dict_class=OrderedDict):

    """Determines appropriate setting for a given request, taking into account

        isinstance(session_setting, Mapping) and isinstance(request_setting, Mapping)

    merged_setting = dict_class(to_key_val_list(session_setting))

    none_keys = [k for (k, v) in merged_setting.items() if v is None]

def merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict):

    if session_hooks is None or session_hooks.get("response") == []:

    if request_hooks is None or request_hooks.get("response") == []:

    return merge_setting(request_hooks, session_hooks, dict_class)

        """Receives a Response. Returns a redirect URI or ``None``"""

        """Decide whether Authorization header should be removed when redirecting"""

        changed_scheme = old_parsed.scheme != new_parsed.scheme

        default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None)

        """Receives a Response. Returns a generator of Responses or Requests."""

                resp.content  # Consume socket so it can be released

            except (ChunkedEncodingError, ContentDecodingError, RuntimeError):

                    f"Exceeded {self.max_redirects} redirects.", response=resp

                url = ":".join([to_native_string(parsed_rurl.scheme), url])

                parsed = parsed._replace(fragment=previous_fragment)

                purged_headers = ("Content-Length", "Content-Type", "Transfer-Encoding")

            extract_cookies_to_jar(prepared_request._cookies, req, resp.raw)

            merge_cookies(prepared_request._cookies, self.cookies)

            prepared_request.prepare_cookies(prepared_request._cookies)

            proxies = self.rebuild_proxies(prepared_request, proxies)

            rewindable = prepared_request._body_position is not None and (

                "Content-Length" in headers or "Transfer-Encoding" in headers

                extract_cookies_to_jar(self.cookies, prepared_request, resp.raw)

        """When being redirected we may want to strip authentication from the

        if "Authorization" in headers and self.should_strip_auth(

        new_auth = get_netrc_auth(url) if self.trust_env else None

        """This method re-evaluates the proxy configuration by considering the

        new_proxies = resolve_proxies(prepared_request, proxies, self.trust_env)

            username, password = get_auth_from_url(new_proxies[scheme])

        if not scheme.startswith('https') and username and password:

            headers["Proxy-Authorization"] = _basic_auth_str(username, password)

        """When being redirected we may want to change the method of the request

        if response.status_code == codes.see_other and method != "HEAD":

        if response.status_code == codes.found and method != "HEAD":

        if response.status_code == codes.moved and method == "POST":

        """Constructs a :class:`PreparedRequest <PreparedRequest>` for

            merge_cookies(RequestsCookieJar(), self.cookies), cookies

                request.headers, self.headers, dict_class=CaseInsensitiveDict

        """Constructs a :class:`Request <Request>`, prepares it and sends it.

        r"""Sends a GET request. Returns :class:`Response` object.

        r"""Sends a OPTIONS request. Returns :class:`Response` object.

        r"""Sends a HEAD request. Returns :class:`Response` object.

        r"""Sends a POST request. Returns :class:`Response` object.

        return self.request("POST", url, data=data, json=json, **kwargs)

        r"""Sends a PUT request. Returns :class:`Response` object.

        r"""Sends a PATCH request. Returns :class:`Response` object.

        r"""Sends a DELETE request. Returns :class:`Response` object.

            kwargs["proxies"] = resolve_proxies(request, self.proxies, self.trust_env)

            raise ValueError("You can only send PreparedRequests.")

                extract_cookies_to_jar(self.cookies, resp.request, resp.raw)

                    self.resolve_redirects(r, request, yield_requests=True, **kwargs)

    def merge_environment_settings(self, url, proxies, stream, verify, cert):

            no_proxy = proxies.get("no_proxy") if proxies is not None else None

            env_proxies = get_environ_proxies(url, no_proxy=no_proxy)

        return {"proxies": proxies, "stream": stream, "verify": verify, "cert": cert}

        raise InvalidSchema(f"No connection adapters were found for {url!r}")

        keys_to_move = [k for k in self.adapters if len(k) < len(prefix)]

        state = {attr: getattr(self, attr, None) for attr in self.__attrs__}