a
    -=ic                     @   sB  d dl Z d dlZd dlZ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 ejrd dlmZ d dlmZ ejd ddddZdOdeeeej ej!e"  e"dddZ#dej ej$e"ej e% f  dddZ&dPdej ej!e"  e"dd d!Z'dej e% dd"d#Z(dQdeej)e* d%d&d'Z+de"dd(d)Z,dRde"e"e"d,d-d.Z-dSde"e"e"d,d/d0Z.dTde"e"ej e" d,d1d2Z/dUde"e"ej e" d,d3d4Z0dVej1e"df ej1e"ef e"e"eej e" d6d7d8Z2G d9d: d:Z3dWdej)e* e%ej!e* d<d=d>Z4G d?d@ d@Z5G dAdB dBZ6ej1ej!e* ej)e* f ej e% e%ej7e* dCdDdEZ8dXej1ej!e* ej)e* f ej e% e%eej7e* dGdHdIZ9dYej1ej!e* ej)e* f e*ej e% e%eej7e* dJdKdLZ:G dMdN dNe j;Z<dS )Z    N)partialupdate_wrapper)chain   )_make_encode_wrapper)	_to_bytes)_to_str)utils)host_is_trusted)	_URLTuple)
uri_to_iri)url_join)	url_parse)	url_quote)WSGIApplication)WSGIEnvironment).r   r   )freturnc                    s   t  fdd S )a
  Marks a function as responder.  Decorate a function with it and it
    will automatically call the return value as WSGI application.

    Example::

        @responder
        def application(environ, start_response):
            return Response('Hello World!')
    c                     s    |  | dd   S )N )ar   r   ^/home/droni/.local/share/virtualenvs/DPS-5Je3_V2c/lib/python3.9/site-packages/werkzeug/wsgi.py<lambda>#       zresponder.<locals>.<lambda>r   r   r   r   r   	responder   s    
r   Fr   )environ	root_onlystrip_querystring	host_onlytrusted_hostsr   c                 C   sf   | d t | |d}|sV| dd|d< |sV| dd|d< |sV| ddd	|d
< tjf i |S )aX  Recreate the URL for a request from the parts in a WSGI
    environment.

    The URL is an IRI, not a URI, so it may contain Unicode characters.
    Use :func:`~werkzeug.urls.iri_to_uri` to convert it to ASCII.

    :param environ: The WSGI environment to get the URL parts from.
    :param root_only: Only build the root path, don't include the
        remaining path or query string.
    :param strip_querystring: Don't include the query string.
    :param host_only: Only build the scheme and host.
    :param trusted_hosts: A list of trusted host names to validate the
        host against.
    wsgi.url_scheme)schemehostSCRIPT_NAME 	root_path	PATH_INFOpathQUERY_STRINGlatin1Zquery_string)get_hostgetencode_sansio_utilsget_current_url)r   r   r   r    r!   partsr   r   r   r0   &   s    r0   )r   r   c              	   C   sN   |  d}|d u rd S zt|  dd }W n ttfyD   d }Y n0 ||fS )NZSERVER_NAMEZSERVER_PORT)r-   int	TypeError
ValueError)r   nameportr   r   r   _get_serverL   s    

r7   )r   r!   r   c                 C   s   t | d | dt| |S )ar  Return the host for the given WSGI environment.

    The ``Host`` header is preferred, then ``SERVER_NAME`` if it's not
    set. The returned host will only contain the port if it is different
    than the standard port for the protocol.

    Optionally, verify that the host is trusted using
    :func:`host_is_trusted` and raise a
    :exc:`~werkzeug.exceptions.SecurityError` if it is not.

    :param environ: A WSGI environment dict.
    :param trusted_hosts: A list of trusted host names.

    :return: Host, with port if necessary.
    :raise ~werkzeug.exceptions.SecurityError: If the host is not
        trusted.
    r"   Z	HTTP_HOST)r/   r,   r-   r7   )r   r!   r   r   r   r,   ]   s    r,   c                 C   s   t j| d| dddS )a  Returns the content length from the WSGI environment as
    integer. If it's not available or chunked transfer encoding is used,
    ``None`` is returned.

    .. versionadded:: 0.9

    :param environ: the WSGI environ to fetch the content length from.
    ZCONTENT_LENGTHZHTTP_TRANSFER_ENCODINGr&   )Zhttp_content_lengthZhttp_transfer_encoding)r/   get_content_lengthr-   )r   r   r   r   r8   y   s    	
r8   T)r   safe_fallbackr   c                 C   s\   t t jt | d }t| }| dr,|S |du rD|r@t S |S t t jt t||S )a
  Returns the input stream from the WSGI environment and wraps it
    in the most sensible way possible. The stream returned is not the
    raw WSGI stream in most cases but one that is safe to read from
    without taking into account the content length.

    If content length is not set, the stream will be empty for safety reasons.
    If the WSGI server supports chunked or infinite streams, it should set
    the ``wsgi.input_terminated`` value in the WSGI environ to indicate that.

    .. versionadded:: 0.9

    :param environ: the WSGI environ to fetch the stream from.
    :param safe_fallback: use an empty stream as a safe fallback when the
        content length is not set. Disabling this allows infinite streams,
        which can be a denial-of-service risk.
    z
wsgi.inputzwsgi.input_terminatedN)	tcastIObytesr8   r-   ioBytesIOLimitedStream)r   r9   streamcontent_lengthr   r   r   get_input_stream   s    
rC   c                 C   s.   t jdtdd | ddd}t|ddS )	aR  Returns the ``QUERY_STRING`` from the WSGI environment. This also
    takes care of the WSGI decoding dance. The string returned will be
    restricted to ASCII characters.

    :param environ: WSGI environment to get the query string from.

    .. deprecated:: 2.2
        Will be removed in Werkzeug 2.3.

    .. versionadded:: 0.9
    zE'get_query_string' is deprecated and will be removed in Werkzeug 2.3.   
stacklevelr*   r&   r+   z:&%=+$!*'(),)safe)warningswarnDeprecationWarningr-   r.   r   )r   qsr   r   r   get_query_string   s    rL   utf-8replace)r   charseterrorsr   c                 C   s"   |  ddd}t|||ddS )a[  Return the ``PATH_INFO`` from the WSGI environment and decode it
    unless ``charset`` is ``None``.

    :param environ: WSGI environment to get the path from.
    :param charset: The charset for the path info, or ``None`` if no
        decoding should be performed.
    :param errors: The decoding error handling.

    .. versionadded:: 0.9
    r(   r&   r+   TZallow_none_charset)r-   r.   r	   r   rO   rP   r)   r   r   r   get_path_info   s    rS   c                 C   s2   t jdtdd | ddd}t|||ddS )	a  Return the ``SCRIPT_NAME`` from the WSGI environment and decode
    it unless `charset` is set to ``None``.

    :param environ: WSGI environment to get the path from.
    :param charset: The charset for the path, or ``None`` if no decoding
        should be performed.
    :param errors: The decoding error handling.

    .. deprecated:: 2.2
        Will be removed in Werkzeug 2.3.

    .. versionadded:: 0.9
    zD'get_script_name' is deprecated and will be removed in Werkzeug 2.3.rD   rE   r%   r&   r+   TrQ   )rH   rI   rJ   r-   r.   r	   rR   r   r   r   get_script_name   s    rT   c                 C   s   t jdtdd | d}|s"dS | dd}|}|d}||kr\|dt|t|  7 }d|vrd| d< || | d< |d	}n4|dd
\}}d| | d< || | d< |d	}t|||ddS )a  Removes and returns the next segment of `PATH_INFO`, pushing it onto
    `SCRIPT_NAME`.  Returns `None` if there is nothing left on `PATH_INFO`.

    If the `charset` is set to `None` bytes are returned.

    If there are empty segments (``'/foo//bar``) these are ignored but
    properly pushed to the `SCRIPT_NAME`:

    >>> env = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/a/b'}
    >>> pop_path_info(env)
    'a'
    >>> env['SCRIPT_NAME']
    '/foo/a'
    >>> pop_path_info(env)
    'b'
    >>> env['SCRIPT_NAME']
    '/foo/a/b'

    .. deprecated:: 2.2
        Will be removed in Werkzeug 2.3.

    .. versionadded:: 0.5

    .. versionchanged:: 0.9
       The path is now decoded and a charset and encoding
       parameter can be provided.

    :param environ: the WSGI environment that is modified.
    :param charset: The ``encoding`` parameter passed to
        :func:`bytes.decode`.
    :param errors: The ``errors`` paramater passed to
        :func:`bytes.decode`.
    zB'pop_path_info' is deprecated and will be removed in Werkzeug 2.3.rD   rE   r(   Nr%   r&   /r+   r   TrQ   )	rH   rI   rJ   r-   lstriplenr.   splitr	   )r   rO   rP   r)   script_nameold_pathrvsegmentr   r   r   pop_path_info   s,    $


r]   c                 C   sL   t jdtdd | ddddd}|rHt|d d	||d
dS dS )ai  Returns the next segment on the `PATH_INFO` or `None` if there
    is none.  Works like :func:`pop_path_info` without modifying the
    environment:

    >>> env = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/a/b'}
    >>> peek_path_info(env)
    'a'
    >>> peek_path_info(env)
    'a'

    If the `charset` is set to `None` bytes are returned.

    .. deprecated:: 2.2
        Will be removed in Werkzeug 2.3.

    .. versionadded:: 0.5

    .. versionchanged:: 0.9
       The path is now decoded and a charset and encoding
       parameter can be provided.

    :param environ: the WSGI environment that is checked.
    zC'peek_path_info' is deprecated and will be removed in Werkzeug 2.3.rD   rE   r(   r&   rU   r   r   r+   TrQ   N)rH   rI   rJ   r-   rV   rX   r	   r.   )r   rO   rP   segmentsr   r   r   peek_path_info3  s    r_   werkzeug.url_quote)environ_or_baseurlpath_or_urlrO   rP   collapse_http_schemesr   c                 C   s  t jdtdd tttddd}t|||}t| trDt| dd} t| ||}t|d	d
 \}}	}
tt	||d	d
 \}}}|||	}	|||}|r||fD ]}|dvr d	S qn|dv r||ksd	S |	|krd	S |

d}
||
sd	S d|t|
d	 d S )ah  Extracts the path info from the given URL (or WSGI environment) and
    path. The path info returned is a string. The URLs might also be IRIs.

    If the path info could not be determined, `None` is returned.

    Some examples:

    >>> extract_path_info('http://example.com/app', '/app/hello')
    '/hello'
    >>> extract_path_info('http://example.com/app',
    ...                   'https://example.com/app/hello')
    '/hello'
    >>> extract_path_info('http://example.com/app',
    ...                   'https://example.com/app/hello',
    ...                   collapse_http_schemes=False) is None
    True

    Instead of providing a base URL you can also pass a WSGI environment.

    :param environ_or_baseurl: a WSGI environment dict, a base URL or
                               base IRI.  This is the root of the
                               application.
    :param path_or_url: an absolute path from the server root, a
                        relative path (in which case it's the path info)
                        or a full URL.
    :param charset: the charset for byte data in URLs
    :param errors: the error handling on decode
    :param collapse_http_schemes: if set to `False` the algorithm does
                                  not assume that http and https on the
                                  same server point to the same
                                  resource.

    .. deprecated:: 2.2
        Will be removed in Werkzeug 2.3.

    .. versionchanged:: 0.15
        The ``errors`` parameter defaults to leaving invalid bytes
        quoted instead of replacing them.

    .. versionadded:: 0.6

    zF'extract_path_info' is deprecated and will be removed in Werkzeug 2.3.rD   rE   )r#   netlocr   c                 S   sx   | ddd  dd}t|dkrR|\}}| dkr<|dksL| dkr^|d	kr^d }n|d
 }d }|d urt|d| 7 }|S )N@r   :rD   http80https443r   )rX   rW   )r#   rd   r1   r6   r   r   r   _normalize_netloc  s    z,extract_path_info.<locals>._normalize_netlocT)r   N   )rh   rj   rU   )rH   rI   rJ   strr   
isinstancedictr0   r   r   rstrip
startswithrW   rV   )ra   rb   rO   rP   rc   rl   r)   Zbase_iriZbase_schemeZbase_netloc	base_pathZ
cur_schemeZ
cur_netlocZcur_pathr#   r   r   r   extract_path_info[  s4    1





rt   c                	   @   s~   e Zd ZdZdeje ejejej	g df ejej	g df  f  ddddZ
d dddZedd	d
ZddddZdS )ClosingIteratoraA  The WSGI specification requires that all middlewares and gateways
    respect the `close` callback of the iterable returned by the application.
    Because it is useful to add another close action to a returned iterable
    and adding a custom iterable is a boring task this class can be used for
    that::

        return ClosingIterator(app(environ, start_response), [cleanup_session,
                                                              cleanup_locals])

    If there is just one close function it can be passed instead of the list.

    A closing iterator is not needed if the application uses response objects
    and finishes the processing if the response is started::

        try:
            return response(environ, start_response)
        finally:
            cleanup_session()
            cleanup_locals()
    N)iterable	callbacksr   c                 C   sr   t |}ttjg tf tt|| _|d u r4g }nt|rD|g}nt	|}t
|dd }|rh|d| || _d S )Ncloser   )iterr:   r;   Callabler=   r   next_nextcallablelistgetattrinsert
_callbacks)selfrv   rw   iteratorZiterable_closer   r   r   __init__  s    zClosingIterator.__init__r   c                 C   s   | S Nr   r   r   r   r   __iter__  s    zClosingIterator.__iter__c                 C   s   |   S r   )r|   r   r   r   r   __next__  s    zClosingIterator.__next__c                 C   s   | j D ]
}|  qd S r   )r   )r   callbackr   r   r   rx     s    
zClosingIterator.close)N)__name__
__module____qualname____doc__r:   Iterabler=   OptionalUnionrz   r   r   r   rx   r   r   r   r   ru     s    &ru       )r   filebuffer_sizer   c                 C   s   |  dt||S )a  Wraps a file.  This uses the WSGI server's file wrapper if available
    or otherwise the generic :class:`FileWrapper`.

    .. versionadded:: 0.5

    If the file wrapper from the WSGI server is used it's important to not
    iterate over it from inside the application but to pass it through
    unchanged.  If you want to pass out a file wrapper inside a response
    object you have to set :attr:`Response.direct_passthrough` to `True`.

    More information about file wrappers are available in :pep:`333`.

    :param file: a :class:`file`-like object with a :meth:`~file.read` method.
    :param buffer_size: number of bytes for one iteration.
    zwsgi.file_wrapper)r-   FileWrapper)r   r   r   r   r   r   	wrap_file  s    
r   c                   @   s   e Zd ZdZdeje eddddZdddd	Z	e
dd
dZejddddZeje dddZd dddZedddZdS )r   a\  This class can be used to convert a :class:`file`-like object into
    an iterable.  It yields `buffer_size` blocks until the file is fully
    read.

    You should not use this class directly but rather use the
    :func:`wrap_file` function that uses the WSGI server's file wrapper
    support if it's available.

    .. versionadded:: 0.5

    If you're using this object together with a :class:`Response` you have
    to use the `direct_passthrough` mode.

    :param file: a :class:`file`-like object with a :meth:`~file.read` method.
    :param buffer_size: number of bytes for one iteration.
    r   N)r   r   r   c                 C   s   || _ || _d S r   )r   r   )r   r   r   r   r   r   r   $  s    zFileWrapper.__init__r   c                 C   s   t | jdr| j  d S Nrx   )hasattrr   rx   r   r   r   r   rx   (  s    zFileWrapper.closec                 C   s*   t | jdr| j S t | jdr&dS dS )NseekableseekTF)r   r   r   r   r   r   r   r   ,  s
    
zFileWrapper.seekable)argsr   c                 G   s   t | jdr| jj|  d S )Nr   )r   r   r   )r   r   r   r   r   r   3  s    zFileWrapper.seekc                 C   s   t | jdr| j S d S )Ntell)r   r   r   r   r   r   r   r   7  s    
zFileWrapper.tellc                 C   s   | S r   r   r   r   r   r   r   <  s    zFileWrapper.__iter__c                 C   s    | j | j}|r|S t d S r   )r   readr   StopIteration)r   datar   r   r   r   ?  s    zFileWrapper.__next__)r   )r   r   r   r   r:   r<   r=   r2   r   rx   boolr   Anyr   r   r   r   r   r   r   r   r   r     s   r   c                   @   s   e Zd ZdZdejeje eje f e	ej
e	 dddZd ddd	Zedd
dZejej
e e	f dddZedddZedddZddddZdS )_RangeWrapperas  This class can be used to convert an iterable object into
    an iterable that will only yield a piece of the underlying content.
    It yields blocks until the underlying stream range is fully read.
    The yielded blocks will have a size that can't exceed the original
    iterator defined block size, but that can be smaller.

    If you're using this object together with a :class:`Response` you have
    to use the `direct_passthrough` mode.

    :param iterable: an iterable object with a :meth:`__next__` method.
    :param start_byte: byte from which read will start.
    :param byte_range: how many bytes to read.
    r   N)rv   
start_byte
byte_rangec                 C   sR   t || _|| _|| _d | _|d ur.|| | _d| _t|doD| | _d| _d S )Nr   r   F)	ry   rv   r   r   end_byteread_lengthr   r   end_reached)r   rv   r   r   r   r   r   r   W  s    

z_RangeWrapper.__init__r   c                 C   s   | S r   r   r   r   r   r   r   k  s    z_RangeWrapper.__iter__c                 C   sB   z"t | j}|  jt|7  _|W S  ty<   d| _ Y n0 d S NT)r{   rv   r   rW   r   r   r   chunkr   r   r   _next_chunkn  s    
z_RangeWrapper._next_chunkc                 C   sl   d }| j r,| j| j | j | _| j}n8| j| jkrB|  }q,|d ur^|| j| j d  }| j}||fS r   )r   rv   r   r   r   r   r   r   r   Zcontextual_read_lengthr   r   r   _first_iterationw  s    
z_RangeWrapper._first_iterationc                 C   sn   | j rt d }| j}| jdkr,|  \}}|d u r<|  }| jd urj| j| jkrjd| _ |d | j|  S |S )Nr   T)r   r   r   r   r   r   r   r   r   r   r|     s    
z_RangeWrapper._nextc                 C   s    |   }|r|S d| _t d S r   )r|   r   r   r   r   r   r   r     s
    z_RangeWrapper.__next__c                 C   s   t | jdr| j  d S r   )r   rv   rx   r   r   r   r   rx     s    z_RangeWrapper.close)r   N)r   r   r   r   r:   r   r   r=   r<   r2   r   r   r   r   Tupler   r|   r   rx   r   r   r   r   r   F  s     	r   )rA   limitr   r   c                 c   s   t | tttfrtdt| ds:| D ]}|r&|V  q&dS ttjt | } t | t	sv|durvttjt t	| |} | j
}||}|sq|V  q|dS )z-Helper for the line and chunk iter functions.zBPassed a string or byte object instead of true iterator or stream.r   N)ro   r=   	bytearrayrn   r3   r   r:   r;   r<   r@   r   )rA   r   r   item_readr   r   r   _make_chunk_iter  s"    
r    (  )rA   r   r   cap_at_bufferr   c                 #   s   t | | t d}|sdS t|}tt|dtt|d}tt|d}tt|dttjt t|f  tjt d fdd}}	| D ]6}
|
|kr|	d	d |kr|	|
7 }	}
|	r|	V  |
}	q|	r|	V  dS )
a  Safely iterates line-based over an input stream.  If the input stream
    is not a :class:`LimitedStream` the `limit` parameter is mandatory.

    This uses the stream's :meth:`~file.read` method internally as opposite
    to the :meth:`~file.readline` method that is unsafe and can only be used
    in violation of the WSGI specification.  The same problem applies to the
    `__iter__` function of the input stream which calls :meth:`~file.readline`
    without arguments.

    If you need line-by-line processing it's strongly recommended to iterate
    over the input stream using this helper function.

    .. versionchanged:: 0.8
       This function now ensures that the limit was reached.

    .. versionadded:: 0.9
       added support for iterators as input stream.

    .. versionadded:: 0.11.10
       added support for the `cap_at_buffer` parameter.

    :param stream: the stream or iterate to iterate over.
    :param limit: the limit in bytes for the stream.  (Usually
                  content length.  Not necessary if the `stream`
                  is a :class:`LimitedStream`.
    :param buffer_size: The optional buffer size.
    :param cap_at_buffer: if this is set chunks are split if they are longer
                          than the buffer size.  Internally this is implemented
                          that the buffer size might be exhausted by a factor
                          of two however.
    r&   N
z
r   c                  3   s   j } g }t d}|sqg }d}ttjt t||dD ]}|| |t	|7 }|r~|dd  v r~| |V  g }q@r@|kr@| |}t	|kr|d  V  |d  }q|g}q@|}q
|r| |V  d S )Nr&   r   Trf   )
joinr{   r:   r;   Iteratorr=   r   
splitlinesappendrW   )_joinbuffernew_datanew_bufbuf_sizer   r[   _iterr   r   Zcrlfemptyr   r   _iter_basic_lines  s0    


z)make_line_iter.<locals>._iter_basic_linesrf   )r   r{   r   r:   r;   r=   r   r   )rA   r   r   r   
first_itemscrlfr   previousr   r   r   r   make_line_iter  s*    %
 
r   )rA   	separatorr   r   r   r   c                 c   sd  t | ||}t|d}|sdS ttjt t|f|}t|trlt	|}t
dt
| dj}dj}n(t|}t
dt
| d j}dj}g }	t|d}
|
sqP||
}g }d}t|	|D ]}||kr||V  g }d}q|t|7 }|| |r||kr||}t||kr:|d| V  ||d }q|g}t|}q|}	q|	r`||	V  dS )	a  Works like :func:`make_line_iter` but accepts a separator
    which divides chunks.  If you want newline based processing
    you should use :func:`make_line_iter` instead as it
    supports arbitrary newline markers.

    .. versionadded:: 0.8

    .. versionadded:: 0.9
       added support for iterators as input stream.

    .. versionadded:: 0.11.10
       added support for the `cap_at_buffer` parameter.

    :param stream: the stream or iterate to iterate over.
    :param separator: the separator that divides chunks.
    :param limit: the limit in bytes for the stream.  (Usually
                  content length.  Not necessary if the `stream`
                  is otherwise already limited).
    :param buffer_size: The optional buffer size.
    :param cap_at_buffer: if this is set chunks are split if they are longer
                          than the buffer size.  Internally this is implemented
                          that the buffer size might be exhausted by a factor
                          of two however.
    r   N()r&      (   )r   )r   r{   r:   r;   r   r=   r   ro   rn   r	   recompileescaperX   r   r   rW   r   )rA   r   r   r   r   r   r   _splitr   r   r   chunksr   r   r   r[   r   r   r   make_chunk_iter  sH    





r   c                   @   s   e Zd ZdZeje eddddZd dddZ	e
edd	d
ZedddZedddZd eddddZd!eje edddZd"eje edddZd#eje eje dddZedddZedddZedddZdS )$r@   a  Wraps a stream so that it doesn't read more than n bytes.  If the
    stream is exhausted and the caller tries to get more bytes from it
    :func:`on_exhausted` is called which by default returns an empty
    string.  The return value of that function is forwarded
    to the reader function.  So if it returns an empty string
    :meth:`read` will return an empty string as well.

    The limit however must never be higher than what the stream can
    output.  Otherwise :meth:`readlines` will try to read past the
    limit.

    .. admonition:: Note on WSGI compliance

       calls to :meth:`readline` and :meth:`readlines` are not
       WSGI compliant because it passes a size argument to the
       readline methods.  Unfortunately the WSGI PEP is not safely
       implementable without a size argument to :meth:`readline`
       because there is no EOF marker in the stream.  As a result
       of that the use of :meth:`readline` is discouraged.

       For the same reason iterating over the :class:`LimitedStream`
       is not portable.  It internally calls :meth:`readline`.

       We strongly suggest using :meth:`read` only or using the
       :func:`make_line_iter` which safely iterates line-based
       over a WSGI input stream.

    :param stream: the stream to wrap.
    :param limit: the limit for the stream, must not be longer than
                  what the string can provide if the stream does not
                  end with `EOF` (like `wsgi.input`)
    N)rA   r   r   c                 C   s    |j | _|j| _d| _|| _d S )Nr   )r   r   readline	_readline_posr   )r   rA   r   r   r   r   r     s    zLimitedStream.__init__r   c                 C   s   | S r   r   r   r   r   r   r     s    zLimitedStream.__iter__c                 C   s   | j | jkS )z4If the stream is exhausted this attribute is `True`.)r   r   r   r   r   r   is_exhausted  s    zLimitedStream.is_exhaustedc                 C   s
   |  dS )zThis is called when the stream tries to read past the limit.
        The return value of this function is returned from the reading
        function.
        r   )r   r   r   r   r   on_exhausted  s    zLimitedStream.on_exhaustedc                 C   s   ddl m} | dS )a  What should happen if a disconnect is detected?  The return
        value of this function is returned from read functions in case
        the client went away.  By default a
        :exc:`~werkzeug.exceptions.ClientDisconnected` exception is raised.
        r   )ClientDisconnectedN)
exceptionsr   )r   r   r   r   r   on_disconnect  s    zLimitedStream.on_disconnect   )
chunk_sizer   c                 C   s:   | j | j }|}|dkr6t||}| | ||8 }qdS )a  Exhaust the stream.  This consumes all the data left until the
        limit is reached.

        :param chunk_size: the size for a chunk.  It will read the chunk
                           until the stream is exhausted and throw away
                           the results.
        r   N)r   r   minr   )r   r   to_readr   r   r   r   exhaust  s    

zLimitedStream.exhaust)sizer   c              	   C   s   | j | jkr|  S |du s$|dkr*| j}t| j| j  |}z| |}W n ttfyh   |   Y S 0 |rt||kr|  S |  j t|7  _ |S )zyRead `size` bytes or if size is not provided everything is read.

        :param size: the number of bytes read.
        Nrf   )	r   r   r   r   r   OSErrorr4   r   rW   )r   r   r   r   r   r   r   r     s    zLimitedStream.readc              	   C   s   | j | jkr|  S |du r*| j| j  }nt|| j| j  }z| |}W n ttfyh   |   Y S 0 |rz|sz|  S |  j t|7  _ |S )zReads one line from the stream.N)	r   r   r   r   r   r4   r   r   rW   )r   r   liner   r   r   r     s    zLimitedStream.readlinec                 C   sp   | j }g }|dur$t| j|| }n| j}|dur@||| j  8 }| j |krLql|| | |dur*| j }q*|S )zReads a file into a list of strings.  It calls :meth:`readline`
        until the file is read to the end.  It does support the optional
        `size` argument if the underlying stream supports it for
        `readline`.
        N)r   r   r   r   r   )r   r   Zlast_posresultendr   r   r   	readlines  s    
zLimitedStream.readlinesc                 C   s   | j S )zKReturns the position of the stream.

        .. versionadded:: 0.9
        )r   r   r   r   r   r     s    zLimitedStream.tellc                 C   s   |   }|st |S r   )r   r   )r   r   r   r   r   r     s    zLimitedStream.__next__c                 C   s   dS r   r   r   r   r   r   readable  s    zLimitedStream.readable)r   )N)N)N)r   r   r   r   r:   r<   r=   r2   r   r   propertyr   r   r   r   r   r   r   r   Listr   r   r   r   r   r   r   r   r@   b  s   !	
r@   )FFFN)N)T)rM   rN   )rM   rN   )rM   rN   )rM   rN   )rM   r`   T)r   )Nr   F)Nr   F)=r>   r   typingr:   rH   	functoolsr   r   	itertoolsr   	_internalr   r   r	   Zsansior
   r/   Zsansio.utilsr   urlsr   r   r   r   r   TYPE_CHECKINGZ_typeshed.wsgir   r   rz   r   r   r   r   rn   r0   r   r2   r7   r,   r8   r<   r=   rC   rL   rS   rT   r]   r_   r   rt   ru   r   r   r   r   r   r   r   IOBaser@   r   r   r   r   <module>   s       '  &   D +   k6 4Z   _   M