
_l                 @   s6  d  d l  Z  d d l m Z d d l m Z d d l m Z d d l m Z d d l m Z d d l m Z d d	 l	 m
 Z
 d d
 l	 m Z d d l	 m Z d d l m Z d d l m Z d d l m Z d d l m Z d d l m Z d d   a d d   Z d d   Z d d   Z Gd d   d e  Z d S)    N   )integer_types)string_types)	text_type)to_bytes)	to_native)Headers)dump_cookie)HTTP_STATUS_CODES)remove_entity_headers)
iri_to_uri)url_join)get_content_type)ClosingIterator)get_current_urlc              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)testr   _run_wsgi_app)args r   C/tmp/pip-build-5gj8f0j9/Werkzeug/werkzeug/wrappers/base_response.pyr      s    r   c             C   s&   t  |  t  r" t j 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 will appear to work but means that the server will send the data to the client one character at a time. This is almost never intended behavior, use 'response.data' to assign strings to the response object.
stacklevelr   N)
isinstancer   warningswarn)iterabler   r   r   _warn_if_string   s    r   c             c   s:   x3 |  D]+ } t  | t  r- | j |  Vq | Vq Wd  S)N)r   r   encode)r   charsetitemr   r   r   _iter_encoded,   s    r    c             C   sI   |  d k r d S|  d k r  d St  |  t  r9 t |   St d   d  S)NTbytesFnonezInvalid accept_ranges value)r   r   r   
ValueError)Zaccept_rangesr   r   r   _clean_accept_ranges4   s    
r$   c            
   @   s  e  Z d  Z d Z d Z d Z d Z d Z d Z d Z	 d Z
 d d d d d d d	 d
  Z d d   Z d d   Z e d d d   Z e d d d   Z e d d    Z e j d d    Z e d d    Z e j d d    Z d d d  Z d d   Z e e e d d Z d d    Z d d! d"  Z d# d$   Z d% d&   Z d' d d d( d d d d d) d*  Z d( d d+ d,  Z e d- d.    Z e d/ d0    Z d1 d2   Z  d3 d4   Z! d5 d6   Z" d7 d8   Z# d9 d:   Z$ d; d<   Z% d= d>   Z& d? d@   Z' d S)A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 :doc:`the unicode chapter </unicode>` 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   sD  t  | t  r | |  _ n$ | s0 t   |  _ n t |  |  _ | d  k r | d  k ro d |  j k ro |  j } | d  k	 r t | |  j  } | } | d  k	 r | |  j d <| d  k r |  j } t  | t  r | |  _ n	 | |  _	 | |  _
 g  |  _ | d  k rg  |  _ n1 t  | t t t f  r7|  j |  n	 | |  _ d  S)Nzcontent-typezContent-Type)r   r   headersdefault_mimetyper   r   default_statusr   status_codestatusdirect_passthrough	_on_closeresponser   r!   	bytearrayset_data)selfr.   r+   r'   mimetypecontent_typer,   r   r   r   __init__   s2    						zBaseResponse.__init__c             C   s   |  j  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-   append)r1   funcr   r   r   call_on_close   s    zBaseResponse.call_on_closec             C   sZ   |  j  r+ d t t t |  j     } 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_streamed	__class____name__r+   )r1   Z	body_infor   r   r   __repr__   s    	"zBaseResponse.__repr__c             C   sI   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)r   r%   	TypeErrorr   r>   )clsr.   environr   r   r   
force_type   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.
        )r   )rB   ZapprC   Zbufferedr   r   r   from_app  s    zBaseResponse.from_appc             C   s   |  j  S)z!The HTTP status code as a number.)_status_code)r1   r   r   r   r*   !  s    zBaseResponse.status_codec             C   sP   | |  _  y! d | t | j   f |  _ Wn t k
 rK d | |  _ Yn Xd  S)Nz%d %sz
%d UNKNOWN)rF   r
   upper_statusKeyError)r1   coder   r   r   r*   &  s
    	!c             C   s   |  j  S)z!The HTTP status code as a string.)rH   )r1   r   r   r   r+   .  s    zBaseResponse.statusc             C   s   y t  |  |  _ Wn t k
 r3 t d   Yn Xy& t |  j j d  d  d  |  _ WnH t k
 r d |  _ d |  j |  _ Yn t k
 r t d   Yn Xd  S)NzInvalid status argument   r   z0 %szEmpty status argument)	r   rH   AttributeErrorrA   intsplitrF   r#   
IndexError)r1   valuer   r   r   r+   3  s    &	c             C   s;   |  j    d j |  j    } | r7 | j |  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_sequencejoinr<   decoder   )r1   Zas_textrvr   r   r   get_dataB  s
    
zBaseResponse.get_datac             C   sb   t  | t  r$ | j |  j  } n t |  } | g |  _ |  j r^ t t |   |  j	 d <d S)zSets a new string as response.  The value set must be either 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)
r   r   r   r   r!   r.    automatically_set_content_lengthstrr;   r'   )r1   rP   r   r   r   r0   U  s    		zBaseResponse.set_datadocz>A descriptor that calls :meth:`get_data` and :meth:`set_data`.c             C   sD   y |  j    Wn t k
 r& d SYn Xt d d   |  j   D  S)z<Returns the content length if available or `None` otherwise.Nc             s   s   |  ] } t  |  Vq d  S)N)r;   ).0xr   r   r   	<genexpr>r  s    z8BaseResponse.calculate_content_length.<locals>.<genexpr>)rR   RuntimeErrorr9   r<   )r1   r   r   r   calculate_content_lengthl  s
    	z%BaseResponse.calculate_content_lengthc             C   sp   |  j  r8 | r4 t |  j t  r4 t |  j  |  _ d S|  j rM t d   |  j sb t d   |  j   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.)r8   r   r.   listr,   r]   implicit_sequence_conversionmake_sequence)r1   Zmutabler   r   r   rR   t  s    					zBaseResponse._ensure_sequencec             C   sP   |  j  sL t |  j d d  } t |  j    |  _ | d k	 rL |  j |  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
        closeN)r8   getattrr.   r_   r<   r7   )r1   rb   r   r   r   ra     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.
        )r   r.   r    r   )r1   r   r   r   r<     s    zBaseResponse.iter_encoded /c
       
      C   s_   |  j  j d t | d | d | d | d | d | d | d | d	 |  j d
 |  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-CookierP   max_ageexpirespathdomainsecurehttponlyr   max_sizesamesiteN)r'   addr	   r   max_cookie_size)
r1   keyrP   rf   rg   rh   ri   rj   rk   rm   r   r   r   
set_cookie  s    '			zBaseResponse.set_cookiec          
   C   s)   |  j  | d d d 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.
        rg   r   rf   rh   ri   N)rq   )r1   rp   rh   ri   r   r   r   delete_cookie  s    	zBaseResponse.delete_cookiec             C   s4   y t  |  j  Wn t t f k
 r/ d SYn Xd 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.   rA   rL   )r1   r   r   r   r=     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
        )r   r.   tupler_   )r1   r   r   r   r8     s    zBaseResponse.is_sequencec             C   s>   t  |  j d  r |  j j   x |  j D] } |   q) Wd 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.
        rb   N)hasattrr.   rb   r-   )r1   r6   r   r   r   rb     s    zBaseResponse.closec             C   s   |  S)Nr   )r1   r   r   r   	__enter__  s    zBaseResponse.__enter__c             C   s   |  j    d  S)N)rb   )r1   exc_type	exc_valuetbr   r   r   __exit__  s    zBaseResponse.__exit__c             C   s>   t  |  j    |  _ 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.   rX   r9   r:   r;   r'   )r1   r   r   r   freeze  s    
zBaseResponse.freezec             C   s   t  |  j  } d } d } d } |  j } x\ | D]T \ } } | j   }	 |	 d k r^ | } q1 |	 d k rs | } q1 |	 d k r1 | } q1 W| d k	 r| }
 t | t  r t | d d } |  j rt | d d } t | t  r t |  } t	 | |  } | |
 k r| | d <| d k	 rBt | t  rBt |  | d	 <d
 | k oYd k  n sj| d k rz| j
 d  n | d k rt |  |  j r|  j r| d k r| d k rd
 | k od k  n ry  t d d   |  j D  } Wn t k
 rYn Xt |  | 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-lengthZsafe_conversionTZstrip_querystringLocationzContent-Locationd   r&      zContent-Length0  c             s   s$   |  ] } t  t | d    Vq d S)asciiN)r;   r   )rZ   r[   r   r   r   r\   z  s    z0BaseResponse.get_wsgi_headers.<locals>.<genexpr>)r~   r   )r   r'   r*   lowerr   r   r   autocorrect_location_headerr   r   remover   rW   r8   r9   r.   UnicodeErrorrX   )r1   rC   r'   r{   content_locationZcontent_lengthr+   rp   rP   ikeyold_locationZcurrent_urlr   r   r   get_wsgi_headers'  sR    			
	
(
		 zBaseResponse.get_wsgi_headersc             C   s   |  j  } | d d k sA d | k o0 d k  n sA | d k rJ f  } n) |  j rg t |  j  |  j S|  j   } 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.
        REQUEST_METHODHEADr}   r&   r~   0  )r~   r   )r*   r,   r   r.   r<   r   rb   )r1   rC   r+   r   r   r   r   get_app_iter  s    			zBaseResponse.get_app_iterc             C   s4   |  j  |  } |  j |  } | |  j | 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)r1   rC   r'   app_iterr   r   r   get_wsgi_response  s    zBaseResponse.get_wsgi_responsec             C   s)   |  j  |  \ } } } | | |  | 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   )r1   rC   Zstart_responser   r+   r'   r   r   r   __call__  s    zBaseResponse.__call__)(r?   
__module____qualname____doc__r   r)   r(   r`   r   rW   ro   r4   r7   r@   classmethodrD   rE   propertyr*   setterr+   rV   r0   datar^   rR   ra   r<   rq   rr   r=   r8   rb   ru   ry   rz   r   r   r   r   r   r   r   r   r%   >   sj   D

$&	.
]r%   )r   _compatr   r   r   r   r   Zdatastructuresr   httpr	   r
   r   urlsr   r   utilsr   Zwsgir   r   r   r   r    r$   objectr%   r   r   r   r   <module>   s&   

