
_c                 @   s  d  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 y d d l m Z Wn" e k
 rbd d l m Z Yn Xy$ d d l m Z d d l m Z  Wn2 e k
 rd d l! m Z d d l! m" Z  Yn Xd Z# d Z$ e j% d e j&  Z' e( d  Z) e j% d  Z* e+ d  Z, e j% d d e j& Z- e j% d   Z. e( d! d" d# d$ d% d& d' d( d) d* g
  Z/ e( d+ d, d- d. d/ d0 d1 d2 g  Z0 d3 d4 d5 d6 d7 d8 d9 d: d; d< d= d> d? d@ dA dB dC dD dE dF dG dH dI dJ dK dL dM dN dO dP dQ dR dS dT dU dV dW dX dY dZ d[ d\ d] d^ d_ d` da db dc dd de df dg dh di dj dk dl dm dn do dp dq dr ds dt du dv dw dx dy dz d{ d| d} d~ d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d i@ Z1 d d   Z2 d d   Z3 d d d d  Z4 d d d  Z5 d d   Z6 d d d  Z7 d d   Z8 d d   Z9 e: d d  Z; d d d  Z< d d d  Z= d d d d  Z> d d d d  Z? d d d  Z@ d d   ZA d d d  ZB d d   ZC d d d  ZD d d d  ZE d d d  ZF d d   ZG d d   ZH d d   ZI d d   ZJ d d   ZK d d d  ZL d d d  ZM d d d  ZN d d d  ZO d d d d d d  ZP dd d  ZQ d d   ZR d d   ZS d d   ZT d d d d d  ZU d d d d d d d d d d d d d  ZV dd  ZW d dlX mY ZY d dlX mZ ZZ d dlX m[ Z[ d dlX m\ Z\ d dlX m] Z] d dlX m^ Z^ d d	lX m_ Z_ d d
lX m` Z` d dlX ma Za d dlX mb Zb d dlX mc Zc d S(  a"  
    werkzeug.http
    ~~~~~~~~~~~~~

    Werkzeug comes with a bunch of utilities that help Werkzeug to deal with
    HTTP data.  Most of the classes and functions provided by this module are
    used by the wrappers, but they are useful on their own, too, especially if
    the response and request objects are not used.

    This covers some of the more HTTP centric features of WSGI, some other
    utilities such as cookie handling are documented in the `werkzeug.utils`
    module.


    :copyright: 2007 Pallets
    :license: BSD-3-Clause
    N)datetime)	timedelta)md5)gmtime)time   )integer_types)	iteritems)PY2)string_types)	text_type)to_bytes)
to_unicode)try_coerce_native)_cookie_parse_impl)_cookie_quote)_make_cookie_domain)parsedate_tz)parse_http_list)unquote_to_bytes)unquotelatin1zutf-8a  
    (                       # 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*|$)z()<>@,;:"/[]?={} 	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upgraded   Continuee   zSwitching Protocolsf   
Processingg   zEarly Hints   OK   Created   Accepted   zNon Authoritative Information   z
No Content   zReset Content   zPartial Content   zMulti Status   zAlready Reported   zIM Usedi,  zMultiple Choicesi-  zMoved Permanentlyi.  Foundi/  z	See Otheri0  zNot Modifiedi1  z	Use Proxyi2  zSwitch Proxyi3  zTemporary Redirecti4  zPermanent Redirecti  zBad Requesti  Unauthorizedi  zPayment Requiredi  	Forbiddeni  z	Not Foundi  zMethod Not Allowedi  zNot Acceptablei  zProxy Authentication Requiredi  zRequest Timeouti  Conflicti  Gonei  zLength Requiredi  zPrecondition Failedi  zRequest Entity Too Largei  zRequest URI Too Longi  zUnsupported Media Typei  zRequested Range Not Satisfiablei  zExpectation Failedi  zI'm a teapoti  zMisdirected Requesti  zUnprocessable Entityi  Lockedi  zFailed Dependencyi  z	Too Earlyi  zUpgrade Requiredi  zPrecondition Requiredi  zToo Many Requestsi  zRequest Header Fields Too Largei  z
Retry Withi  zUnavailable For Legal Reasonsi  zInternal Server Errori  zNot Implementedi  zBad Gatewayi  zService Unavailablei  zGateway Timeouti  zHTTP Version Not Supportedi  zVariant Also Negotiatesi  zInsufficient Storagei  zLoop Detectedi  zNot Extendedi  zNetwork Authentication Failedc             C   s    t  |  t  r |  S|  j d  S)z2coerce wsgi unicode represented bytes to real onesr   )
isinstancebytesencode)data r<   1/tmp/pip-build-5gj8f0j9/Werkzeug/werkzeug/http.pywsgi_to_bytes   s    r>   c             C   s?   t  |  t  s t d   t  |  t  r. |  S|  j d  Sd  S)Nzdata must be bytesr   )r8   r9   AssertionErrorstrdecode)r;   r<   r<   r=   bytes_to_wsgi   s    rB    Tc             C   sv   t  |  t  r t |   }  t |   }  | rV t t |  B} t |   j |  rV |  Sd |  j d d  j 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.
    z"%s"\z\\"z\")r8   r9   rB   r@   _token_charssetissubsetreplace)valueZextra_charsallow_tokenZtoken_charsr<   r<   r=   quote_header_value   s    
rL   Fc             C   sw   |  rs |  d |  d	 k o% d k n rs |  d d
  }  | sW |  d d  d k rs |  j  d d  j  d d  S|  S)zUnquotes 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.
    r   r   rE   N   z\\rD   z\"rN   )rI   )rJ   is_filenamer<   r<   r=   unquote_header_value   s
    	*rP   c             C   s   g  } |  d k	 r | j  |   xS t |  D]E \ } } | d k rT | j  |  q, | j  d | t |  f  q, Wd j |  S)zThe reverse function to :func:`parse_options_header`.

    :param header: the header to dump
    :param options: a dict of options to append.
    Nz%s=%sz; )appendr	   rL   join)headeroptionssegmentskeyrJ   r<   r<   r=   dump_options_header  s    !rW   c                s   t  |  t  rt g  } xu t |   D]K \ } } | d k rJ | j |  q" | j d | t | d   f  q" Wn   f d d   |  D } d j |  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.
    Nz%s=%srK   c                s"   g  |  ] } t  | d     q S)rK   )rL   ).0x)rK   r<   r=   
<listcomp>6  s   	 zdump_header.<locals>.<listcomp>z, )r8   dictr	   rQ   rL   rR   )iterablerK   itemsrV   rJ   r<   )rK   r=   dump_header  s    $r^   c             C   s    d j  d d   t |   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.

    z; c             s   s%   |  ] \ } } d  | | f Vq d S)z%s %sNr<   )rX   rV   rJ   r<   r<   r=   	<genexpr>D  s    z"dump_csp_header.<locals>.<genexpr>)rR   r	   )rS   r<   r<   r=   dump_csp_header:  s    
r`   c             C   st   g  } xg t  |   D]Y } | d d  | d d  k oD d k n r_ t | d d   } | j |  q W| 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   rE   rN   rN   )_parse_list_headerrP   rQ   )rJ   resultitemr<   r<   r=   parse_list_headerG  s    0rd   c             C   s   |   } t  |  t  s$ t |   }  x t |   D] } d | k rP d | | <q1 | j d d  \ } }  |  d d  |  d d  k o d k n r t |  d d   }  |  | | <q1 W| 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`
    =Nr   rE   rN   rN   )r8   r   rB   ra   splitrP   )rJ   clsrb   rc   namer<   r<   r=   parse_dict_headere  s    	
0ri   c             C   s  |  s d i  f Sg  } d |  j  d d  }  xj|  rt j |   } | sK P| j | j d   i  } | j d  } d } x | rkt j |  } | s P| j   \ } }	 }
 } } |	 s d } n |
 s | }
 |
 } t |  } | d k	 r%t | | d k  } |
 d k	 r%t |  j	 |
  } |	 rH| j
 | d  | | | <n
 | | | <| | j   d  } q W| j |  | d k rt |  S| }  q/ W| rt |  Sd i  f S)	u  Parse a ``Content-Type`` like header into a tuple with the content
    type and the options:

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

    This should not be used to parse ``Cache-Control`` like headers that use
    a slightly different format.  For these headers use the
    :func:`parse_dict_header` function.

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

    .. versionadded:: 0.5

    :param value: the header to parse.
    :param multiple: Whether try to parse and return multiple MIME types
    :return: (mimetype, options) or (mimetype, options, mimetype, options, …)
             if multiple=True
    rC   ,
r   rM   NfilenameF)rI   _option_header_start_mime_typematchrQ   group_option_header_piece_regroupsrP   _unquoterA   getendtuple)rJ   multiplerb   rn   rT   restZcontinued_encodingZoptmatchoptioncountencodinglanguageZoption_valuer<   r<   r=   parse_options_header  sH    
			


r|   c             C   s   | d k r t  } |  s" | d  Sg  } xo t j |   D]^ } | j d  } | s\ d } n t t t |  d  d  } | j | j d  | f  q8 W| |  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`.
    NrM   r   r   )Accept
_accept_refinditerro   maxminfloatrQ   )rJ   rg   rb   rn   Zqualityr<   r<   r=   parse_accept_header  s    
	 r   c             C   s8   | d k r t  } |  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.
    N)RequestCacheControlri   )rJ   	on_updaterg   r<   r<   r=   parse_cache_control_header  s
    r   c             C   s   | d k r t  } |  d k r+ | d |  Sg  } xl |  j d  D][ } | j   } d | k rA | j   j d d  \ } }  | j | j   |  j   f  qA W| | |  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.
    N; r   )ContentSecurityPolicyrf   striprQ   )rJ   r   rg   r]   policyZ	directiver<   r<   r=   parse_csp_header  s    #r   c             C   s&   |  s t  d |  St  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)	HeaderSetrd   )rJ   r   r<   r<   r=   parse_set_header+  s    r   c             C   sF  |  s
 d St  |   }  y( |  j d d  \ } } | j   } Wn t k
 rV d SYn X| d k r y% t j |  j d d  \ } } Wn t k
 r d SYn Xt d d t | t	  d t | t	  i  S| d k rBt
 |  } x d D] } | | k r d Sq Wd | k r5| j d  s1| j d  r5d St d |  Sd 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   s   basic   :basicusernamepasswords   digestrealmnonceuriresponseqopZnccnoncedigest)r   r   r   r   r   )r>   rf   lower
ValueErrorbase64	b64decode	ExceptionAuthorizationr   _basic_auth_charsetri   rs   )rJ   	auth_type	auth_infor   r   Zauth_maprV   r<   r<   r=   parse_authorization_headerI  s4    		%	 r   c             C   s   |  s t  d |  Sy( |  j d d  \ } } | j   } Wn4 t t f k
 rq t  |  j   j   d | SYn Xt  | 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   )WWWAuthenticaterf   r   r   AttributeErrorr   ri   )rJ   r   r   r   r<   r<   r=   parse_www_authenticate_headerq  s    
!r   c             C   sF   |  s t    St |   } | d k	 r2 t  d |  St  t |   d  S)zParses an if-range header which can be an etag or a date.  Returns
    a :class:`~werkzeug.datastructures.IfRange` object.

    .. versionadded:: 0.7
    Ndater   )IfRange
parse_dateunquote_etag)rJ   r   r<   r<   r=   parse_if_range_header  s    r   c       	      C   s  |  s d |  k r d Sg  } d } |  j  d d  \ } } | j   j   } xV| j  d  D]E} | j   } d | k r d S| j d  r | d k  r d Sy t |  } Wn t k
 r d SYn Xd } d } n d | k r| j  d d  \ } } | j   } | j   } | j   s"d St |  } | | k  sF| d k  rJd S| r| j   s`d St |  d } | | k rd Sn d } | } | j | | f  q] Wt | |  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
    re   Nr   r   rj   -rN   )	rf   r   r   
startswithintr   isdigitrQ   Range)	rJ   Zmake_inclusiverangesZlast_endunitsrngrc   beginrt   r<   r<   r=   parse_range_header  sL    		r   c             C   sb  |  d k r d Sy( |  p d j    j d d  \ } } Wn t k
 rP d SYn Xd | k ra d S| j d d  \ } } | d k r d } n | j   r t |  } n d S| d k r t | d d | d | Sd | k r d S| j d d  \ } } y  t |  } t |  d } Wn t k
 r2d SYn Xt | | |  r^t | | | | d | Sd 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.
    NrC   r   /*r   r   )r   rf   r   r   r   ContentRangeis_byte_range_valid)rJ   r   r   Zrangedefr   lengthstartstopr<   r<   r=   parse_content_range_header  s4    (			r   c             C   s6   d |  k r t  d   d |  }  | r2 d |  }  |  S)ziQuote an etag.

    :param etag: the etag to quote.
    :param weak: set to `True` to tag it "weak".
    rE   zinvalid etagz"%s"zW/)r   )etagweakr<   r<   r=   
quote_etag  s    

r   c             C   s   |  s
 d	 S|  j    }  d } |  j d
  rA d } |  d d  }  |  d d  |  d d  k ol d k n r |  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.
    NFW/w/TrM   r   rE   )NN)r   r   rN   rN   )r   r   )r   r   r<   r<   r=   r     s    0r   c       	      C   s   |  s t    Sg  } g  } t |   } d } x | | k  r t j |  |  } | d k rY P| j   \ } } } | d k r t  d d  S| r | } | r | j |  n | j |  | j   } q. Wt  | |  S)zParse an etag header.

    :param value: the tag header to parse
    :return: an :class:`~werkzeug.datastructures.ETags` object.
    r   Nr   Zstar_tagT)ETagslen_etag_rern   rq   rQ   rt   )	rJ   strongr   rt   posrn   Zis_weakquotedrawr<   r<   r=   parse_etags  s(    r   c             C   s   t  |   j   S)zGenerate an etag for some data.)r   	hexdigest)r;   r<   r<   r=   generate_etag7  s    r   c             C   s   |  r t  |  j    } | d k	 r y | d } | d k rV | d k rV | d 7} n" | d k rx | d k rx | d 7} t | f | d d	    t d
 | d p d  SWn t t f k
 r d SYn Xd S)a  Parse one of the following date formats into a datetime object:

    .. sourcecode:: text

        Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123
        Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
        Sun Nov  6 08:49:37 1994       ; ANSI C's asctime() format

    If parsing fails the return value is `None`.

    :param value: a string with a supported date format.
    :return: a :class:`datetime.datetime` object.
    Nr   D   i  E   c   il  r      secondsrN   )r   r   r   r   r   OverflowError)rJ   tyearr<   r<   r=   r   <  s    

6r   c             C   s   |  d k r t    }  n? t |  t  r6 |  j   }  n! t |  t t f  rW t  |   }  d d |  j |  j | d |  j d | |  j	 |  j
 |  j |  j f	 S)z'Used for `http_date` and `cookie_date`.Nz%%s, %02d%s%s%s%04d %02d:%02d:%02d GMTMonTueWedThuFriSatSunJanFebMarAprMayJunJulAugSepOctNovDecr   )r   r   r   r   r   r   r   )r   r   r   r   r   r   r   r   r   r   r   r   )r   r8   r   utctimetupler   r   tm_wdaytm_mdaytm_montm_yeartm_hourtm_mintm_sec)ddelimr<   r<   r=   
_dump_date\  s8    
           r   c             C   s   t  |  d  S)a  Formats the time to ensure compatibility with Netscape's cookie
    standard.

    Accepts a floating point number expressed in seconds since the epoch in, a
    datetime object or a timetuple.  All times in UTC.  The :func:`parse_date`
    function can be used to parse such a date.

    Outputs a string in the format ``Wdy, DD-Mon-YYYY HH:MM:SS GMT``.

    :param expires: If provided that date is used, otherwise the current.
    r   )r   )r   r<   r<   r=   cookie_date~  s    r   c             C   s   t  |  d  S)a  Formats the time to match the RFC1123 date format.

    Accepts a floating point number expressed in seconds since the epoch in, a
    datetime object or a timetuple.  All times in UTC.  The :func:`parse_date`
    function can be used to parse such a date.

    Outputs a string in the format ``Wdy, DD Mon YYYY HH:MM:SS GMT``.

    :param timestamp: If provided that date is used, otherwise the current.
    r   )r   )	timestampr<   r<   r=   	http_date  s    r   c             C   sq   |  s
 d Sy t  |   } Wn t k
 r2 d SYn X| d k  rC d Sy t d |  SWn t k
 rl d SYn Xd 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   r   )r   r   r   r   )rJ   r   r<   r<   r=   	parse_age  s    	r   c             C   se   |  d k r d St  |  t  r7 |  j |  j d d }  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).
    N   i  r   zage cannot be negative)r8   r   r   daysr   r   r@   )Zager<   r<   r=   dump_age  s    r   c             C   s  | d k r' | d k	 r' t  |  } n | d k	 r? t d   d } t | t  r` t |  } | d k	 r~ | j d d  } d } | r d |  k r t |  j d   } | d k	 r | j d k	 r | j } n t |  j d   } | r| r| | k rd	 } | rt	 |  \ } } | d k	 rT| j
 d k	 rTt | j
  j |  } nU t |  j d
   }	 |	 r~|	 j |  } t |  j d   }
 |
 r|
 j |  } | S)a  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:: 1.0.0
        The check is run for methods other than ``GET`` and ``HEAD``.
    Nzboth data and etag givenFmicrosecondr   Z
HTTP_RANGEZHTTP_IF_RANGEZHTTP_IF_MODIFIED_SINCETZHTTP_IF_NONE_MATCHZHTTP_IF_MATCH)r   	TypeErrorr8   r   r   rI   r   rs   r   r   r   r   containsZcontains_weakZ	is_strong)environr   r;   Zlast_modifiedZignore_if_rangeZ
unmodifiedZif_rangeZmodified_since_Zif_none_matchZif_matchr<   r<   r=   is_resource_modified  s8    r   c                s@   t  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   |  ] } | j    Vq d  S)N)r   )rX   rY   r<   r<   r=   r_     s    z(remove_entity_headers.<locals>.<genexpr>c                sA   g  |  ]7 \ } } t  |  s1 | j     k r | | f  q Sr<   )is_entity_headerr   )rX   rV   rJ   )allowedr<   r=   rZ     s   		z)remove_entity_headers.<locals>.<listcomp>N)rG   )headersr  r<   )r  r=   remove_entity_headers
  s    r  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 Sr<   )is_hop_by_hop_header)rX   rV   rJ   r<   r<   r=   rZ   (  s   	 z-remove_hop_by_hop_headers.<locals>.<listcomp>Nr<   )r  r<   r<   r=   remove_hop_by_hop_headers  s    	r  c             C   s   |  j    t k 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_headers)rS   r<   r<   r=   r   ,  s    r   c             C   s   |  j    t k 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_headers)rS   r<   r<   r=   r  7  s    r  rI   c                s   t   t  r$  j d d   n  d k r6 d  t   t  rW  j d d   | d k ri t }     f d 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_COOKIErC   Nr   rI   c              3   sk   xd t    D]V \ }  } t |     d d }  |  s: q t |    d d } t |   | f Vq Wd  S)NZallow_none_charsetT)r   r   r   )rV   val)charseterrorsrS   r<   r=   _parse_pairsf  s    z"parse_cookie.<locals>._parse_pairs)r8   r[   rs   r   r:   	MultiDict)rS   r	  r
  rg   r  r<   )r	  r
  rS   r=   parse_cookieB  s    r  r   i  c             C   s  t  |  |  }  t  | |  } | d k	 rI d d l m } | | |  } t |  } t | t  r | j d d d | j } | d k	 r t | t  s t	 |  } n+ | d k	 r |	 r t  t	 t
   |   } | d k	 r| j   } | d k rt d	   |  d
 t |  g } xd | d f d | d f d | d f d | d f d | d f d | d f d | d f f D] \ } } } | d k r| rw| j |  qw| d k rqwt |  } t | t t f  st  t |  |  } | rt |  } | d
 | 7} | j t |   qwWd j |  } t sH| j d  } t |  } |
 r| |
 k rt |  } t j d j d |  d | d | | d | d |
  d d | S)a	  Creates a new Set-Cookie header without the ``Set-Cookie`` prefix
    The parameters are the same as in the cookie Morsel object in the
    Python standard library but it accepts unicode data, too.

    On Python 3 the return value of this function will be a unicode
    string, on Python 2 it will be a native string.  In both cases the
    return value is usually restricted to ascii as the vast majority of
    values are properly escaped, but that is no guarantee.  If a unicode
    string is returned 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 unicode 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<   r   StrictLaxNonez,SameSite must be 'Strict', 'Lax', or 'None'.   =s   DomainTs   ExpiresFs   Max-Ages   Secures   HttpOnlys   Paths   SameSites   ; r   zThe "{key}" cookie is too large: the value was {value_size} bytes but the header required {extra_size} extra bytes. The final size was {cookie_size} bytes but the limit is {max_size} bytes. Browsers may silently ignore cookies larger than this.rV   
value_sizeZ
extra_sizecookie_sizemax_size
stacklevelrM   >   r  r  r  )r   urlsr  r   r8   r   r   r   r   r   r   titler   r   rQ   	bytearrayr9   r   rR   r
   rA   r   warningswarnformat)rV   rJ   Zmax_ager   pathdomainsecurehttponlyr	  Zsync_expiresr  Zsamesiter  bufkvqtmprvr  r  r<   r<   r=   dump_cookieq  sl    <	
	r(  c             C   s   |  d k | d k k r d S|  d k r> | d k p= | d k S| d k rb d |  k o_ | k  SS|  | k rr d Sd |  k o | 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   )r}   )r   )r   )r   )r   )r   )r   )r  )r   )r   )r   )r   r   )d__doc__r   rer  r   r   hashlibr   r   r   _compatr   r	   r
   r   r   r   r   r   Z	_internalr   r   r   email.utilsr   ImportErrorZemail.Utilsurllib.requestr   ra   urllib.parser   rr   urllib2r   Z_cookie_charsetr   compileVERBOSEr~   	frozensetrF   r   rG   Z_unsafe_header_charsrp   rm   r  r  ZHTTP_STATUS_CODESr>   rB   rL   rP   rW   r^   r`   rd   r[   ri   r|   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r   r  r  r(  r   Zdatastructuresr}   r   r   r   r   r   r   r  r   r   r   r<   r<   r<   r=   <module>   sp  	)H!(4- "C1