"""
requests.models
~~~~~~~~~~~~~~~

This module contains the primary objects that power Requests.
"""

# Import encoding now, to avoid implicit import later.
# Implicit import within threads may cause LookupError when standard library is in a ZIP,
# such as in Embedded Python. See https://github.com/psf/requests/issues/3578.

#: The set of HTTP status codes that indicate an automatically
#: processable redirect.

"""Encode parameters in a piece of data.

        Will successfully encode parameters when passed as a dict or a list of
        2-tuples. Order is retained if data is a list of 2-tuples but arbitrary
        if parameters are supplied as a dict.
        """

"""Build the body for a multipart/form-data request.

        Will successfully encode files when passed as a dict or a list of
        tuples. Order is retained if data is a list of tuples but arbitrary
        The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype)
        or 4-tuples (filename, fileobj, contentype, custom_headers).
        """

                    # Don't call str() on bytestrings: in Py3 it all goes wrong.
                    
"""Deregister a previously registered hook.
        Returns True if the hook existed, False if not.
        """

"""A user-created :class:`Request <Request>` object.

    Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server.

    :param method: HTTP method to use.
    :param url: URL to send.
    :param headers: dictionary of headers to send.
    :param files: dictionary of {filename: fileobject} files to multipart upload.
    :param data: the body to attach to the request. If a dictionary or
        list of tuples ``[(key, value)]`` is provided, form-encoding will
        take place.
    :param json: json for the body to attach to the request (if files or data is not specified).
    :param params: URL parameters to append to the URL. If a dictionary or
    :param auth: Auth handler or (user, pass) tuple.
    :param cookies: dictionary or CookieJar of cookies to attach to this request.
    :param hooks: dictionary of callback hooks, for internal usage.

    Usage::

      >>> import requests
      >>> req = requests.Request('GET', 'https://httpbin.org/get')
      >>> req.prepare()
      <PreparedRequest [GET]>
    """

"""Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it."""

"""The fully mutable :class:`PreparedRequest <PreparedRequest>` object,
    containing the exact bytes that will be sent to the server.

    Instances are generated from a :class:`Request <Request>` object, and
    should not be instantiated manually; doing so may produce undesirable
    effects.

    Usage::

      >>> r = req.prepare()
      >>> r

      >>> s = requests.Session()
      >>> s.send(r)
      <Response [200]>
    """

        # The `CookieJar` used to create the Cookie header will be stored here
        # after prepare_cookies is called
        
        #: dictionary of callback hooks, for internal usage.
        
        #: integer denoting starting position of a readable file-like body.
        
        # Note that prepare_auth must be last to enable authentication schemes
        # such as OAuth to work on a fully prepared request.

        # This MUST go after prepare_auth. Authenticators could add a hook
        
        #: Accept objects that have string representations.
        #: We're unable to blindly call unicode/str functions
        #: as this will include the bytestring indicator (b'')
        #: on python 3.x.
        #: https://github.com/psf/requests/pull/2238
        
        # Don't do any URL preparation for non-HTTP schemes like `mailto`,
        # `data` etc to work around exceptions from `url_parse`, which
        # handles RFC 3986 only.
        
        # In general, we want to try IDNA encoding the hostname if the string contains
        # non-ASCII characters. This allows users to automatically get the correct IDNA
        # behaviour. For strings containing only ASCII characters, we need to also verify
        # it doesn't start with a wildcard (*), before allowing the unencoded hostname.
        
                # Raise exception on invalid header value.
                
        # Check if file, fo, generator, iterator.
        # If not, run through normal process.

        # Nottin' on you.
        
            # urllib3 requires a bytes-like body. Python 2's json.dumps
            # provides this natively, but Python 3 gives a Unicode string.
            
                # Record the current file position before reading.
                # This will allow us to rewind a file in the event
                # of a redirect.
                
                    # This differentiates from None, allowing us to catch
                    # a failed `tell()` later when trying to rewind the body
                    
            # Add content-type if it wasn't explicitly provided.
            
"""Prepare Content-Length header based on request method and body"""

                # If length exists, set it. Otherwise, we fallback
                # to Transfer-Encoding: chunked.
                
            # Set Content-Length to 0 for methods that can have a body
            # but don't provide one. (i.e. not GET or HEAD)
            
        # If no Auth is explicitly provided, extract it from the URL first.
        
            # Update self to reflect the auth changes.
            
"""Prepares the given HTTP cookie data.

        This function eventually generates a ``Cookie`` header from the
        given cookies using cookielib. Due to cookielib's design, the header
        will not be regenerated if it already exists, meaning this function
        can only be called once for the life of the
        :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls
        to ``prepare_cookies`` will have no actual effect, unless the "Cookie"
        header is removed beforehand.
        """

        # hooks can be passed as None to the prepare method and to this
        # method. To prevent iterating over None, simply use an empty list
        # if hooks is False-y
        
"""The :class:`Response <Response>` object, which contains a
    server's response to an HTTP request.
    """

        #: Integer Code of responded HTTP Status, e.g. 404 or 200.
        
        #: Case-insensitive Dictionary of Response Headers.
        #: For example, ``headers['content-encoding']`` will return the
        #: value of a ``'Content-Encoding'`` response header.
        
        #: File-like object representation of response (for advanced usage).
        #: Use of ``raw`` requires that ``stream=True`` be set on the request.
        #: This requirement does not apply for use internally to Requests.
        
        #: Encoding to decode with when accessing r.text.
        
        #: A list of :class:`Response <Response>` objects from
        #: the history of the Request. Any redirect responses will end
        #: up here. The list is sorted from the oldest to the most recent request.
        
        #: Textual reason of responded HTTP Status, e.g. "Not Found" or "OK".
        
        #: A CookieJar of Cookies the server sent back.
        
        #: The amount of time elapsed between sending the request
        #: and the arrival of the response (as a timedelta).
        #: This property specifically measures the time taken between sending
        #: the first byte of the request and finishing parsing the headers. It
        #: is therefore unaffected by consuming the response content or the
        #: value of the ``stream`` keyword argument.
        
        #: The :class:`PreparedRequest <PreparedRequest>` object to which this
        #: is a response.
        
        # Consume everything; accessing the content attribute makes
        # sure the content has been fully read.
        
"""Returns True if :attr:`status_code` is less than 400.

        This attribute checks if the status code of the response is between
        400 and 600 to see if there was a client error or a server error. If
        the status code, is between 200 and 400, this will return True. This
        is **not** a check to see if the response code is ``200 OK``.
        """

"""Returns True if :attr:`status_code` is less than 400, False if not.

        the status code is between 200 and 400, this will return True. This
        """

"""True if this Response is a well-formed HTTP redirect that could have
        been processed automatically (by :meth:`Session.resolve_redirects`).
        """

"""True if this Response one of the permanent versions of redirect."""

"""Returns a PreparedRequest for the next request in a redirect chain, if there is one."""

"""The apparent encoding, provided by the charset_normalizer or chardet libraries."""

"""Iterates over the response data.  When stream=True is set on the
        request, this avoids reading the content at once into memory for
        large responses.  The chunk size is the number of bytes it should
        read into memory.  This is not necessarily the length of each item
        returned as decoding can take place.

        chunk_size must be of type int or None. A value of None will
        function differently depending on the value of `stream`.
        stream=True will read data as it arrives in whatever size the
        chunks are received. If stream=False, data is returned as
        a single chunk.

        If decode_unicode is True, content will be decoded using the best
        available encoding based on the response.
        """

"""Iterates over the response data, one line at a time.  When
        stream=True is set on the request, this avoids reading the
        content at once into memory for large responses.

        .. note:: This method is not reentrant safe.
        """

        # don't need to release the connection; that's been handled by urllib3
        # since we exhausted the data.
        
"""Content of the response, in unicode.

        If Response.encoding is None, encoding will be guessed using
        ``charset_normalizer`` or ``chardet``.

        The encoding of the response content is determined based solely on HTTP
        headers, following RFC 2616 to the letter. If you can take advantage of
        non-HTTP knowledge to make a better guess at the encoding, you should
        set ``r.encoding`` appropriately before accessing this property.
        """

            # A LookupError is raised if the encoding was not found which could
            # indicate a misspelling or similar mistake.
            #
            # A TypeError can be raised if encoding is None
            #
            # So we try blindly encoding.
            
r"""Returns the json-encoded content of a response, if any.

        :param \*\*kwargs: Optional arguments that ``json.loads`` takes.
        :raises requests.exceptions.JSONDecodeError: If the response body does not
            contain valid json.
        """

            # No encoding set. JSON RFC 4627 section 3 states we should expect
            # UTF-8, -16 or -32. Detect which one to use; If the detection or
            # decoding fails, fall back to `self.text` (using charset_normalizer to make
            # a best guess).
            
                    # Wrong UTF codec detected; usually because it's not UTF-8
                    # but some other 8-bit codec.  This is an RFC violation,
                    # and the server didn't bother to tell us what codec *was*
                    # used.
                    
            # Catch JSON-related errors and raise as requests.JSONDecodeError
            # This aliases json.JSONDecodeError and simplejson.JSONDecodeError
            
            # We attempt to decode utf-8 first because some servers
            # choose to localize their reason strings. If the string
            # isn't utf-8, we fall back to iso-8859-1 for all other
            # encodings. (See PR #3538)
            
"""Releases the connection back to the pool. Once this method has been
        called the underlying ``raw`` object must not be accessed again.

        *Note: Should not normally need to be called explicitly.*
        """

from ._internal_utils import to_native_string, unicode_is_ascii

from .cookies import _copy_cookie_jar, cookiejar_from_dict, get_cookie_header

from .exceptions import JSONDecodeError as RequestsJSONDecodeError

                if isinstance(vs, basestring) or not hasattr(vs, "__iter__"):

                                k.encode("utf-8") if isinstance(k, str) else k,

                                v.encode("utf-8") if isinstance(v, str) else v,

            if isinstance(val, basestring) or not hasattr(val, "__iter__"):

                            v.encode("utf-8") if isinstance(v, str) else v,

            rf = RequestField(name=k, data=fdata, filename=fn, headers=fh)

        body, content_type = encode_multipart_formdata(new_fields)

            raise ValueError(f'Unsupported event specified, with event name "{event}"')

            self.hooks[event].extend(h for h in hook if isinstance(h, Callable))

        """Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it."""

class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):

    """The fully mutable :class:`PreparedRequest <PreparedRequest>` object,

        """Prepares the entire request with the given parameters."""

        p.headers = self.headers.copy() if self.headers is not None else None

            self.method = to_native_string(self.method.upper())

            host = idna.encode(host, uts46=True).decode("utf-8")

            scheme, auth, host, port, path, query, fragment = parse_url(url)

            raise InvalidURL(f"Invalid URL {url!r}: No host supplied")

        url = requote_uri(urlunparse([scheme, netloc, path, None, query, fragment]))

                body = complexjson.dumps(json, allow_nan=False)

                not isinstance(data, (basestring, list, tuple, Mapping)),

            except (TypeError, AttributeError, UnsupportedOperation):

                    "Streamed bodies and files are mutually exclusive."

                self.headers["Content-Length"] = builtin_str(length)

                (body, content_type) = self._encode_files(files, data)

                    if isinstance(data, basestring) or hasattr(data, "read"):

                        content_type = "application/x-www-form-urlencoded"

            if content_type and ("content-type" not in self.headers):

        """Prepare Content-Length header based on request method and body"""

    """The :class:`Response <Response>` object, which contains a

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

        """Returns True if :attr:`status_code` is less than 400.

        """Returns True if :attr:`status_code` is less than 400, False if not.

        """True if this Response is a well-formed HTTP redirect that could have

        return "location" in self.headers and self.status_code in REDIRECT_STATI

        """True if this Response one of the permanent versions of redirect."""

        return "location" in self.headers and self.status_code in (

        """Returns a PreparedRequest for the next request in a redirect chain, if there is one."""

        """The apparent encoding, provided by the charset_normalizer or chardet libraries."""

    def iter_content(self, chunk_size=1, decode_unicode=False):

        """Iterates over the response data.  When stream=True is set on the

                    yield from self.raw.stream(chunk_size, decode_content=True)

        if self._content_consumed and isinstance(self._content, bool):

        elif chunk_size is not None and not isinstance(chunk_size, int):

                f"chunk_size must be an int, it is instead a {type(chunk_size)}."

        chunks = reused_chunks if self._content_consumed else stream_chunks

            chunks = stream_decode_response_unicode(chunks, self)

        self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=False, delimiter=None

        """Iterates over the response data, one line at a time.  When

            chunk_size=chunk_size, decode_unicode=decode_unicode

            if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]:

                raise RuntimeError("The content for this response was already consumed")

                self._content = b"".join(self.iter_content(CONTENT_CHUNK_SIZE)) or b""

            content = str(self.content, encoding, errors="replace")

        r"""Returns the json-encoded content of a response, if any.

        if not self.encoding and self.content and len(self.content) > 3:

                    return complexjson.loads(self.content.decode(encoding), **kwargs)

                    raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)

        """Returns the parsed header links of the response, if any."""

                f"{self.status_code} Client Error: {reason} for url: {self.url}"

                f"{self.status_code} Server Error: {reason} for url: {self.url}"

        """Releases the connection back to the pool. Once this method has been