a
    -=ic                  A   @   s  d dl Z d dlZ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 ddlmZ ddlmZ ddlmZ ddlmZ ejrd dl m!Z! e"dej#Z$e%dZ&e"dZ'ej"dej#dZ(e"dZ)e%g dZ*e%g dZ+dddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]@Z,G d^d_ d_eZ-G d`da daeZ.dej/e0e1f e0e2e0dddedfZ3de0e2e0dhdidjZ4ej5e0 ej6e0ej5ej/e0e1f  f e0dkdldmZ7dej/ej8e0ej/e0e1f f ej9e0 f e2e0dndodpZ:dqe0drdsdtZ;e0ej<e0 dudvdwZ=e>fe0ej?e> ej8e0e0f dxdydzZ@ej5e0 ejAe0ej8e0e0f f dud{d|ZBejCd}d~dZDejEej5e0 d~duddZFejEej5e0 ej?eD eDdxddZFdej5e0 ej5ej?eD  eDdxddZFejCdddZGej5ejHeGgdf  ZIejEdej5e0 eIdddddZJejEej5e0 eIej?eG eGdddZJdej5e0 eIej5ej?eG  eGdddZJejCddqdZKej5ejHeKgdf  ZLejEdej5e0 eLddqdddZMejEej5e0 eLej?eK eKdddZMdej5e0 eLej5ej?eK  eKdddZMdej5e0 ej5ejHdgdf  ddddZNej5e0 ej5d duddZOdej5e0 ej5ejHdgdf  ddddZPej5e0 dduddZQdej5e0 e2ej5d dddZRdej5e0 ej5ejHdgdf  ej5d dddZSde0e2e0dddZTej5e0 ej/ejAe0e2f ejAd f dddZUej5e0 dduddZVeWe0dddZXej5e0 ej5e duddZYdej5ej/eee1eZef  e0dddZ[dej5e0 ej5e
 duddZ\dej5ej/e
e1f  ej5e0 dddZ]ddej5e0 ej5eW ej5ej/ee0f  e2e2dddZ^dej/dej<ejAe0e0f  f ej9e0 ddddĄZ_ej/dej<ejAe0e0f  f ddŜddǄZ`e0e2drddɄZae0e2drdd˄Zbdej/de0eWdf e0e0ej5ej?d  ddМdd҄Zcde0ej/eWe0f ej5ej/e
e1f  ej5ej/e0ee1eZf  ej5e0 ej5e0 e2e2e0e2e1ej5e0 e0d՜ddׄZdej5e1 ej5e1 ej5e1 e2d؜ddڄZeddlfmgZh ddlimjZk dS )    Ndate)datetime)time)	timedelta)timezone)Enum)sha1)mktime)struct_time)unquote_to_bytes)parse_http_list   )_cookie_quote)
_dt_as_utc)_make_cookie_domain)	_to_bytes)_to_str)_wsgi_decoding_dance)WSGIEnvironmenta  
    (                       # media-range capturing-parenthesis
      [^\s;,]+              # type/subtype
      (?:[ \t]*;[ \t]*      # ";"
        (?:                 # parameter non-capturing-parenthesis
          [^\s;,q][^\s;,]*  # token that doesn't start with "q"
        |                   # or
          q[^\s;,=][^\s;,]* # token that is more than just "q"
        )
      )*                    # zero or more parameters
    )                       # end of media-range
    (?:[ \t]*;[ \t]*q=      # weight is a "q" parameter
      (\d*(?:\.\d+)?)       # qvalue capturing-parentheses
      [^,]*                 # "extension" accept params: who cares?
    )?                      # accept params are optional
    zM!#$%&'*+-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ^_`abcdefghijklmnopqrstuvwxyz|~z&([Ww]/)?(?:"(.*?)"|(.*?))(?:\s*,\s*|$)a  
    ;\s*,?\s*  # newlines were replaced with commas
    (?P<key>
        "[^"\\]*(?:\\.[^"\\]*)*"  # quoted string
    |
        [^\s;,=*]+  # token
    )
    (?:\*(?P<count>\d+))?  # *1, optional continuation index
    \s*
    (?:  # optionally followed by =value
        (?:  # equals sign, possibly with encoding
            \*\s*=\s*  # * indicates extended notation
            (?:  # optional encoding
                (?P<encoding>[^\s]+?)
                '(?P<language>[^\s]*?)'
            )?
        |
            =\s*  # basic notation
        )
        (?P<value>
            "[^"\\]*(?:\\.[^"\\]*)*"  # quoted string
        |
            [^;,]+  # token
        )?
    )?
    \s*
    )flagsz,\s*([^;,\s]+)([;,]\s*.+)?)
Zallowzcontent-encodingzcontent-languagezcontent-lengthcontent-locationzcontent-md5zcontent-rangezcontent-typeexpireszlast-modified)
connectionz
keep-alivezproxy-authenticatezproxy-authorizationtetrailerztransfer-encodingupgradeContinuezSwitching Protocols
ProcessingzEarly HintsOKCreatedAcceptedzNon Authoritative Informationz
No ContentzReset ContentzPartial ContentzMulti StatuszAlready ReportedzIM UsedzMultiple ChoiceszMoved PermanentlyFoundz	See OtherzNot Modifiedz	Use ProxyzSwitch ProxyzTemporary RedirectzPermanent RedirectzBad RequestUnauthorizedzPayment Required	Forbiddenz	Not FoundzMethod Not AllowedzNot AcceptablezProxy Authentication RequiredzRequest TimeoutConflictGonezLength RequiredzPrecondition FailedzRequest Entity Too LargezRequest URI Too LongzUnsupported Media TypezRequested Range Not SatisfiablezExpectation FailedzI'm a teapotzMisdirected RequestzUnprocessable EntityLockedzFailed Dependencyz	Too EarlyzUpgrade RequiredzPrecondition RequiredzToo Many RequestszRequest Header Fields Too Largez
Retry WithzUnavailable For Legal ReasonszInternal Server ErrorzNot ImplementedzBad GatewayzService UnavailablezGateway TimeoutzHTTP Version Not SupportedzVariant Also NegotiateszInsufficient StoragezLoop DetectedzNot ExtendedzNetwork Authentication Failed)@d   e   f   g                                 i,  i-  i.  i/  i0  i1  i2  i3  i4  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  c                   @   s   e Zd ZdZdZdZdS )COEPzCross Origin Embedder Policiesunsafe-nonezrequire-corpN)__name__
__module____qualname____doc__UNSAFE_NONEZREQUIRE_CORP r=   r=   ^/home/droni/.local/share/virtualenvs/DPS-5Je3_V2c/lib/python3.9/site-packages/werkzeug/http.pyr6      s   r6   c                   @   s   e Zd ZdZdZdZdZdS )COOPzCross Origin Opener Policiesr7   zsame-origin-allow-popupszsame-originN)r8   r9   r:   r;   r<   ZSAME_ORIGIN_ALLOW_POPUPSZSAME_ORIGINr=   r=   r=   r>   r?      s   r?    T)valueextra_charsallow_tokenreturnc                 C   s^   t | tr| d} t| } |r>tt|B }t| |r>| S | dddd} d|  dS )a  Quote a header value if necessary.

    .. versionadded:: 0.5

    :param value: the value to quote.
    :param extra_chars: a list of extra characters to skip quoting.
    :param allow_token: if this is enabled token values are returned
                        unchanged.
    latin1\\\"\")
isinstancebytesdecodestr_token_charssetissubsetreplace)rA   rB   rC   Ztoken_charsr=   r=   r>   quote_header_value   s    

rR   F)rA   is_filenamerD   c                 C   s\   | rX| d | d   kr dkrXn n4| dd } |rD| dd dkrX|  dd d	dS | S )
a3  Unquotes a header value.  (Reversal of :func:`quote_header_value`).
    This does not use the real unquoting but what browsers are actually
    using for quoting.

    .. versionadded:: 0.5

    :param value: the header value to unquote.
    :param is_filename: The value represents a filename or path.
    r   rH   r   N   rG   rF   rI   )rQ   )rA   rS   r=   r=   r>   unquote_header_value   s
    
$rV   )headeroptionsrD   c                 C   s^   g }| dur| |  | D ]4\}}|du r:| | q| | dt|  qd|S )zThe reverse function to :func:`parse_options_header`.

    :param header: the header to dump
    :param options: a dict of options to append.
    N=; )appenditemsrR   join)rW   rX   segmentskeyrA   r=   r=   r>   dump_options_header   s    
r`   )iterablerC   rD   c              	      sn   t | trRg }|  D ]8\}}|du r2|| q|| dt| d  qn fdd| D }d|S )aJ  Dump an HTTP header again.  This is the reversal of
    :func:`parse_list_header`, :func:`parse_set_header` and
    :func:`parse_dict_header`.  This also quotes strings that include an
    equals sign unless you pass it as dict of key, value pairs.

    >>> dump_header({'foo': 'bar baz'})
    'foo="bar baz"'
    >>> dump_header(('foo', 'bar baz'))
    'foo, "bar baz"'

    :param iterable: the iterable or dict of values to quote.
    :param allow_token: if set to `False` tokens as values are disallowed.
                        See :func:`quote_header_value` for more details.
    NrY   rC   c                    s   g | ]}t | d qS )rb   )rR   .0xrb   r=   r>   
<listcomp>"      zdump_header.<locals>.<listcomp>z, )rJ   dictr\   r[   rR   r]   )ra   rC   r\   r_   rA   r=   rb   r>   dump_header  s    
ri   zds.ContentSecurityPolicy)rW   rD   c                 C   s   d dd |  D S )zDump a Content Security Policy header.

    These are structured into policies such as "default-src 'self';
    script-src 'self'".

    .. versionadded:: 1.0.0
       Support for Content Security Policy headers was added.

    rZ   c                 s   s    | ]\}}| d | V  qdS ) Nr=   rd   r_   rA   r=   r=   r>   	<genexpr>0  rg   z"dump_csp_header.<locals>.<genexpr>)r]   r\   rW   r=   r=   r>   dump_csp_header&  s    
rn   )rA   rD   c                 C   sX   g }t | D ]F}|dd |dd   kr4dkrHn nt|dd }|| q|S )a  Parse lists as described by RFC 2068 Section 2.

    In particular, parse comma-separated lists where the elements of
    the list may include quoted-strings.  A quoted-string could
    contain a comma.  A non-quoted string could have quotes in the
    middle.  Quotes are removed automatically after parsing.

    It basically works like :func:`parse_set_header` just that items
    may appear multiple times and case sensitivity is preserved.

    The return value is a standard :class:`list`:

    >>> parse_list_header('token, "quoted value"')
    ['token', 'quoted value']

    To create a header from the :class:`list` again, use the
    :func:`dump_header` function.

    :param value: a string with a list header.
    :return: :class:`list`
    Nr   rT   rH   )_parse_list_headerrV   r[   )rA   resultitemr=   r=   r>   parse_list_header3  s    (rr   )rA   clsrD   c                 C   s   | }t | tr| d} t| D ]f}d|vr8d||< q"|dd\}} | dd | dd   krldkrn nt| dd } | ||< q"|S )aK  Parse lists of key, value pairs as described by RFC 2068 Section 2 and
    convert them into a python dict (or any other mapping object created from
    the type with a dict like interface provided by the `cls` argument):

    >>> d = parse_dict_header('foo="is a fish", bar="as well"')
    >>> type(d) is dict
    True
    >>> sorted(d.items())
    [('bar', 'as well'), ('foo', 'is a fish')]

    If there is no value for a key it will be `None`:

    >>> parse_dict_header('key_without_value')
    {'key_without_value': None}

    To create a header from the :class:`dict` again, use the
    :func:`dump_header` function.

    .. versionchanged:: 0.9
       Added support for `cls` argument.

    :param value: a string with a dict header.
    :param cls: callable to use for storage of parsed results.
    :return: an instance of `cls`
    rE   rY   Nr   rT   rH   )rJ   rK   rL   ro   splitrV   )rA   rs   rp   rq   namer=   r=   r>   parse_dict_headerQ  s    

(
rv   c                 C   s6  | sdi fS g }d|  dd } | r t| }|s8q ||d i }|d}d}|rt|}|srq| \}}}	}
}|sd}n|	s|}	|	}t| }|durt||dk}|	durt	|
|	}|r|dur||d| ||< n|||< || d }qZ|| t|S |r.t|S di fS )a  Parse a ``Content-Type``-like header into a tuple with the
    value and any options:

    >>> parse_options_header('text/html; charset=utf8')
    ('text/html', {'charset': 'utf8'})

    This should is not for ``Cache-Control``-like headers, which use a
    different format. For those, use :func:`parse_dict_header`.

    :param value: The header value to parse.

    .. versionchanged:: 2.2
        Option names are always converted to lowercase.

    .. versionchanged:: 2.1
        The ``multiple`` parameter is deprecated and will be removed in
        Werkzeug 2.2.

    .. versionchanged:: 0.15
        :rfc:`2231` parameter continuations are handled.

    .. versionadded:: 0.5
    r@   ,
r   rU   Nfilename)rQ   _option_header_start_mime_typematchr[   group_option_header_piece_regroupsrV   lower_unquoterL   getendtuple)rA   rp   r{   rX   restZcontinued_encodingZoptmatchoptioncountencodinglanguageZoption_valuer=   r=   r>   parse_options_headery  sF    



r   _TAnyAcceptz	ds.Accept)boundc                 C   s   d S Nr=   )rA   r=   r=   r>   parse_accept_header  s    r   c                 C   s   d S r   r=   )rA   rs   r=   r=   r>   r     s    c                 C   s   |du rt t jt tj}| s(|dS g }t| D ]@}|d}|sNd}nt	t
t|dd}||d|f q6||S )a  Parses an HTTP Accept-* header.  This does not implement a complete
    valid algorithm but one that supports at least value and quality
    extraction.

    Returns a new :class:`Accept` object (basically a list of ``(value, quality)``
    tuples sorted by the quality with some additional accessor methods).

    The second parameter can be a subclass of :class:`Accept` that is created
    with the parsed values and returned.

    :param value: the accept header string to be parsed.
    :param cls: the wrapper class for the return value (can be
                         :class:`Accept` or a subclass thereof)
    :return: an instance of `cls`.
    NrU   r   r   )tcastTyper   dsAccept
_accept_refinditerr|   maxminfloatr[   )rA   rs   rp   r{   Zquality_matchZqualityr=   r=   r>   r     s    
_TAnyCCzds._CacheControlzds.RequestCacheControl)rA   	on_updaters   rD   c                 C   s   d S r   r=   rA   r   rs   r=   r=   r>   parse_cache_control_header  s    r   c                 C   s   d S r   r=   r   r=   r=   r>   r     s    c                 C   s8   |du rt t jt tj}| s*|d|S |t| |S )a  Parse a cache control header.  The RFC differs between response and
    request cache control, this method does not.  It's your responsibility
    to not use the wrong control statements.

    .. versionadded:: 0.5
       The `cls` was added.  If not specified an immutable
       :class:`~werkzeug.datastructures.RequestCacheControl` is returned.

    :param value: a cache control header to be parsed.
    :param on_update: an optional callable that is called every time a value
                      on the :class:`~werkzeug.datastructures.CacheControl`
                      object is changed.
    :param cls: the class for the returned object.  By default
                :class:`~werkzeug.datastructures.RequestCacheControl` is used.
    :return: a `cls` object.
    Nr=   )r   r   r   r   r   ZRequestCacheControlrv   r   r=   r=   r>   r     s
    
_TAnyCSPc                 C   s   d S r   r=   r   r=   r=   r>   parse_csp_header.  s    r   c                 C   s   d S r   r=   r   r=   r=   r>   r   5  s    c                 C   s   |du rt t jt tj}| du r.|d|S g }| dD ]>}| }d|v r<| dd\}} || |  f q<|||S )a  Parse a Content Security Policy header.

    .. versionadded:: 1.0.0
       Support for Content Security Policy headers was added.

    :param value: a csp header to be parsed.
    :param on_update: an optional callable that is called every time a value
                      on the object is changed.
    :param cls: the class for the returned object.  By default
                :class:`~werkzeug.datastructures.ContentSecurityPolicy` is used.
    :return: a `cls` object.
    Nr=   ;rj   r   )	r   r   r   r   r   ZContentSecurityPolicyrt   stripr[   )rA   r   rs   r\   policy	directiver=   r=   r>   r   <  s    
zds.HeaderSet)rA   r   rD   c                 C   s    | st d|S t t| |S )a  Parse a set-like header and return a
    :class:`~werkzeug.datastructures.HeaderSet` object:

    >>> hs = parse_set_header('token, "quoted value"')

    The return value is an object that treats the items case-insensitively
    and keeps the order of the items:

    >>> 'TOKEN' in hs
    True
    >>> hs.index('quoted value')
    1
    >>> hs
    HeaderSet(['token', 'quoted value'])

    To create a header from the :class:`HeaderSet` again, use the
    :func:`dump_header` function.

    :param value: a set header to be parsed.
    :param on_update: an optional callable that is called every time a
                      value on the :class:`~werkzeug.datastructures.HeaderSet`
                      object is changed.
    :return: a :class:`~werkzeug.datastructures.HeaderSet`
    N)r   Z	HeaderSetrr   )rA   r   r=   r=   r>   parse_set_header`  s    r   zds.Authorizationc                 C   s  | sdS t | } z| dd\}}| }W n ty@   Y dS 0 |dkrzt|dd\}}W n tyx   Y dS 0 z tdt	|dt	|ddW S  t
y   Y dS 0 n\|dkrt|}dD ]}||vr dS qd	|v r|d
 r|dsdS td|S dS )aw  Parse an HTTP basic/digest authorization header transmitted by the web
    browser.  The return value is either `None` if the header was invalid or
    not given, otherwise an :class:`~werkzeug.datastructures.Authorization`
    object.

    :param value: the authorization header to parse.
    :return: a :class:`~werkzeug.datastructures.Authorization` object or `None`.
    Nr   basic   :utf-8)usernamepassworddigest)r   realmnonceuriresponseqopnccnonce)r   rt   r   
ValueErrorbase64	b64decode	Exceptionr   Authorizationr   UnicodeDecodeErrorrv   r   )rA   	auth_type	auth_infor   r   Zauth_mapr_   r=   r=   r>   parse_authorization_header  s@    


r   zds.WWWAuthenticatec              	   C   sl   | st j|dS z| dd\}}| }W n, ttfyX   t j|   |d Y S 0 t |t||S )a  Parse an HTTP WWW-Authenticate header into a
    :class:`~werkzeug.datastructures.WWWAuthenticate` object.

    :param value: a WWW-Authenticate header to parse.
    :param on_update: an optional callable that is called every time a value
                      on the :class:`~werkzeug.datastructures.WWWAuthenticate`
                      object is changed.
    :return: a :class:`~werkzeug.datastructures.WWWAuthenticate` object.
    r   Nr   )r   ZWWWAuthenticatert   r   r   AttributeErrorr   rv   )rA   r   r   r   r=   r=   r>   parse_www_authenticate_header  s    r   z
ds.IfRangec                 C   s:   | st  S t| }|dur(t j|dS t t| d S )zParses an if-range header which can be an etag or a date.  Returns
    a :class:`~werkzeug.datastructures.IfRange` object.

    .. versionchanged:: 2.0
        If the value represents a datetime, it is timezone-aware.

    .. versionadded:: 0.7
    Nr   r   )r   ZIfRange
parse_dateunquote_etag)rA   r   r=   r=   r>   parse_if_range_header  s    	r   zds.Range)rA   make_inclusiverD   c              	   C   s|  | rd| vrdS g }d}|  dd\}}|  }| dD ].}| }d|vrZ dS |dr|dk rr dS zt|}W n ty   Y  dS 0 d}d}nd|v r`| dd\}	}
|	 }	|
 }
zt|	}W n ty   Y  dS 0 ||k s|dk r dS |
rJzt|
d }W n ty6   Y  dS 0 ||krN dS nd}|dur\|nd}|||f q>t||S )a  Parses a range header into a :class:`~werkzeug.datastructures.Range`
    object.  If the header is missing or malformed `None` is returned.
    `ranges` is a list of ``(start, stop)`` tuples where the ranges are
    non-inclusive.

    .. versionadded:: 0.7
    rY   Nr   r   rw   -rT   )	rt   r   r   
startswithintr   r[   r   Range)rA   r   rangesZlast_endunitsrngrq   beginr   Z	begin_strZend_strr=   r=   r>   parse_range_header  sP    






r   zds.ContentRangec                 C   s  | du rdS z| pd  dd\}}W n ty<   Y dS 0 d|vrJdS |dd\}}|dkrhd}n"zt|}W n ty   Y dS 0 |dkrtj|dd||dS d|vrdS |dd\}}zt|}	t|d }
W n ty   Y dS 0 t|	|
|rtj||	|
||dS dS )a  Parses a range header into a
    :class:`~werkzeug.datastructures.ContentRange` object or `None` if
    parsing is not possible.

    .. versionadded:: 0.7

    :param value: a content range header to be parsed.
    :param on_update: an optional callable that is called every time a value
                      on the :class:`~werkzeug.datastructures.ContentRange`
                      object is changed.
    Nr@   r   /*r   r   )r   rt   r   r   r   ZContentRangeis_byte_range_valid)rA   r   r   Zrangedefr   Z
length_strlengthZ	start_strZstop_strstartstopr=   r=   r>   parse_content_range_header  s8    r   )etagweakrD   c                 C   s.   d| v rt dd|  d} |r*d|  } | S )ziQuote an etag.

    :param etag: the etag to quote.
    :param weak: set to `True` to tag it "weak".
    rH   zinvalid etagW/)r   r   r   r=   r=   r>   
quote_etagF  s    
r   NN)r   rD   c                 C   sj   | sdS |   } d}| dr.d}| dd } | dd | dd   krRd	krbn n| dd } | |fS )
zUnquote a single etag:

    >>> unquote_etag('W/"bar"')
    ('bar', True)
    >>> unquote_etag('"bar"')
    ('bar', False)

    :param etag: the etag identifier to unquote.
    :return: a ``(etag, weak)`` tuple.
    r   F)r   zw/TrU   Nr   rT   rH   )r   r   r   r=   r=   r>   r   T  s    
(r   zds.ETagsc           	      C   s   | st  S g }g }t| }d}||k rt| |}|du r>q| \}}}|dkr`t jddS |rh|}|rx|| n
|| | }q t ||S )zParse an etag header.

    :param value: the tag header to parse
    :return: an :class:`~werkzeug.datastructures.ETags` object.
    r   Nr   T)Zstar_tag)r   ZETagslen_etag_rer{   r~   r[   r   )	rA   strongr   r   posr{   Zis_weakquotedrawr=   r=   r>   parse_etagsm  s(    

r   )datarD   c                 C   s   t |  S )zGenerate an etag for some data.

    .. versionchanged:: 2.0
        Use SHA-1. MD5 may not be available in some environments.
    )r	   	hexdigest)r   r=   r=   r>   generate_etag  s    r   c              	   C   sR   | du rdS zt j| }W n ttfy4   Y dS 0 |jdu rN|jtjdS |S )aK  Parse an :rfc:`2822` date into a timezone-aware
    :class:`datetime.datetime` object, or ``None`` if parsing fails.

    This is a wrapper for :func:`email.utils.parsedate_to_datetime`. It
    returns ``None`` if parsing fails instead of raising an exception,
    and always returns a timezone-aware datetime object. If the string
    doesn't have timezone information, it is assumed to be UTC.

    :param value: A string with a supported date format.

    .. versionchanged:: 2.0
        Return a timezone-aware datetime object. Use
        ``email.utils.parsedate_to_datetime``.
    Ntzinfo)	emailutilsparsedate_to_datetime	TypeErrorr   r   rQ   r   utc)rA   dtr=   r=   r>   r     s    
r   )	timestamprD   c                 C   sd   t | trBt | ts*tj| t tjd} nt| } tj	j
| ddS t | trTt| } tj	j| ddS )a  Format a datetime object or timestamp into an :rfc:`2822` date
    string.

    This is a wrapper for :func:`email.utils.format_datetime`. It
    assumes naive datetime objects are in UTC instead of raising an
    exception.

    :param timestamp: The datetime or timestamp to format. Defaults to
        the current time.

    .. versionchanged:: 2.0
        Use ``email.utils.format_datetime``. Accept ``date`` objects.
    r   T)usegmt)rJ   r   r   combiner   r   r   r   r   r   format_datetimer   r
   
formatdate)r   r=   r=   r>   	http_date  s    


r   c                 C   s\   | sdS zt | }W n ty(   Y dS 0 |dk r6dS zt|dW S  tyV   Y dS 0 dS )zParses a base-10 integer count of seconds into a timedelta.

    If parsing fails, the return value is `None`.

    :param value: a string consisting of an integer represented in base-10
    :return: a :class:`datetime.timedelta` object or `None`.
    Nr   )seconds)r   r   r   OverflowError)rA   r   r=   r=   r>   	parse_age  s    r   )agerD   c                 C   sD   | du rdS t | tr$t|  } nt| } | dk r<tdt| S )zFormats the duration as a base-10 integer.

    :param age: should be an integer number of seconds,
                a :class:`datetime.timedelta` object, or,
                if the age is unknown, `None` (default).
    Nr   zage cannot be negative)rJ   r   r   total_secondsr   rM   )r   r=   r=   r>   dump_age  s    
r   r   )environr   r   last_modifiedignore_if_rangerD   c                 C   s:   t j| d| d| d| d| d||||d	S )a2  Convenience method for conditional requests.

    :param environ: the WSGI environment of the request to be checked.
    :param etag: the etag for the response for comparison.
    :param data: or alternatively the data of the response to automatically
                 generate an etag using :func:`generate_etag`.
    :param last_modified: an optional date of the last modification.
    :param ignore_if_range: If `False`, `If-Range` header will be taken into
                            account.
    :return: `True` if the resource was modified, otherwise `False`.

    .. versionchanged:: 2.0
        SHA-1 is used to generate an etag value for the data. MD5 may
        not be available in some environments.

    .. versionchanged:: 1.0.0
        The check is run for methods other than ``GET`` and ``HEAD``.
    Z
HTTP_RANGEZHTTP_IF_RANGEZHTTP_IF_MODIFIED_SINCEZHTTP_IF_NONE_MATCHZHTTP_IF_MATCH)	Z
http_rangeZhttp_if_rangeZhttp_if_modified_sinceZhttp_if_none_matchZhttp_if_matchr   r   r   r   )_sansio_httpis_resource_modifiedr   )r   r   r   r   r   r=   r=   r>   r     s    r   r   r   z
ds.Headers)headersallowedrD   c                    s,   dd  D   fdd| D | dd< dS )a  Remove all entity headers from a list or :class:`Headers` object.  This
    operation works in-place.  `Expires` and `Content-Location` headers are
    by default not removed.  The reason for this is :rfc:`2616` section
    10.3.5 which specifies some entity headers that should be sent.

    .. versionchanged:: 0.5
       added `allowed` parameter.

    :param headers: a list or :class:`Headers` object.
    :param allowed: a list of headers that should still be allowed even though
                    they are entity headers.
    c                 S   s   h | ]}|  qS r=   )r   rc   r=   r=   r>   	<setcomp>0  rg   z(remove_entity_headers.<locals>.<setcomp>c                    s,   g | ]$\}}t |r |  v r||fqS r=   )is_entity_headerr   rk   r   r=   r>   rf   1  s   z)remove_entity_headers.<locals>.<listcomp>Nr=   )r   r   r=   r   r>   remove_entity_headers   s    
r   )r   rD   c                 C   s   dd | D | dd< dS )zRemove all HTTP/1.1 "Hop-by-Hop" headers from a list or
    :class:`Headers` object.  This operation works in-place.

    .. versionadded:: 0.5

    :param headers: a list or :class:`Headers` object.
    c                 S   s    g | ]\}}t |s||fqS r=   )is_hop_by_hop_headerrk   r=   r=   r>   rf   B  s   z-remove_hop_by_hop_headers.<locals>.<listcomp>Nr=   )r   r=   r=   r>   remove_hop_by_hop_headers8  s    
r  c                 C   s   |   tv S )zCheck if a header is an entity header.

    .. versionadded:: 0.5

    :param header: the header to test.
    :return: `True` if it's an entity header, `False` otherwise.
    )r   _entity_headersrm   r=   r=   r>   r   G  s    r   c                 C   s   |   tv S )zCheck if a header is an HTTP/1.1 "Hop-by-Hop" header.

    .. versionadded:: 0.5

    :param header: the header to test.
    :return: `True` if it's an HTTP/1.1 "Hop-by-Hop" header, `False` otherwise.
    )r   _hop_by_hop_headersrm   r=   r=   r>   r   R  s    r   r   rQ   zds.MultiDictzds.MultiDict[str, str])rW   charseterrorsrs   rD   c                 C   s<   t | tr| dd}n| du r&d}n| }tj||||dS )a]  Parse a cookie from a string or WSGI environ.

    The same key can be provided multiple times, the values are stored
    in-order. The default :class:`MultiDict` will have the first value
    first, and all values can be retrieved with
    :meth:`MultiDict.getlist`.

    :param header: The cookie header as a string, or a WSGI environ dict
        with a ``HTTP_COOKIE`` key.
    :param charset: The charset for the cookie values.
    :param errors: The error behavior for the charset decoding.
    :param cls: A dict-like class to store the parsed cookies in.
        Defaults to :class:`MultiDict`.

    .. versionchanged:: 1.0.0
        Returns a :class:`MultiDict` instead of a
        ``TypeConversionDict``.

    .. versionchanged:: 0.5
       Returns a :class:`TypeConversionDict` instead of a regular dict.
       The ``cls`` parameter was added.
    ZHTTP_COOKIEr@   N)cookier  r  rs   )rJ   rh   r   r   parse_cookie)rW   r  r  rs   r  r=   r=   r>   r  ]  s    
r  r     )r_   rA   max_ager   pathdomainsecurehttponlyr  sync_expiresmax_sizesamesiterD   c                 C   s  t | |} t ||}|dur2ddlm} |||}t|}t|trPt| }|durlt|tst	|}n&|dur|	rt	t
jtjd | }|dur| }|dvrtd| d t| g}d|d	fd
|dfd|dfd|dfd|dfd|dfd|dffD ]\}}}|du r(|r || q |du r6q t|}t|ttfs\t t||}|rjt|}|d| 7 }|t| q d|}|d}t|}|
r||
krt|}tjd| |d| d||  d| d|
 ddd |S )a  Create a Set-Cookie header without the ``Set-Cookie`` prefix.

    The return value is usually restricted to ascii as the vast majority
    of values are properly escaped, but that is no guarantee. It's
    tunneled through latin1 as required by :pep:`3333`.

    The return value is not ASCII safe if the key contains unicode
    characters.  This is technically against the specification but
    happens in the wild.  It's strongly recommended to not use
    non-ASCII values for the keys.

    :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.  Additionally `timedelta` objects
                    are accepted, too.
    :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: Use this 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: 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 charset: the encoding for string values.
    :param sync_expires: automatically set expires if max_age is defined
                         but expires not.
    :param max_size: Warn if the final header value exceeds this size. The
        default, 4093, should be safely `supported by most browsers
        <cookie_>`_. Set to 0 to disable this check.
    :param samesite: Limits the scope of the cookie such that it will
        only be attached to requests if those requests are same-site.

    .. _`cookie`: http://browsercookielimits.squawky.net/

    .. versionchanged:: 1.0.0
        The string ``'None'`` is accepted for ``samesite``.
    Nr   )
iri_to_uri)tz>   ZLaxNoneZStrictz,SameSite must be 'Strict', 'Lax', or 'None'.   =s   DomainTs   ExpiresFs   Max-Ages   Secures   HttpOnlys   Paths   SameSites   ; rE   zThe z$ cookie is too large: the value was z bytes but the header required z! extra bytes. The final size was z bytes but the limit is z> bytes. Browsers may silently ignore cookies larger than this.rU   )
stacklevel)r   urlsr  r   rJ   r   r   r   rM   r   r   nowr   r   r   titler   r   r[   	bytearrayrK   r]   rL   r   warningswarn)r_   rA   r	  r   r
  r  r  r  r  r  r  r  r  bufkvqtmprvZcookie_sizeZ
value_sizer=   r=   r>   dump_cookie  sr    7





	




	r"  )r   r   r   rD   c                 C   sp   | du |du krdS | du r,|du p*|dkS |du rLd|   koF|k S   S | |krXdS d|   koj|k S   S )zcChecks if a given byte content range is valid for the given length.

    .. versionadded:: 0.7
    NFr   r=   )r   r   r   r=   r=   r>   r     s    r   )datastructures)http)r@   T)F)T)N)N)NN)N)NN)N)N)T)N)F)N)N)N)NNNT)r   )r   rQ   N)r@   NNr   NFFr   Tr  N)lr   email.utilsr   retypingr   r  r   r   r   r   r   enumr   hashlibr	   r
   r   urllib.parser   r   Zurllib.requestr   ro   	_internalr   r   r   r   r   r   TYPE_CHECKINGZ_typeshed.wsgir   compileVERBOSEr   	frozensetrN   r   r}   rz   r  r  ZHTTP_STATUS_CODESr6   r?   UnionrM   r   boolrR   rV   OptionalMappingr`   DictIterableri   rn   Listrr   rh   r   rv   Tupler   TypeVarr   overloadr   r   CallableZ_t_cc_updater   r   Z_t_csp_updater   r   r   r   r   r   r   r   r   r   rK   r   r   r   r   r   r   r   r   r  r   r   r  r"  r   r@   r#  r   Zsansior$  r   r=   r=   r=   r>   <module>   s>  

D	 $ & &(*O #      & "0  
= 3	  (    (    *            