B
    GZJ             	   @   s  d Z ddlmZ ddlmZmZ ddlmZ ddlmZm	Z	m
Z
mZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZ ddl m!Z!m"Z"m#Z# ddl$m%Z%m&Z& ddl'm(Z(m)Z)m*Z*m+Z+ dd	l,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2 dd
l3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZB ddlCmDZD ddlEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZMmNZN dd aOdd ZPdd ZQdd ZRdd ZSG dd deTZUG dd deTZVG dd deTZWG dd deTZXG dd  d eTZYG d!d" d"eTZZG d#d$ d$eTZ[G d%d& d&eTZ\G d'd( d(eTZ]G d)d* d*eTZ^G d+d, d,eTZ_G d-d. d.eTZ`G d/d0 d0eTZaG d1d2 d2eUeWeXeYeZe_ZbG d3d4 d4e[ebZcG d5d6 d6eVe\e^e`eaZdd7S )8ai  
    werkzeug.wrappers
    ~~~~~~~~~~~~~~~~~

    The wrappers are simple request and response objects which you can
    subclass to do whatever you want them to do.  The request object contains
    the information transmitted by the client (webbrowser) and the response
    object contains all the information sent back to the browser.

    An important detail is that the request object is created with the WSGI
    environ and will act as high-level proxy whereas the response object is an
    actual WSGI application.

    Like everything else in Werkzeug these objects will work correctly with
    unicode data.  Incoming form data parsed by the response object will be
    decoded into an unicode object if possible and if it makes sense.


    :copyright: (c) 2014 by the Werkzeug Team, see AUTHORS for more details.
    :license: BSD, see LICENSE for more details.
    )update_wrapper)datetime	timedelta)warn)HTTP_STATUS_CODESparse_accept_headerparse_cache_control_headerparse_etags
parse_dategenerate_etagis_resource_modifiedunquote_etag
quote_etagparse_set_headerparse_authorization_headerparse_www_authenticate_headerremove_entity_headersparse_options_headerdump_options_header	http_dateparse_if_range_headerparse_cookiedump_cookieparse_range_headerparse_content_range_headerdump_header	parse_agedump_age)
url_decode
iri_to_uriurl_join)FormDataParserdefault_stream_factory)cached_propertyenviron_propertyheader_propertyget_content_type)get_current_urlget_hostClosingIteratorget_input_streamget_content_length_RangeWrapper)	MultiDictCombinedMultiDictHeadersEnvironHeadersImmutableMultiDictImmutableTypeConversionDictImmutableList
MIMEAcceptCharsetAcceptLanguageAcceptResponseCacheControlRequestCacheControlCallbackDictContentRangeiter_multi_items)_get_environ)	to_bytesstring_types	text_typeinteger_typeswsgi_decoding_dancewsgi_get_bytes
to_unicode	to_nativeBytesIOc              G   s   ddl ma t|  S )zsThis function replaces itself to ensure that the test module is not
    imported unless required.  DO NOT USE!
    r   )run_wsgi_app)werkzeug.testrF   _run_wsgi_app)args rJ   0lib/python3.7/site-packages/werkzeug/wrappers.pyrH   5   s    rH   c             C   s   t | trttddd dS )znHelper for the response objects to check if the iterable returned
    to the WSGI server is not a string.
    zresponse iterable was set to a string.  This appears to work but means that the server will send the data to the client char, by char.  This is almost never intended behavior, use response.data to assign strings to the response object.   )
stacklevelN)
isinstancer>   r   Warning)iterablerJ   rJ   rK   _warn_if_string>   s    
rQ   c             C   s   | j rtdd S )NzeA shallow request tried to consume form data.  If you really want to do that, set `shallow` to False.)shallowRuntimeError)requestrJ   rJ   rK   _assert_not_shallowJ   s    rU   c             c   s0   x*| D ]"}t |tr"||V  q|V  qW d S )N)rN   r?   encode)rP   charsetitemrJ   rJ   rK   _iter_encodedQ   s    

rY   c             C   s6   | dkrdS | dkrdS t | tr*t| S tdd S )NTbytesFZnonezInvalid accept_ranges value)rN   r?   rD   
ValueError)accept_rangesrJ   rJ   rK   _clean_accept_rangesY   s    
r]   c               @   s   e Zd ZdZdZdZdZdZeZ	e
ZeZeZdZdZdaddZd	d
 Zedd Zedd Zedd ZdbddZedd Zdd Zdd Zdd Zdd Zdd Zdd  Z e!d!d" Z"e#d#d$Z$e!d%d& Z%e!d'd( Z&dcd)d*Z'e!d+d, Z(e!d-d. Z)e!d/d0 Z*e!d1d2 Z+e!d3d4 Z,e!d5d6 Z-e!d7d8 Z.e!d9d: Z/e!d;d< Z0e!d=d> Z1e!d?d@ Z2e!dAdB Z3e!dCdD Z4e#dEdFde5dGdHZ6e#dIdJddKdL dMdHZ7e!dNdO Z8edPdQ Z9e#dRdSdTZ:e#dUdVdTZ;edWdX Z<edYdL dZdTZ=e#d[d\dTZ>e#d]d^dTZ?e#d_d`dTZ@dS )dBaseRequesta  Very basic request object.  This does not implement advanced stuff like
    entity tag parsing or cache controls.  The request object is created with
    the WSGI environment as first argument and will add itself to the WSGI
    environment as ``'werkzeug.request'`` unless it's created with
    `populate_request` set to False.

    There are a couple of mixins available that add additional functionality
    to the request object, there is also a class called `Request` which
    subclasses `BaseRequest` and all the important mixins.

    It's a good idea to create a custom subclass of the :class:`BaseRequest`
    and add missing functionality either via mixins or direct implementation.
    Here an example for such subclasses::

        from werkzeug.wrappers import BaseRequest, ETagRequestMixin

        class Request(BaseRequest, ETagRequestMixin):
            pass

    Request objects are **read only**.  As of 0.5 modifications are not
    allowed in any place.  Unlike the lower level parsing functions the
    request object will use immutable objects everywhere possible.

    Per default the request object will assume all the text data is `utf-8`
    encoded.  Please refer to `the unicode chapter <unicode.txt>`_ for more
    details about customizing the behavior.

    Per default the request object will be added to the WSGI
    environment as `werkzeug.request` to support the debugging system.
    If you don't want that, set `populate_request` to `False`.

    If `shallow` is `True` the environment is initialized as shallow
    object around the environ.  Every operation that would modify the
    environ in any way (such as consuming form data) raises an exception
    unless the `shallow` attribute is explicitly set to `False`.  This
    is useful for middlewares where you don't want to consume the form
    data by accident.  A shallow request is not populated to the WSGI
    environment.

    .. versionchanged:: 0.5
       read-only mode was enforced by using immutables classes for all
       data.
    zutf-8replaceNFTc             C   s"   || _ |r|s| | j d< || _d S )Nzwerkzeug.request)environrR   )selfr`   Zpopulate_requestrR   rJ   rJ   rK   __init__   s    
zBaseRequest.__init__c             C   sf   g }y,| dt| j| j  | d| j  W n tk
rN   | d Y nX d| jjd|f S )Nz'%s'z[%s]z(invalid WSGI environ)z<%s %s> )	appendrD   urlurl_charsetmethod	Exception	__class____name__join)ra   rI   rJ   rJ   rK   __repr__   s    zBaseRequest.__repr__c             C   s   | j S )zThe charset that is assumed for URLs.  Defaults to the value
        of :attr:`charset`.

        .. versionadded:: 0.6
        )rW   )ra   rJ   rJ   rK   rf      s    zBaseRequest.url_charsetc             O   sF   ddl m} |d| j}||d< |||}z
|| S |  X dS )a  Create a new request object based on the values provided.  If
        environ is given missing values are filled from there.  This method is
        useful for small scripts when you need to simulate a request from an URL.
        Do not use this method for unittesting, there is a full featured client
        object (:class:`Client`) that allows to create multipart requests,
        support for cookies etc.

        This accepts the same options as the
        :class:`~werkzeug.test.EnvironBuilder`.

        .. versionchanged:: 0.5
           This method now accepts the same arguments as
           :class:`~werkzeug.test.EnvironBuilder`.  Because of this the
           `environ` parameter is now called `environ_overrides`.

        :return: request object
        r   )EnvironBuilderrW   N)rG   rm   poprW   Zget_requestclose)clsrI   kwargsrm   rW   ZbuilderrJ   rJ   rK   from_values   s    

zBaseRequest.from_valuesc                s&   ddl m   fdd}t|S )a_  Decorate a function as responder that accepts the request as first
        argument.  This works like the :func:`responder` decorator but the
        function is passed the request object as first argument and the
        request object will be closed automatically::

            @Request.application
            def my_wsgi_app(request):
                return Response('Hello World!')

        As of Werkzeug 0.14 HTTP exceptions are automatically caught and
        converted to responses instead of failing.

        :param f: the WSGI callable to decorate
        :return: a new WSGI callable
        r   )HTTPExceptionc                 sx   | d }|^ y| d d |f  }W n0  k
r\ } z| | d }W d d }~X Y nX || dd   S Q R X d S )N)Zget_response)rI   rT   Zrespe)rs   rp   frJ   rK   application0  s     z,BaseRequest.application.<locals>.application)werkzeug.exceptionsrs   r   )rp   rv   rw   rJ   )rs   rp   rv   rK   rw     s    	zBaseRequest.applicationc             C   s   t ||||dS )a  Called to get a stream for the file upload.

        This must provide a file-like class with `read()`, `readline()`
        and `seek()` methods that is both writeable and readable.

        The default implementation returns a temporary file if the total
        content length is higher than 500KB.  Because many browsers do not
        provide a content length for the files only the total content
        length matters.

        :param total_content_length: the total content length of all the
                                     data in the request combined.  This value
                                     is guaranteed to be there.
        :param content_type: the mimetype of the uploaded file.
        :param filename: the filename of the uploaded file.  May be `None`.
        :param content_length: the length of this file.  This value is usually
                               not provided because webbrowsers do not provide
                               this value.
        )total_content_lengthcontent_typefilenamecontent_length)r"   )ra   ry   rz   r{   r|   rJ   rJ   rK   _get_file_stream;  s
    zBaseRequest._get_file_streamc             C   s   t | jdS )zReturns True if the request method carries content.  As of
        Werkzeug 0.9 this will be the case if a content type is transmitted.

        .. versionadded:: 0.8
        CONTENT_TYPE)boolr`   get)ra   rJ   rJ   rK   want_form_data_parsedV  s    z!BaseRequest.want_form_data_parsedc             C   s    |  | j| j| j| j| j| jS )zCreates the form data parser. Instantiates the
        :attr:`form_data_parser_class` with some parameters.

        .. versionadded:: 0.8
        )form_data_parser_classr}   rW   encoding_errorsmax_form_memory_sizemax_content_lengthparameter_storage_class)ra   rJ   rJ   rK   make_form_data_parser_  s    z!BaseRequest.make_form_data_parserc             C   s   d| j krdS t|  | jr^| jdd}t| j}t|\}}|  }|| 	 |||}n| j
|  |  f}| j }|\|d< |d< |d< dS )au  Method used internally to retrieve submitted data.  After calling
        this sets `form` and `files` on the request object to multi dicts
        filled with the incoming form data.  As a matter of fact the input
        stream will be empty afterwards.  You can also call this method to
        force the parsing of the form data.

        .. versionadded:: 0.8
        formNr~    streamfiles)__dict__rU   r   r`   r   r+   r   r   parse_get_stream_for_parsingr   r   )ra   rz   r|   mimetypeZoptionsparserdatadrJ   rJ   rK   _load_form_datal  s    





zBaseRequest._load_form_datac             C   s"   t | dd}|dk	rt|S | jS )zThis is the same as accessing :attr:`stream` with the difference
        that if it finds cached data from calling :meth:`get_data` first it
        will create a new stream out of the cached data.

        .. versionadded:: 0.9.3
        _cached_dataN)getattrrE   r   )ra   Zcached_datarJ   rJ   rK   r     s    z#BaseRequest._get_stream_for_parsingc             C   s2   | j d}x t|pdD ]\}}|  qW dS )zCloses associated resources of this request object.  This
        closes all file handles explicitly.  You can also use the request
        object in a with statement which will automatically close it.

        .. versionadded:: 0.9
        r   rJ   N)r   r   r;   ro   )ra   r   keyvaluerJ   rJ   rK   ro     s    zBaseRequest.closec             C   s   | S )NrJ   )ra   rJ   rJ   rK   	__enter__  s    zBaseRequest.__enter__c             C   s   |    d S )N)ro   )ra   exc_type	exc_valuetbrJ   rJ   rK   __exit__  s    zBaseRequest.__exit__c             C   s   t |  t| jS )a7  
        If the incoming form data was not encoded with a known mimetype
        the data is stored unmodified in this stream for consumption.  Most
        of the time it is a better idea to use :attr:`data` which will give
        you that data as a string.  The stream only returns the data once.

        Unlike :attr:`input_stream` this stream is properly guarded that you
        can't accidentally read past the length of the input.  Werkzeug will
        internally always refer to this stream to read data which makes it
        possible to wrap this object with a stream that does filtering.

        .. versionchanged:: 0.9
           This stream is now always available but might be consumed by the
           form parser later on.  Previously the stream was only set if no
           parsing happened.
        )rU   r*   r`   )ra   rJ   rJ   rK   r     s    zBaseRequest.streamz
wsgi.inputz
    The WSGI input stream.

    In general it's a bad idea to use this one because you can easily read past
    the boundary.  Use the :attr:`stream` instead.
    c             C   s$   t t| jdd| j| j| jdS )a  The parsed URL parameters (the part in the URL after the question
        mark).

        By default an
        :class:`~werkzeug.datastructures.ImmutableMultiDict`
        is returned from this function.  This can be changed by setting
        :attr:`parameter_storage_class` to a different type.  This might
        be necessary if the order of the form data is important.
        QUERY_STRINGr   )errorsrp   )r   rB   r`   r   rf   r   r   )ra   rJ   rJ   rK   rI     s    zBaseRequest.argsc             C   s   | j rtd| jddS )z
        Contains the incoming request data as string in case it came with
        a mimetype Werkzeug does not handle.
        zdata descriptor is disabledT)parse_form_data)disable_data_descriptorAttributeErrorget_data)ra   rJ   rJ   rK   r     s    zBaseRequest.datac             C   sL   t | dd}|dkr4|r |   | j }|r4|| _|rH|| j| j}|S )a  This reads the buffered incoming data from the client into one
        bytestring.  By default this is cached but that behavior can be
        changed by setting `cache` to `False`.

        Usually it's a bad idea to call this method without checking the
        content length first as a client could send dozens of megabytes or more
        to cause memory problems on the server.

        Note that if the form data was already parsed this method will not
        return anything as form data parsing does not cache the data like
        this method does.  To implicitly invoke form data parsing function
        set `parse_form_data` to `True`.  When this is done the return value
        of this method will be an empty string if the form parser handles
        the data.  This generally is not necessary as if the whole data is
        cached (which is the default) the form parser will used the cached
        data to parse the form data.  Please be generally aware of checking
        the content length first in any case before calling this method
        to avoid exhausting server memory.

        If `as_text` is set to `True` the return value will be a decoded
        unicode string.

        .. versionadded:: 0.9
        r   N)r   r   r   readr   decoderW   r   )ra   cacheas_textr   rvrJ   rJ   rK   r     s    
zBaseRequest.get_datac             C   s   |    | jS )aD  The form parameters.  By default an
        :class:`~werkzeug.datastructures.ImmutableMultiDict`
        is returned from this function.  This can be changed by setting
        :attr:`parameter_storage_class` to a different type.  This might
        be necessary if the order of the form data is important.

        Please keep in mind that file uploads will not end up here, but instead
        in the :attr:`files` attribute.

        .. versionchanged:: 0.9

            Previous to Werkzeug 0.9 this would only contain form data for POST
            and PUT requests.
        )r   r   )ra   rJ   rJ   rK   r   	  s    zBaseRequest.formc             C   s>   g }x0| j | jfD ] }t|ts(t|}|| qW t|S )ziA :class:`werkzeug.datastructures.CombinedMultiDict` that combines
        :attr:`args` and :attr:`form`.)rI   r   rN   r-   rd   r.   )ra   rI   r   rJ   rJ   rK   values  s    
zBaseRequest.valuesc             C   s   |    | jS )a  :class:`~werkzeug.datastructures.MultiDict` object containing
        all uploaded files.  Each key in :attr:`files` is the name from the
        ``<input type="file" name="">``.  Each value in :attr:`files` is a
        Werkzeug :class:`~werkzeug.datastructures.FileStorage` object.

        It basically behaves like a standard file object you know from Python,
        with the difference that it also has a
        :meth:`~werkzeug.datastructures.FileStorage.save` function that can
        store the file on the filesystem.

        Note that :attr:`files` will only contain data if the request method was
        POST, PUT or PATCH and the ``<form>`` that posted to the request had
        ``enctype="multipart/form-data"``.  It will be empty otherwise.

        See the :class:`~werkzeug.datastructures.MultiDict` /
        :class:`~werkzeug.datastructures.FileStorage` documentation for
        more details about the used data structure.
        )r   r   )ra   rJ   rJ   rK   r   '  s    zBaseRequest.filesc             C   s   t | j| j| j| jdS )zVA :class:`dict` with the contents of all cookies transmitted with
        the request.)rp   )r   r`   rW   r   dict_storage_class)ra   rJ   rJ   rK   cookies>  s    
zBaseRequest.cookiesc             C   s
   t | jS )zqThe headers from the WSGI environ as immutable
        :class:`~werkzeug.datastructures.EnvironHeaders`.
        )r0   r`   )ra   rJ   rJ   rK   headersF  s    zBaseRequest.headersc             C   s*   t | jdpd| j| j}d|d S )zRequested path as unicode.  This works a bit like the regular path
        info in the WSGI environment but will always include a leading slash,
        even if the URL root is accessed.
        Z	PATH_INFOr   /)rA   r`   r   rW   r   lstrip)ra   raw_pathrJ   rJ   rK   pathM  s    zBaseRequest.pathc             C   s   | j d t| j| j S )z6Requested path as unicode, including the query string.?)r   rC   query_stringrf   )ra   rJ   rJ   rK   	full_pathW  s    zBaseRequest.full_pathc             C   s&   t | jdpd| j| j}|dS )z7The root path of the script without the trailing slash.ZSCRIPT_NAMEr   r   )rA   r`   r   rW   r   rstrip)ra   r   rJ   rJ   rK   script_root\  s    zBaseRequest.script_rootc             C   s   t | j| jdS )zWThe reconstructed current URL as IRI.
        See also: :attr:`trusted_hosts`.
        )trusted_hosts)r'   r`   r   )ra   rJ   rJ   rK   re   c  s    zBaseRequest.urlc             C   s   t | jd| jdS )z^Like :attr:`url` but without the querystring
        See also: :attr:`trusted_hosts`.
        T)Zstrip_querystringr   )r'   r`   r   )ra   rJ   rJ   rK   base_urlk  s    zBaseRequest.base_urlc             C   s   t | jd| jdS )zThe full URL root (with hostname), this is the application
        root as IRI.
        See also: :attr:`trusted_hosts`.
        T)r   )r'   r`   r   )ra   rJ   rJ   rK   url_roots  s    zBaseRequest.url_rootc             C   s   t | jd| jdS )zSJust the host with scheme as IRI.
        See also: :attr:`trusted_hosts`.
        T)Z	host_onlyr   )r'   r`   r   )ra   rJ   rJ   rK   host_url|  s    zBaseRequest.host_urlc             C   s   t | j| jdS )z`Just the host including the port if available.
        See also: :attr:`trusted_hosts`.
        )r   )r(   r`   r   )ra   rJ   rJ   rK   host  s    zBaseRequest.hostr   r   z%The URL parameters as raw bytestring.)Z	read_onlyZ	load_funcdocREQUEST_METHODGETc             C   s   |   S )N)upper)xrJ   rJ   rK   <lambda>  s    zBaseRequest.<lambda>z:The request method. (For example ``'GET'`` or ``'POST'``).c             C   sR   d| j kr.| j d d}| dd |D S d| j krJ| | j d gS |  S )z}If a forwarded header exists this is a list of all ip addresses
        from the client ip to the last proxy server.
        ZHTTP_X_FORWARDED_FOR,c             S   s   g | ]}|  qS rJ   )strip).0r   rJ   rJ   rK   
<listcomp>  s    z,BaseRequest.access_route.<locals>.<listcomp>REMOTE_ADDR)r`   splitlist_storage_class)ra   ZaddrrJ   rJ   rK   access_route  s    

zBaseRequest.access_routec             C   s   | j dS )z!The remote address of the client.r   )r`   r   )ra   rJ   rJ   rK   remote_addr  s    zBaseRequest.remote_addrZREMOTE_USERz
        If the server supports user authentication, and the script is
        protected, this attribute contains the username the user has
        authenticated as.)r   zwsgi.url_schemezC
        URL scheme (http or https).

        .. versionadded:: 0.7c             C   s&   t tddd | jdd dkS )a  True if the request was triggered via a JavaScript XMLHttpRequest.
        This only works with libraries that support the ``X-Requested-With``
        header and set it to "XMLHttpRequest".  Libraries that do that are
        prototype, jQuery and Mochikit and probably some more.

        .. deprecated:: 0.13
            ``X-Requested-With`` is not standard and is unreliable.
        zrRequest.is_xhr is deprecated. Given that the X-Requested-With header is not a part of any spec, it is not reliablerL   )rM   ZHTTP_X_REQUESTED_WITHr   Zxmlhttprequest)r   DeprecationWarningr`   r   lower)ra   rJ   rJ   rK   is_xhr  s    

zBaseRequest.is_xhrc             C   s   | j d dkS )Nzwsgi.url_schemeZhttps)r`   )r   rJ   rJ   rK   r     s    z `True` if the request is secure.zwsgi.multithreadzd
        boolean that is `True` if the application is served by
        a multithreaded WSGI server.zwsgi.multiprocesszu
        boolean that is `True` if the application is served by
        a WSGI server that spawns multiple processes.zwsgi.run_oncez
        boolean that is `True` if the application will be executed only
        once in a process lifetime.  This is the case for CGI for example,
        but it's not guaranteed that the execution only happens one time.)TF)NN)TFF)Arj   
__module____qualname____doc__rW   r   r   r   r1   r   r3   r   r2   r   r!   r   r   r   rb   rl   propertyrf   classmethodrr   rw   r}   r   r   r   r   ro   r   r   r#   r   r$   Zinput_streamrI   r   r   r   r   r   r   r   r   r   r   re   r   r   r   r   rB   r   rg   r   r   Zremote_userZschemer   Z	is_secureZis_multithreadZis_multiprocessZis_run_oncerJ   rJ   rJ   rK   r^   c   s   ,
	# 
	
$
	
r^   c               @   sT  e Zd ZdZdZdZdZdZdZdZ	dZ
dEd	d
Zdd Zdd ZedFddZedGddZdd Zdd ZeeeddZ[[dd Zdd ZeeeddZ[[dHddZd d! Zeeed"dZd#d$ ZdId%d&Zd'd( Zd)d* ZdJd-d.ZdKd/d0Z ed1d2 Z!ed3d4 Z"d5d6 Z#d7d8 Z$d9d: Z%d;d< Z&d=d> Z'd?d@ Z(dAdB Z)dCdD Z*dS )LBaseResponsea  Base response class.  The most important fact about a response object
    is that it's a regular WSGI application.  It's initialized with a couple
    of response parameters (headers, body, status code etc.) and will start a
    valid WSGI response when called with the environ and start response
    callable.

    Because it's a WSGI application itself processing usually ends before the
    actual response is sent to the server.  This helps debugging systems
    because they can catch all the exceptions before responses are started.

    Here a small example WSGI application that takes advantage of the
    response objects::

        from werkzeug.wrappers import BaseResponse as Response

        def index():
            return Response('Index page')

        def application(environ, start_response):
            path = environ.get('PATH_INFO') or '/'
            if path == '/':
                response = index()
            else:
                response = Response('Not Found', status=404)
            return response(environ, start_response)

    Like :class:`BaseRequest` which object is lacking a lot of functionality
    implemented in mixins.  This gives you a better control about the actual
    API of your response objects, so you can create subclasses and add custom
    functionality.  A full featured response object is available as
    :class:`Response` which implements a couple of useful mixins.

    To enforce a new type of already existing responses you can use the
    :meth:`force_type` method.  This is useful if you're working with different
    subclasses of response objects and you want to post process them with a
    known interface.

    Per default the response object will assume all the text data is `utf-8`
    encoded.  Please refer to `the unicode chapter <unicode.txt>`_ for more
    details about customizing the behavior.

    Response can be any kind of iterable or string.  If it's a string it's
    considered being an iterable with one item which is the string passed.
    Headers can be a list of tuples or a
    :class:`~werkzeug.datastructures.Headers` object.

    Special note for `mimetype` and `content_type`:  For most mime types
    `mimetype` and `content_type` work the same, the difference affects
    only 'text' mimetypes.  If the mimetype passed with `mimetype` is a
    mimetype starting with `text/`, the charset parameter of the response
    object is appended to it.  In contrast the `content_type` parameter is
    always added as header unmodified.

    .. versionchanged:: 0.5
       the `direct_passthrough` parameter was added.

    :param response: a string or response iterable.
    :param status: a string with a status or an integer with the status code.
    :param headers: a list of headers or a
                    :class:`~werkzeug.datastructures.Headers` object.
    :param mimetype: the mimetype for the response.  See notice above.
    :param content_type: the content type for the response.  See notice above.
    :param direct_passthrough: if set to `True` :meth:`iter_encoded` is not
                               called before iteration which makes it
                               possible to pass special iterators through
                               unchanged (see :func:`wrap_file` for more
                               details.)
    zutf-8   z
text/plainTi  NFc             C   s   t |tr|| _n|s t | _n
t|| _|d krb|d krJd| jkrJ| j}|d k	r^t|| j}|}|d k	rt|| jd< |d kr| j}t |tr|| _n|| _	|| _
g | _|d krg | _n"t |tttfr| | n|| _d S )Nzcontent-typezContent-Type)rN   r/   r   default_mimetyper&   rW   default_statusr@   status_codestatusdirect_passthrough	_on_closeresponser?   rZ   	bytearrayset_data)ra   r   r   r   r   rz   r   rJ   rJ   rK   rb   >  s2    




zBaseResponse.__init__c             C   s   | j | |S )a  Adds a function to the internal list of functions that should
        be called as part of closing down the response.  Since 0.7 this
        function also returns the function that was passed so that this
        can be used as a decorator.

        .. versionadded:: 0.6
        )r   rd   )ra   funcrJ   rJ   rK   call_on_closeb  s    zBaseResponse.call_on_closec             C   s@   | j rdttt|   }n| jr(dnd}d| jj|| jf S )Nz%d bytesZstreamedzlikely-streamedz<%s %s [%s]>)	is_sequencesummapleniter_encodedis_streamedri   rj   r   )ra   Z	body_inforJ   rJ   rK   rl   m  s    zBaseResponse.__repr__c             C   s2   t |ts(|dkrtdtt|| }| |_|S )a  Enforce that the WSGI response is a response object of the current
        type.  Werkzeug will use the :class:`BaseResponse` internally in many
        situations like the exceptions.  If you call :meth:`get_response` on an
        exception you will get back a regular :class:`BaseResponse` object, even
        if you are using a custom subclass.

        This method can enforce a given response type, and it will also
        convert arbitrary WSGI callables into response objects if an environ
        is provided::

            # convert a Werkzeug response object into an instance of the
            # MyResponseClass subclass.
            response = MyResponseClass.force_type(response)

            # convert any WSGI application into a response object
            response = MyResponseClass.force_type(response, environ)

        This is especially useful if you want to post-process responses in
        the main dispatcher and use functionality provided by your subclass.

        Keep in mind that this will modify response objects in place if
        possible!

        :param response: a response object or wsgi application.
        :param environ: a WSGI environment object.
        :return: a response object.
        NzHcannot convert WSGI application into response objects without an environ)rN   r   	TypeErrorrH   ri   )rp   r   r`   rJ   rJ   rK   
force_typex  s    
zBaseResponse.force_typec             C   s   | t ||| S )a  Create a new response object from an application output.  This
        works best if you pass it an application that returns a generator all
        the time.  Sometimes applications may use the `write()` callable
        returned by the `start_response` function.  This tries to resolve such
        edge cases automatically.  But if you don't get the expected output
        you should set `buffered` to `True` which enforces buffering.

        :param app: the WSGI application to execute.
        :param environ: the WSGI environment to execute against.
        :param buffered: set to `True` to enforce buffering.
        :return: a response object.
        )rH   )rp   Zappr`   ZbufferedrJ   rJ   rK   from_app  s    zBaseResponse.from_appc             C   s   | j S )N)_status_code)ra   rJ   rJ   rK   _get_status_code  s    zBaseResponse._get_status_codec             C   sD   || _ yd|t|  f | _W n tk
r>   d| | _Y nX d S )Nz%d %sz
%d UNKNOWN)r   r   r   _statusKeyError)ra   coderJ   rJ   rK   _set_status_code  s
    zBaseResponse._set_status_codezThe HTTP Status code as number)r   c             C   s   | j S )N)r   )ra   rJ   rJ   rK   _get_status  s    zBaseResponse._get_statusc             C   s   yt || _W n tk
r*   tdY nX yt| jd dd | _W n@ tk
rn   d| _d| j | _Y n tk
r   tdY nX d S )NzInvalid status argument   r   z0 %szEmpty status argument)	rD   r   r   r   intr   r   r[   
IndexError)ra   r   rJ   rJ   rK   _set_status  s    zBaseResponse._set_statuszThe HTTP Status codec             C   s*   |    d|  }|r&|| j}|S )a  The string representation of the request body.  Whenever you call
        this property the request iterable is encoded and flattened.  This
        can lead to unwanted behavior if you stream big data.

        This behavior can be disabled by setting
        :attr:`implicit_sequence_conversion` to `False`.

        If `as_text` is set to `True` the return value will be a decoded
        unicode string.

        .. versionadded:: 0.9
            )_ensure_sequencerk   r   r   rW   )ra   r   r   rJ   rJ   rK   r     s
    zBaseResponse.get_datac             C   sD   t |tr|| j}nt|}|g| _| jr@tt|| j	d< dS )zSets a new string as response.  The value set must either by a
        unicode or bytestring.  If a unicode string is set it's encoded
        automatically to the charset of the response (utf-8 by default).

        .. versionadded:: 0.9
        zContent-LengthN)
rN   r?   rV   rW   rZ   r    automatically_set_content_lengthstrr   r   )ra   r   rJ   rJ   rK   r     s    	
zBaseResponse.set_dataz
        A descriptor that calls :meth:`get_data` and :meth:`set_data`.  This
        should not be used and will eventually get deprecated.
        c             C   s8   y|    W n tk
r    dS X tdd |  D S )z<Returns the content length if available or `None` otherwise.Nc             s   s   | ]}t |V  qd S )N)r   )r   r   rJ   rJ   rK   	<genexpr>  s    z8BaseResponse.calculate_content_length.<locals>.<genexpr>)r   rS   r   r   )ra   rJ   rJ   rK   calculate_content_length  s
    z%BaseResponse.calculate_content_lengthc             C   sN   | j r&|r"t| jts"t| j| _dS | jr4td| jsBtd|   dS )zThis method can be called by methods that need a sequence.  If
        `mutable` is true, it will also ensure that the response sequence
        is a standard Python list.

        .. versionadded:: 0.6
        Nz]Attempted implicit sequence conversion but the response object is in direct passthrough mode.zThe response object required the iterable to be a sequence, but the implicit conversion was disabled.  Call make_sequence() yourself.)r   rN   r   listr   rS   implicit_sequence_conversionmake_sequence)ra   mutablerJ   rJ   rK   r     s    zBaseResponse._ensure_sequencec             C   s8   | j s4t| jdd}t|  | _|dk	r4| | dS )aC  Converts the response iterator in a list.  By default this happens
        automatically if required.  If `implicit_sequence_conversion` is
        disabled, this method is not automatically called and some properties
        might raise exceptions.  This also encodes all the items.

        .. versionadded:: 0.6
        ro   N)r   r   r   r   r   r   )ra   ro   rJ   rJ   rK   r     s
    zBaseResponse.make_sequencec             C   s   t | j t| j| jS )a  Iter the response encoded with the encoding of the response.
        If the response object is invoked as WSGI application the return
        value of this method is used as application iterator unless
        :attr:`direct_passthrough` was activated.
        )rQ   r   rY   rW   )ra   rJ   rJ   rK   r   &  s    
zBaseResponse.iter_encodedr   r   c
       
      C   s0   | j dt||||||||| j| j|	d dS )aX  Sets a cookie. The parameters are the same as in the cookie `Morsel`
        object in the Python standard library but it accepts unicode data, too.

        A warning is raised if the size of the cookie header exceeds
        :attr:`max_cookie_size`, but the header will still be set.

        :param key: the key (name) of the cookie to be set.
        :param value: the value of the cookie.
        :param max_age: should be a number of seconds, or `None` (default) if
                        the cookie should last only as long as the client's
                        browser session.
        :param expires: should be a `datetime` object or UNIX timestamp.
        :param path: limits the cookie to a given path, per default it will
                     span the whole domain.
        :param domain: if you want to set a cross-domain cookie.  For example,
                       ``domain=".example.com"`` will set a cookie that is
                       readable by the domain ``www.example.com``,
                       ``foo.example.com`` etc.  Otherwise, a cookie will only
                       be readable by the domain that set it.
        :param secure: If `True`, the cookie will only be available via HTTPS
        :param httponly: disallow JavaScript to access the cookie.  This is an
                         extension to the cookie standard and probably not
                         supported by all browsers.
        :param samesite: Limits the scope of the cookie such that it will only
                         be attached to requests if those requests are
                         "same-site".
        z
Set-Cookie)
r   max_ageexpiresr   domainsecurehttponlyrW   Zmax_sizesamesiteN)r   addr   rW   max_cookie_size)
ra   r   r   r   r   r   r   r   r   r  rJ   rJ   rK   
set_cookie3  s    
zBaseResponse.set_cookiec             C   s   | j |dd||d dS )a  Delete a cookie.  Fails silently if key doesn't exist.

        :param key: the key (name) of the cookie to be deleted.
        :param path: if the cookie that should be deleted was limited to a
                     path, the path has to be defined here.
        :param domain: if the cookie that should be deleted was limited to a
                       domain, that domain has to be defined here.
        r   )r   r   r   r   N)r  )ra   r   r   r   rJ   rJ   rK   delete_cookie_  s    	zBaseResponse.delete_cookiec          	   C   s,   yt | j W n ttfk
r&   dS X dS )a  If the response is streamed (the response is not an iterable with
        a length information) this property is `True`.  In this case streamed
        means that there is no information about the number of iterations.
        This is usually `True` if a generator is passed to the response object.

        This is useful for checking before applying some sort of post
        filtering that should not take place for streamed responses.
        TF)r   r   r   r   )ra   rJ   rJ   rK   r   j  s
    
zBaseResponse.is_streamedc             C   s   t | jttfS )zIf the iterator is buffered, this property will be `True`.  A
        response object will consider an iterator to be buffered if the
        response attribute is a list or tuple.

        .. versionadded:: 0.6
        )rN   r   tupler   )ra   rJ   rJ   rK   r   z  s    zBaseResponse.is_sequencec             C   s0   t | jdr| j  x| jD ]
}|  qW dS )zClose the wrapped response if possible.  You can also use the object
        in a with statement which will automatically close it.

        .. versionadded:: 0.9
           Can now be used in a with statement.
        ro   N)hasattrr   ro   r   )ra   r   rJ   rJ   rK   ro     s    
zBaseResponse.closec             C   s   | S )NrJ   )ra   rJ   rJ   rK   r     s    zBaseResponse.__enter__c             C   s   |    d S )N)ro   )ra   r   r   r   rJ   rJ   rK   r     s    zBaseResponse.__exit__c             C   s,   t |  | _tttt| j| jd< dS )a5  Call this method if you want to make your response object ready for
        being pickled.  This buffers the generator if there is one.  It will
        also set the `Content-Length` header to the length of the body.

        .. versionchanged:: 0.6
           The `Content-Length` header is now set.
        zContent-LengthN)r   r   r   r   r   r   r   r   )ra   rJ   rJ   rK   freeze  s    
zBaseResponse.freezec             C   sj  t | j}d}d}d}| j}x@|D ]8\}}| }	|	dkr@|}q"|	dkrN|}q"|	dkr"|}q"W |dk	r|}
t|trt|dd}| jrt|dd}t|trt|}t	||}||
kr||d< |dk	rt|trt||d	< |d
krt
| | jrf| jrf|dkrf|dkrfd|  kr(dk sfn ytdd | jD }W n tk
rX   Y nX t||d< |S )ak  This is automatically called right before the response is started
        and returns headers modified for the given environment.  It returns a
        copy of the headers from the response with some modifications applied
        if necessary.

        For example the location header (if present) is joined with the root
        URL of the environment.  Also the content length is automatically set
        to zero here for certain status codes.

        .. versionchanged:: 0.6
           Previously that function was called `fix_headers` and modified
           the response object in place.  Also since 0.6, IRIs in location
           and content-location headers are handled properly.

           Also starting with 0.6, Werkzeug will attempt to set the content
           length if it is able to figure it out on its own.  This is the
           case if all the strings in the response iterable are already
           encoded and the iterable is buffered.

        :param environ: the WSGI environment of the request.
        :return: returns a new :class:`~werkzeug.datastructures.Headers`
                 object.
        Nlocationzcontent-locationzcontent-lengthT)Zsafe_conversion)Z	root_onlyLocationzContent-Location)i0  i  )   i0  d   r   c             s   s   | ]}t t|d V  qdS )asciiN)r   r=   )r   r   rJ   rJ   rK   r     s   z0BaseResponse.get_wsgi_headers.<locals>.<genexpr>zContent-Length)r/   r   r   r   rN   r?   r   autocorrect_location_headerr'   r    r   r   r   r   r   UnicodeErrorr   )ra   r`   r   r	  content_locationr|   r   r   r   ZikeyZold_locationZcurrent_urlrJ   rJ   rK   get_wsgi_headers  sP    





zBaseResponse.get_wsgi_headersc             C   s`   | j }|d dks0d|  kr&dk s0n |dkr6d}n| jrLt| j | jS |  }t|| jS )a  Returns the application iterator for the given environ.  Depending
        on the request method and the current status code the return value
        might be an empty response rather than the one from the response.

        If the request method is `HEAD` or the status code is in a range
        where the HTTP specification requires an empty response, an empty
        iterable is returned.

        .. versionadded:: 0.6

        :param environ: the WSGI environment of the request.
        :return: a response iterable.
        r   HEADr  r   )r  i0  i  rJ   )r   r   rQ   r   r   r)   ro   )ra   r`   r   rP   rJ   rJ   rK   get_app_iter  s    
zBaseResponse.get_app_iterc             C   s$   |  |}| |}|| j| fS )aF  Returns the final WSGI response as tuple.  The first item in
        the tuple is the application iterator, the second the status and
        the third the list of headers.  The response returned is created
        specially for the given environment.  For example if the request
        method in the WSGI environment is ``'HEAD'`` the response will
        be empty and only the headers and status code will be present.

        .. versionadded:: 0.6

        :param environ: the WSGI environment of the request.
        :return: an ``(app_iter, status, headers)`` tuple.
        )r  r  r   Zto_wsgi_list)ra   r`   r   app_iterrJ   rJ   rK   get_wsgi_response  s    

zBaseResponse.get_wsgi_responsec             C   s   |  |\}}}||| |S )zProcess this response as WSGI application.

        :param environ: the WSGI environment.
        :param start_response: the response callable provided by the WSGI
                               server.
        :return: an application iterator
        )r  )ra   r`   Zstart_responser  r   r   rJ   rJ   rK   __call__%  s    
zBaseResponse.__call__)NNNNNF)N)F)F)F)r   NNr   NFFN)r   N)+rj   r   r   r   rW   r   r   r   r  r   r  rb   r   rl   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r   r   ro   r   r   r  r  r  r  r  rJ   rJ   rJ   rK   r     s^   E

 
#$

  
*

Wr   c               @   s@   e Zd ZdZedd Zedd Zedd Zedd	 Zd
S )AcceptMixinzA mixin for classes with an :attr:`~BaseResponse.environ` attribute
    to get all the HTTP accept headers as
    :class:`~werkzeug.datastructures.Accept` objects (or subclasses
    thereof).
    c             C   s   t | jdtS )zoList of mimetypes this client supports as
        :class:`~werkzeug.datastructures.MIMEAccept` object.
        ZHTTP_ACCEPT)r   r`   r   r4   )ra   rJ   rJ   rK   accept_mimetypes:  s    zAcceptMixin.accept_mimetypesc             C   s   t | jdtS )zqList of charsets this client supports as
        :class:`~werkzeug.datastructures.CharsetAccept` object.
        ZHTTP_ACCEPT_CHARSET)r   r`   r   r5   )ra   rJ   rJ   rK   accept_charsetsA  s    zAcceptMixin.accept_charsetsc             C   s   t | jdS )zList of encodings this client accepts.  Encodings in a HTTP term
        are compression encodings such as gzip.  For charsets have a look at
        :attr:`accept_charset`.
        ZHTTP_ACCEPT_ENCODING)r   r`   r   )ra   rJ   rJ   rK   accept_encodingsI  s    zAcceptMixin.accept_encodingsc             C   s   t | jdtS )a   List of languages this client accepts as
        :class:`~werkzeug.datastructures.LanguageAccept` object.

        .. versionchanged 0.5
           In previous versions this was a regular
           :class:`~werkzeug.datastructures.Accept` object.
        ZHTTP_ACCEPT_LANGUAGE)r   r`   r   r6   )ra   rJ   rJ   rK   accept_languagesQ  s    	zAcceptMixin.accept_languagesN)	rj   r   r   r   r#   r  r  r  r  rJ   rJ   rJ   rK   r  2  s
   r  c               @   sd   e Zd ZdZedd Zedd Zedd Zedd	 Zed
d Z	edd Z
edd ZdS )ETagRequestMixinzAdd entity tag and cache descriptors to a request object or object with
    a WSGI environment available as :attr:`~BaseRequest.environ`.  This not
    only provides access to etags but also to the cache control header.
    c             C   s   | j d}t|dtS )zwA :class:`~werkzeug.datastructures.RequestCacheControl` object
        for the incoming cache control headers.
        ZHTTP_CACHE_CONTROLN)r`   r   r   r8   )ra   cache_controlrJ   rJ   rK   r  e  s    zETagRequestMixin.cache_controlc             C   s   t | jdS )z~An object containing all the etags in the `If-Match` header.

        :rtype: :class:`~werkzeug.datastructures.ETags`
        HTTP_IF_MATCH)r	   r`   r   )ra   rJ   rJ   rK   if_matchn  s    zETagRequestMixin.if_matchc             C   s   t | jdS )zAn object containing all the etags in the `If-None-Match` header.

        :rtype: :class:`~werkzeug.datastructures.ETags`
        ZHTTP_IF_NONE_MATCH)r	   r`   r   )ra   rJ   rJ   rK   if_none_matchv  s    zETagRequestMixin.if_none_matchc             C   s   t | jdS )z9The parsed `If-Modified-Since` header as datetime object.ZHTTP_IF_MODIFIED_SINCE)r
   r`   r   )ra   rJ   rJ   rK   if_modified_since~  s    z"ETagRequestMixin.if_modified_sincec             C   s   t | jdS )z;The parsed `If-Unmodified-Since` header as datetime object.ZHTTP_IF_UNMODIFIED_SINCE)r
   r`   r   )ra   rJ   rJ   rK   if_unmodified_since  s    z$ETagRequestMixin.if_unmodified_sincec             C   s   t | jdS )zThe parsed `If-Range` header.

        .. versionadded:: 0.7

        :rtype: :class:`~werkzeug.datastructures.IfRange`
        HTTP_IF_RANGE)r   r`   r   )ra   rJ   rJ   rK   if_range  s    zETagRequestMixin.if_rangec             C   s   t | jdS )z{The parsed `Range` header.

        .. versionadded:: 0.7

        :rtype: :class:`~werkzeug.datastructures.Range`
        
HTTP_RANGE)r   r`   r   )ra   rJ   rJ   rK   range  s    zETagRequestMixin.rangeN)rj   r   r   r   r#   r  r  r   r!  r"  r$  r&  rJ   rJ   rJ   rK   r  ^  s   	
r  c               @   s   e Zd ZdZedd ZdS )UserAgentMixinzAdds a `user_agent` attribute to the request object which contains the
    parsed user agent of the browser that triggered the request as a
    :class:`~werkzeug.useragents.UserAgent` object.
    c             C   s   ddl m} || jS )zThe current user agent.r   )	UserAgent)Zwerkzeug.useragentsr(  r`   )ra   r(  rJ   rJ   rK   
user_agent  s    zUserAgentMixin.user_agentN)rj   r   r   r   r#   r)  rJ   rJ   rJ   rK   r'    s   r'  c               @   s   e Zd ZdZedd ZdS )AuthorizationMixinzAdds an :attr:`authorization` property that represents the parsed
    value of the `Authorization` header as
    :class:`~werkzeug.datastructures.Authorization` object.
    c             C   s   | j d}t|S )z*The `Authorization` object in parsed form.ZHTTP_AUTHORIZATION)r`   r   r   )ra   headerrJ   rJ   rK   authorization  s    z AuthorizationMixin.authorizationN)rj   r   r   r   r#   r,  rJ   rJ   rJ   rK   r*    s   r*  c               @   s   e Zd ZdZdZdZdS )StreamOnlyMixina'  If mixed in before the request object this will change the bahavior
    of it to disable handling of form parsing.  This disables the
    :attr:`files`, :attr:`form` attributes and will just provide a
    :attr:`stream` attribute that however is always available.

    .. versionadded:: 0.9
    TFN)rj   r   r   r   r   r   rJ   rJ   rJ   rK   r-    s   r-  c                   s   e Zd ZdZedd Zdd Zdd Zdd	d
ZdddZ	d ddZ
d!ddZdd Zd" fdd	ZedddZdd Zdd ZeeeddZ[[  ZS )#ETagResponseMixina  Adds extra functionality to a response object for etag and cache
    handling.  This mixin requires an object with at least a `headers`
    object that implements a dict like interface similar to
    :class:`~werkzeug.datastructures.Headers`.

    If you want the :meth:`freeze` method to automatically add an etag, you
    have to mixin this method before the response base class.  The default
    response class does not do that.
    c                s     fdd}t  jd|tS )zThe Cache-Control general-header field is used to specify
        directives that MUST be obeyed by all caching mechanisms along the
        request/response chain.
        c                s.   | sd j kr j d= n| r*|   j d< d S )Nzcache-controlzCache-Control)r   	to_header)r  )ra   rJ   rK   	on_update  s    
z2ETagResponseMixin.cache_control.<locals>.on_updatezcache-control)r   r   r   r7   )ra   r0  rJ   )ra   rK   r    s    zETagResponseMixin.cache_controlc             C   s   | j dkrt| j||| _dS )z8Wrap existing Response in case of Range Request context.   N)r   r,   r   )ra   startlengthrJ   rJ   rK   _wrap_response  s    
z ETagResponseMixin._wrap_responsec             C   s4   d|ks,t || jdd| jddd o2d|kS )zReturn ``True`` if `Range` header is present and if underlying
        resource is considered unchanged when compared with `If-Range` header.
        r#  etagNzlast-modifiedF)Zignore_if_ranger%  )r   r   r   )ra   r`   rJ   rJ   rK   _is_range_request_processable  s
    z/ETagResponseMixin._is_range_request_processableNc       	      C   s   ddl m} |dkrdS || jd< | |r4|dkr8dS t|d}|dkrV||||}||}|dksz|dkr|||d |d  }||kr|| jd< || _d	| _	| 
|d | d
S dS )a  Handle Range Request related headers (RFC7233).  If `Accept-Ranges`
        header is valid, and Range Request is processable, we set the headers
        as described by the RFC, and wrap the underlying response in a
        RangeWrapper.

        Returns ``True`` if Range Request can be fulfilled, ``False`` otherwise.

        :raises: :class:`~werkzeug.exceptions.RequestedRangeNotSatisfiable`
                 if `Range` header could not be parsed or satisfied.
        r   )RequestedRangeNotSatisfiableNFzAccept-Rangesr%  r   zContent-Lengthr1  T)rx   r7  r   r6  r   r   Zrange_for_lengthZto_content_range_headercontent_ranger   r4  )	ra   r`   complete_lengthr\   r7  Zparsed_rangeZrange_tupleZcontent_range_headerr|   rJ   rJ   rK   _process_range_request  s*    



z(ETagResponseMixin._process_range_requestFc             C   s   t |}|d dkrd| jkr*t | jd< t|}| |||}|s~t|| jdd| jds~t|drxd	| _nd
| _| j	rd| jkr| 
 }|dk	r|| jd< | S )a  Make the response conditional to the request.  This method works
        best if an etag was defined for the response already.  The `add_etag`
        method can be used to do that.  If called without etag just the date
        header is set.

        This does nothing if the request method in the request or environ is
        anything but GET or HEAD.

        For optimal performance when handling range requests, it's recommended
        that your response data object implements `seekable`, `seek` and `tell`
        methods as described by :py:class:`io.IOBase`.  Objects returned by
        :meth:`~werkzeug.wsgi.wrap_file` automatically implement those methods.

        It does not remove the body of the response because that's something
        the :meth:`__call__` function does for us automatically.

        Returns self so that you can do ``return resp.make_conditional(req)``
        but modifies the object in-place.

        :param request_or_environ: a request object or WSGI environment to be
                                   used to make the response conditional
                                   against.
        :param accept_ranges: This parameter dictates the value of
                              `Accept-Ranges` header. If ``False`` (default),
                              the header is not set. If ``True``, it will be set
                              to ``"bytes"``. If ``None``, it will be set to
                              ``"none"``. If it's a string, it will use this
                              value.
        :param complete_length: Will be used only in valid Range Requests.
                                It will set `Content-Range` complete length
                                value and compute `Content-Length` real value.
                                This parameter is mandatory for successful
                                Range Requests completion.
        :raises: :class:`~werkzeug.exceptions.RequestedRangeNotSatisfiable`
                 if `Range` header could not be parsed or satisfied.
        r   )r   r  dateDater5  Nzlast-modifiedr  i  i0  zcontent-lengthzContent-Length)r<   r   r   r]   r:  r   r   r	   r   r   r   )ra   Zrequest_or_environr\   r9  r`   Zis206r3  rJ   rJ   rK   make_conditional  s"    &

z"ETagResponseMixin.make_conditionalc             C   s&   |sd| j kr"| t|  | dS )z:Add an etag for the current response if there is none yet.r5  N)r   set_etagr   r   )ra   Z	overwriteweakrJ   rJ   rK   add_etagT  s    zETagResponseMixin.add_etagc             C   s   t ||| jd< dS )z8Set the etag, and override the old one if there was one.ETagN)r   r   )ra   r5  r?  rJ   rJ   rK   r>  Y  s    zETagResponseMixin.set_etagc             C   s   t | jdS )z{Return a tuple in the form ``(etag, is_weak)``.  If there is no
        ETag the return value is ``(None, None)``.
        rA  )r   r   r   )ra   rJ   rJ   rK   get_etag]  s    zETagResponseMixin.get_etagc                s   |s|    tt|   dS )zCall this method if you want to make your response object ready for
        pickeling.  This buffers the generator if there is one.  This also
        sets the etag unless `no_etag` is set to `True`.
        N)r@  superr.  r  )ra   Zno_etag)ri   rJ   rK   r  c  s    zETagResponseMixin.freezezAccept-Rangesz
        The `Accept-Ranges` header.  Even though the name would indicate
        that multiple values are supported, it must be one string token only.

        The values ``'bytes'`` and ``'none'`` are common.

        .. versionadded:: 0.7)r   c                s:    fdd}t  jd|}|d kr6td d d |d}|S )Nc                s    | s j d= n|   j d< d S )Nzcontent-rangezContent-Range)r   r/  )rng)ra   rJ   rK   r0  u  s    
z7ETagResponseMixin._get_content_range.<locals>.on_updatezcontent-range)r0  )r   r   r   r:   )ra   r0  r   rJ   )ra   rK   _get_content_ranget  s    z$ETagResponseMixin._get_content_rangec             C   s6   |s| j d= n$t|tr$|| j d< n| | j d< d S )Nzcontent-rangezContent-Range)r   rN   r>   r/  )ra   r   rJ   rJ   rK   _set_content_range  s
    

z$ETagResponseMixin._set_content_rangez
        The `Content-Range` header as
        :class:`~werkzeug.datastructures.ContentRange` object.  Even if the
        header is not set it wil provide such an object for easier
        manipulation.

        .. versionadded:: 0.7)NN)FN)FF)F)F)rj   r   r   r   r   r  r4  r6  r:  r=  r@  r>  rB  r  r%   r\   rE  rF  r8  __classcell__rJ   rJ   )ri   rK   r.    s$   

# 
=

	r.  c               @   sX   e Zd ZdZdZdd Zdd Zdd Zd	d
 Zdd Z	dd Z
dd Zedd ZdS )ResponseStreamzA file descriptor like object used by the :class:`ResponseStreamMixin` to
    represent the body of the stream.  It directly pushes into the response
    iterable of the response object.
    zwb+c             C   s   || _ d| _d S )NF)r   closed)ra   r   rJ   rJ   rK   rb     s    zResponseStream.__init__c             C   sB   | j rtd| jjdd | jj| | jjdd  t|S )NzI/O operation on closed fileT)r   zContent-Length)rI  r[   r   r   rd   r   rn   r   )ra   r   rJ   rJ   rK   write  s    zResponseStream.writec             C   s   x|D ]}|  | qW d S )N)rJ  )ra   seqrX   rJ   rJ   rK   
writelines  s    
zResponseStream.writelinesc             C   s
   d| _ d S )NT)rI  )ra   rJ   rJ   rK   ro     s    zResponseStream.closec             C   s   | j rtdd S )NzI/O operation on closed file)rI  r[   )ra   rJ   rJ   rK   flush  s    zResponseStream.flushc             C   s   | j rtddS )NzI/O operation on closed fileF)rI  r[   )ra   rJ   rJ   rK   isatty  s    zResponseStream.isattyc             C   s   | j   ttt| j j S )N)r   r   r   r   r   )ra   rJ   rJ   rK   tell  s    
zResponseStream.tellc             C   s   | j jS )N)r   rW   )ra   rJ   rJ   rK   encoding  s    zResponseStream.encodingN)rj   r   r   r   moderb   rJ  rL  ro   rM  rN  rO  r   rP  rJ   rJ   rJ   rK   rH    s   rH  c               @   s   e Zd ZdZedd ZdS )ResponseStreamMixinzMixin for :class:`BaseRequest` subclasses.  Classes that inherit from
    this mixin will automatically get a :attr:`stream` property that provides
    a write-only interface to the response iterable.
    c             C   s   t | S )z+The response iterable as write-only stream.)rH  )ra   rJ   rJ   rK   r     s    zResponseStreamMixin.streamN)rj   r   r   r   r#   r   rJ   rJ   rJ   rK   rR    s   rR  c               @   s   e Zd ZdZedddZedd ZedddZed	d
dZ	edddZ
eddeddZeddeddZdd Zedd Zedd Zedd ZdS )CommonRequestDescriptorsMixinzA mixin for :class:`BaseRequest` subclasses.  Request objects that
    mix this class in will automatically get descriptors for a couple of
    HTTP headers with automatic type conversion.

    .. versionadded:: 0.5
    r~   z
        The Content-Type entity-header field indicates the media type of
        the entity-body sent to the recipient or, in the case of the HEAD
        method, the media type that would have been sent had the request
        been a GET.)r   c             C   s
   t | jS )zThe Content-Length entity-header field indicates the size of the
        entity-body in bytes or, in the case of the HEAD method, the size of
        the entity-body that would have been sent had the request been a
        GET.
        )r+   r`   )ra   rJ   rJ   rK   r|     s    z,CommonRequestDescriptorsMixin.content_lengthZHTTP_CONTENT_ENCODINGa  
        The Content-Encoding entity-header field is used as a modifier to the
        media-type.  When present, its value indicates what additional content
        codings have been applied to the entity-body, and thus what decoding
        mechanisms must be applied in order to obtain the media-type
        referenced by the Content-Type header field.

        .. versionadded:: 0.9ZHTTP_CONTENT_MD5a  
         The Content-MD5 entity-header field, as defined in RFC 1864, is an
         MD5 digest of the entity-body for the purpose of providing an
         end-to-end message integrity check (MIC) of the entity-body.  (Note:
         a MIC is good for detecting accidental modification of the
         entity-body in transit, but is not proof against malicious attacks.)

        .. versionadded:: 0.9ZHTTP_REFERERa  
        The Referer[sic] request-header field allows the client to specify,
        for the server's benefit, the address (URI) of the resource from which
        the Request-URI was obtained (the "referrer", although the header
        field is misspelled).Z	HTTP_DATENz
        The Date general-header field represents the date and time at which
        the message was originated, having the same semantics as orig-date
        in RFC 822.ZHTTP_MAX_FORWARDSz
         The Max-Forwards request-header field provides a mechanism with the
         TRACE and OPTIONS methods to limit the number of proxies or gateways
         that can forward the request to the next inbound server.c             C   s"   t | dst| jdd| _d S )N_parsed_content_typer~   r   )r  r   r`   r   rT  )ra   rJ   rJ   rK   _parse_content_type  s    
z1CommonRequestDescriptorsMixin._parse_content_typec             C   s   |    | jd  S )zLike :attr:`content_type`, but without parameters (eg, without
        charset, type etc.) and always lowercase.  For example if the content
        type is ``text/HTML; charset=utf-8`` the mimetype would be
        ``'text/html'``.
        r   )rU  rT  r   )ra   rJ   rJ   rK   r   
  s    z&CommonRequestDescriptorsMixin.mimetypec             C   s   |    | jd S )zThe mimetype parameters as dict.  For example if the content
        type is ``text/html; charset=utf-8`` the params would be
        ``{'charset': 'utf-8'}``.
        r   )rU  rT  )ra   rJ   rJ   rK   mimetype_params  s    z-CommonRequestDescriptorsMixin.mimetype_paramsc             C   s   t | jddS )aj  The Pragma general-header field is used to include
        implementation-specific directives that might apply to any recipient
        along the request/response chain.  All pragma directives specify
        optional behavior from the viewpoint of the protocol; however, some
        systems MAY require that behavior be consistent with the directives.
        ZHTTP_PRAGMAr   )r   r`   r   )ra   rJ   rJ   rK   pragma  s    z$CommonRequestDescriptorsMixin.pragma)rj   r   r   r   r$   rz   r#   r|   content_encodingcontent_md5Zreferrerr
   r;  r   Zmax_forwardsrU  r   r   rV  rW  rJ   rJ   rJ   rK   rS    s$   	
	rS  c               @   s.  e Zd ZdZdd Zdd Zdd Zeeedd	Zeed
d	Z	e
ddd	Ze
ddeedd	Ze
ddd	Ze
ddeedd	Ze
ddd	Ze
ddd	Ze
ddd	Ze
ddeedd	Ze
ddeedd	Ze
ddeedd	Zd d! Zd"d# Zeeed$d	Zd-d%d&Zed'd(d	Zed)d*d	Z ed+d,d	Z![[[[[dS ).CommonResponseDescriptorsMixinzA mixin for :class:`BaseResponse` subclasses.  Response objects that
    mix this class in will automatically get descriptors for a couple of
    HTTP headers with automatic type conversion.
    c             C   s&   | j d}|r"|dd  S d S )Nzcontent-type;r   )r   r   r   r   )ra   ZctrJ   rJ   rK   _get_mimetype/  s    z,CommonResponseDescriptorsMixin._get_mimetypec             C   s   t || j| jd< d S )NzContent-Type)r&   rW   r   )ra   r   rJ   rJ   rK   _set_mimetype4  s    z,CommonResponseDescriptorsMixin._set_mimetypec                s,    fdd}t  jddd }t||S )Nc                s   t  j|  jd< d S )NzContent-Type)r   r   r   )r   )ra   rJ   rK   r0  8  s    zFCommonResponseDescriptorsMixin._get_mimetype_params.<locals>.on_updatezcontent-typer   r   )r   r   r   r9   )ra   r0  r   rJ   )ra   rK   _get_mimetype_params7  s    z3CommonResponseDescriptorsMixin._get_mimetype_paramsz9
        The mimetype (content type without charset etc.))r   z
        The mimetype parameters as dict.  For example if the content
        type is ``text/html; charset=utf-8`` the params would be
        ``{'charset': 'utf-8'}``.

        .. versionadded:: 0.5
        r
  z
        The Location response-header field is used to redirect the recipient
        to a location other than the Request-URI for completion of the request
        or identification of a new resource.ZAgeNa  
        The Age response-header field conveys the sender's estimate of the
        amount of time since the response (or its revalidation) was
        generated at the origin server.

        Age values are non-negative decimal integers, representing time in
        seconds.zContent-Typez
        The Content-Type entity-header field indicates the media type of the
        entity-body sent to the recipient or, in the case of the HEAD method,
        the media type that would have been sent had the request been a GET.
    zContent-Lengtha  
        The Content-Length entity-header field indicates the size of the
        entity-body, in decimal number of OCTETs, sent to the recipient or,
        in the case of the HEAD method, the size of the entity-body that would
        have been sent had the request been a GET.zContent-Locationz
        The Content-Location entity-header field MAY be used to supply the
        resource location for the entity enclosed in the message when that
        entity is accessible from a location separate from the requested
        resource's URI.zContent-Encodingad  
        The Content-Encoding entity-header field is used as a modifier to the
        media-type.  When present, its value indicates what additional content
        codings have been applied to the entity-body, and thus what decoding
        mechanisms must be applied in order to obtain the media-type
        referenced by the Content-Type header field.zContent-MD5a|  
         The Content-MD5 entity-header field, as defined in RFC 1864, is an
         MD5 digest of the entity-body for the purpose of providing an
         end-to-end message integrity check (MIC) of the entity-body.  (Note:
         a MIC is good for detecting accidental modification of the
         entity-body in transit, but is not proof against malicious attacks.)
        r<  z
        The Date general-header field represents the date and time at which
        the message was originated, having the same semantics as orig-date
        in RFC 822.ZExpiresz
        The Expires entity-header field gives the date/time after which the
        response is considered stale. A stale cache entry may not normally be
        returned by a cache.zLast-Modifiedz
        The Last-Modified entity-header field indicates the date and time at
        which the origin server believes the variant was last modified.c             C   s>   | j d}|d krd S | r6t tt|d S t|S )Nzretry-after)Zseconds)r   r   isdigitr   Zutcnowr   r   r
   )ra   r   rJ   rJ   rK   _get_retry_after{  s    z/CommonResponseDescriptorsMixin._get_retry_afterc             C   sH   |d krd| j kr| j d= d S t|tr2t|}nt|}|| j d< d S )Nzretry-afterzRetry-After)r   rN   r   r   r   )ra   r   rJ   rJ   rK   _set_retry_after  s    


z/CommonResponseDescriptorsMixin._set_retry_aftera   
        The Retry-After response-header field can be used with a 503 (Service
        Unavailable) response to indicate how long the service is expected
        to be unavailable to the requesting client.

        Time in seconds until expiration or date.c                s&    fdd} fdd}t |||dS )Nc                s     fdd}t  j|S )Nc                s.   | s j krj  = n| r*|  j  < d S )N)r   r/  )Z
header_set)namera   rJ   rK   r0    s    
zMCommonResponseDescriptorsMixin._set_property.<locals>.fget.<locals>.on_update)r   r   r   )ra   r0  )rb  )ra   rK   fget  s    z:CommonResponseDescriptorsMixin._set_property.<locals>.fgetc                s6   |s| j  = n$t|tr$|| j  < nt|| j  < d S )N)r   rN   r>   r   )ra   r   )rb  rJ   rK   fset  s
    

z:CommonResponseDescriptorsMixin._set_property.<locals>.fset)r   )r   )rb  r   rc  rd  rJ   )rb  rK   _set_property  s    z,CommonResponseDescriptorsMixin._set_propertyZVarya   
         The Vary field value indicates the set of request-header fields that
         fully determines, while the response is fresh, whether a cache is
         permitted to use the response to reply to a subsequent request
         without revalidation.zContent-Languagez
         The Content-Language entity-header field describes the natural
         language(s) of the intended audience for the enclosed entity.  Note
         that this might not be equivalent to all the languages used within
         the entity-body.ZAllowaS  
        The Allow entity-header field lists the set of methods supported
        by the resource identified by the Request-URI. The purpose of this
        field is strictly to inform the recipient of valid methods
        associated with the resource. An Allow header field MUST be
        present in a 405 (Method Not Allowed) response.)N)"rj   r   r   r   r\  r]  r^  r   r   rV  r%   r	  r   r   Zagerz   r   r   r|   r  rX  rY  r
   r   r;  r   Zlast_modifiedr`  ra  Zretry_afterre  ZvaryZcontent_languageZallowrJ   rJ   rJ   rK   rZ  (  sT   




rZ  c               @   s   e Zd ZdZedd ZdS )WWWAuthenticateMixinz>Adds a :attr:`www_authenticate` property to a response object.c                s"    fdd} j d}t||S )z/The `WWW-Authenticate` header in a parsed form.c                s.   | sd j kr j d= n| r*|   j d< d S )Nzwww-authenticatezWWW-Authenticate)r   r/  )Zwww_auth)ra   rJ   rK   r0    s    
z8WWWAuthenticateMixin.www_authenticate.<locals>.on_updatezwww-authenticate)r   r   r   )ra   r0  r+  rJ   )ra   rK   www_authenticate  s    z%WWWAuthenticateMixin.www_authenticateN)rj   r   r   r   r   rg  rJ   rJ   rJ   rK   rf    s   rf  c               @   s   e Zd ZdZdS )Requestar  Full featured request object implementing the following mixins:

    - :class:`AcceptMixin` for accept header parsing
    - :class:`ETagRequestMixin` for etag and cache control handling
    - :class:`UserAgentMixin` for user agent introspection
    - :class:`AuthorizationMixin` for http auth handling
    - :class:`CommonRequestDescriptorsMixin` for common headers
    N)rj   r   r   r   rJ   rJ   rJ   rK   rh    s   rh  c               @   s   e Zd ZdZdS )PlainRequestz[A request object without special form parsing capabilities.

    .. versionadded:: 0.9
    N)rj   r   r   r   rJ   rJ   rJ   rK   ri    s   ri  c               @   s   e Zd ZdZdS )Responseaf  Full featured response object implementing the following mixins:

    - :class:`ETagResponseMixin` for etag and cache control handling
    - :class:`ResponseStreamMixin` to add support for the `stream` property
    - :class:`CommonResponseDescriptorsMixin` for various HTTP descriptors
    - :class:`WWWAuthenticateMixin` for HTTP authentication support
    N)rj   r   r   r   rJ   rJ   rJ   rK   rj    s   
rj  N)er   	functoolsr   r   r   warningsr   Zwerkzeug.httpr   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   Zwerkzeug.urlsr   r   r    Zwerkzeug.formparserr!   r"   Zwerkzeug.utilsr#   r$   r%   r&   Zwerkzeug.wsgir'   r(   r)   r*   r+   r,   Zwerkzeug.datastructuresr-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   Zwerkzeug._internalr<   Zwerkzeug._compatr=   r>   r?   r@   rA   rB   rC   rD   rE   rH   rQ   rU   rY   r]   objectr^   r   r  r  r'  r*  r-  r.  rH  rR  rS  rZ  rf  rh  ri  rj  rJ   rJ   rJ   rK   <module>   s\   h	 D,	
    o    h,? N.Y 