
_b                 @   s  d  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 y d d l m Z Wn" e k
 r
d d l m Z Yn Xe j d dQ  Z e j d  Z e j d  Z dR Z Gd d   d e  Z d  d!   Z Gd" d#   d# e  Z Gd$ d%   d% e  Z Gd& d'   d' e  Z  e  d(  Z! e  d)  Z" d* d+ d, d- d. d/ h Z# d0 d1   Z$ d2 d3   Z% d4 d5   Z& d6 d7   Z' d8 d9   Z( d: d;   Z) d< d d= d>  Z* d? d@ dA  Z+ dB dC dD  Z, dB dB dE dF  Z- dG dH dI  Z. dJ dK   Z/ GdL dM   dM e0  Z1 GdN dO   dO e  Z2 d S)SaD  
    werkzeug.utils
    ~~~~~~~~~~~~~~

    This module implements various utilities for WSGI applications.  Most of
    them are used by the request and response wrappers but especially for
    middleware development it makes sense to use them without the wrappers.

    :copyright: 2007 Pallets
    :license: BSD-3-Clause
    N   )	iteritems)PY2)reraise)string_types)	text_type)unichr)_DictAccessorProperty)_missing)_parse_signature)name2codepointz\$(?:(%s)|\{(%s)\})[a-zA-Z_][a-zA-Z0-9_]*   z	&([^;]+);z[^A-Za-z0-9_.-]CONAUXCOM1COM2COM3COM4LPT1LPT2LPT3PRNNULc               @   sC   e  Z d  Z d Z d d d d  Z d d   Z d d d  Z d S)	cached_propertya  A decorator that converts a function into a lazy property.  The
    function wrapped is called the first time to retrieve the result
    and then that calculated result is used the next time you access
    the value::

        class Foo(object):

            @cached_property
            def foo(self):
                # calculate something important here
                return 42

    The class has to have a `__dict__` in order for this property to
    work.
    Nc             C   s=   | p | j  |  _  | j |  _ | p* | j |  _ | |  _ d  S)N)__name__
__module____doc__func)selfr   namedoc r"   2/tmp/pip-build-5gj8f0j9/Werkzeug/werkzeug/utils.py__init__L   s    zcached_property.__init__c             C   s   | | j  |  j <d  S)N)__dict__r   )r   objvaluer"   r"   r#   __set__R   s    zcached_property.__set__c             C   sW   | d  k r |  S| j  j |  j t  } | t k rS |  j |  } | | j  |  j <| S)N)r%   getr   r
   r   )r   r&   typer'   r"   r"   r#   __get__U   s    zcached_property.__get__)r   r   __qualname__r   r$   r(   r+   r"   r"   r"   r#   r   5   s   r   c             C   sG   t  t |  j | d  t  s6 t d j | |     t |  j | <d S)a  Invalidates the cache for a :class:`cached_property`:

    >>> class Test(object):
    ...     @cached_property
    ...     def magic_number(self):
    ...         print("recalculating...")
    ...         return 42
    ...
    >>> var = Test()
    >>> var.magic_number
    recalculating...
    42
    >>> var.magic_number
    42
    >>> invalidate_cached_property(var, "magic_number")
    >>> var.magic_number
    recalculating...
    42

    You must pass the name of the cached property as the second argument.
    NzIAttribute {} of object {} is not a cached_property, cannot be invalidated)
isinstancegetattr	__class__r   	TypeErrorformatr
   r%   )r&   r    r"   r"   r#   invalidate_cached_property_   s
    r2   c               @   s(   e  Z d  Z d Z d Z d d   Z d S)environ_propertya  Maps request attributes to environment variables. This works not only
    for the Werzeug request object, but also any other class with an
    environ attribute:

    >>> class Test(object):
    ...     environ = {'key': 'value'}
    ...     test = environ_property('key')
    >>> var = Test()
    >>> var.test
    'value'

    If you pass it a second value it's used as default if the key does not
    exist, the third one can be a converter that takes a value and converts
    it.  If it raises :exc:`ValueError` or :exc:`TypeError` the default value
    is used. If no default value is provided `None` is used.

    Per default the property is read only.  You have to explicitly enable it
    by passing ``read_only=False`` to the constructor.
    Tc             C   s   | j  S)N)environ)r   r&   r"   r"   r#   lookup   s    zenviron_property.lookupN)r   r   r,   r   Z	read_onlyr5   r"   r"   r"   r#   r3   }   s   r3   c               @   s"   e  Z d  Z d Z d d   Z d S)header_propertyz(Like `environ_property` but for headers.c             C   s   | j  S)N)headers)r   r&   r"   r"   r#   r5      s    zheader_property.lookupN)r   r   r,   r   r5   r"   r"   r"   r#   r6      s   r6   c               @   s   e  Z d  Z d Z e j d  Z e j   Z	 d e	 d <d d d d d	 d
 d d d d d d d d d d d d h Z
 d d d d d d d d d d  d! d" h Z d# h Z d$ d% h Z d& d'   Z d( d)   Z d* d+   Z d, d-   Z d. S)/HTMLBuildera  Helper object for HTML generation.

    Per default there are two instances of that class.  The `html` one, and
    the `xhtml` one for those two dialects.  The class uses keyword parameters
    and positional parameters to generate small snippets of HTML.

    Keyword parameters are converted to XML/SGML attributes, positional
    arguments are used as children.  Because Python accepts positional
    arguments before keyword arguments it's a good idea to use a list with the
    star-syntax for some children:

    >>> html.p(class_='foo', *[html.a('foo', href='foo.html'), ' ',
    ...                        html.a('bar', href='bar.html')])
    u'<p class="foo"><a href="foo.html">foo</a> <a href="bar.html">bar</a></p>'

    This class works around some browser limitations and can not be used for
    arbitrary SGML/XML generation.  For that purpose lxml and similar
    libraries exist.

    Calling the builder escapes the string passed:

    >>> html.p(html("<foo>"))
    u'<p>&lt;foo&gt;</p>'
    z	&([^;]+);'   ZaposareabasebasefontbrcolcommandembedframehrimginputkeygenisindexlinkmetaparamsourcewbrselectedcheckedcompactZdeclaredeferdisabledismapmultipleZnohrefZnoresizenoshadeZnowraptextareascriptstylec             C   s   | |  _  d  S)N)_dialect)r   dialectr"   r"   r#   r$      s    zHTMLBuilder.__init__c             C   s
   t  |  S)N)escape)r   sr"   r"   r#   __call__   s    zHTMLBuilder.__call__c                s;    d  d  d k r" t        f d d   } | S)Nr   __c                 s  d  } x t  |  D] \ } } | d  k r2 q | d d k rR | d  d  } |   j k r | sj q   j d k r d | d } q d } n d t |  d } | d | | 7} q W|  r    j k r   j d k r | d	 7} n
 | d
 7} | S| d
 7} d j d d   |  D  } | rs   j k rGt |  } n,    j k rs  j d k rsd | d } | | d  d
 7} | S)N<r   _xhtmlz=""  z />>c             S   s(   g  |  ] } | d  k	 r t  |   q S)N)r   ).0xr"   r"   r#   
<listcomp>  s   	 z:HTMLBuilder.__getattr__.<locals>.proxy.<locals>.<listcomp>z/*<![CDATA[*/z/*]]>*/z</rg   )r   _boolean_attributesrW   rY   _empty_elementsjoin_plaintext_elements_c_like_cdata)childrenZ	argumentsbufferkeyr'   Zchildren_as_string)r   tagr"   r#   proxy   s:    
	

z&HTMLBuilder.__getattr__.<locals>.proxy)AttributeError)r   rp   rq   r"   )r   rp   r#   __getattr__   s    'zHTMLBuilder.__getattr__c             C   s   d |  j  j |  j f S)Nz<%s for %r>)r/   r   rW   )r   r"   r"   r#   __repr__  s    zHTMLBuilder.__repr__N)r   r   r,   r   recompile
_entity_rer   copy	_entitiesri   rh   rk   rl   r$   r[   rs   rt   r"   r"   r"   r#   r8      sP   
			-r8   htmlr_   zapplication/ecmascriptzapplication/javascriptzapplication/sqlzapplication/xmlzapplication/xml-dtdz&application/xml-external-parsed-entityc             C   s<   |  j  d  s* |  t k s* |  j d  r8 |  d | 7}  |  S)aL  Returns the full content type string with charset for a mimetype.

    If the mimetype represents text, the charset parameter will be
    appended, otherwise the mimetype is returned unchanged.

    :param mimetype: The mimetype to be used as content type.
    :param charset: The charset to be appended for text mimetypes.
    :return: The content type.

    .. versionchanged:: 0.15
        Any type that ends with ``+xml`` gets a charset, not just those
        that start with ``application/``. Known text types such as
        ``application/javascript`` are also given charsets.
    ztext/z+xmlz
; charset=)
startswith_charset_mimetypesendswith)mimetypecharsetr"   r"   r#   get_content_type(  s
    r   c             C   s,  |  d d  } | d d  t  j k r- d Sd | k r= d S| t  j t  j f k rY d S| d d  t  j t  j f k r d	 St |  d k r | d d  d
 k r d S| d d d  d k r d S| d d  d
 k r d S| d d d  d k r d St |  d k r(| j d  r$d Sd Sd S)a  Detect which UTF encoding was used to encode the given bytes.

    The latest JSON standard (:rfc:`8259`) suggests that only UTF-8 is
    accepted. Older documents allowed 8, 16, or 32. 16 and 32 can be big
    or little endian. Some editors or libraries may prepend a BOM.

    :internal:

    :param data: Bytes in unknown UTF encoding.
    :return: UTF encoding name

    .. versionadded:: 0.15
    N      z	utf-8-sigs    zutf-8zutf-32r   zutf-16s      z	utf-32-bes     z	utf-16-ber   z	utf-32-lez	utf-16-le)codecsBOM_UTF8BOM_UTF32_BEBOM_UTF32_LEBOM_UTF16_BEBOM_UTF16_LElenr{   )dataheadr"   r"   r#   detect_utf_encodingA  s*    "r   c                s%      f d d   } t  j |   S)aX  String-template format a string:

    >>> format_string('$foo and ${foo}s', dict(foo=42))
    '42 and 42s'

    This does not do any attribute lookup etc.  For more advanced string
    formattings have a look at the `werkzeug.template` module.

    :param string: the format string.
    :param context: a dict with the variables to insert.
    c                sG     |  j  d  p |  j  d  } t | t  sC t   |  } | S)Nr   r   )groupr-   r   r*   )matchre   )contextstringr"   r#   
lookup_arg}  s    "z!format_string.<locals>.lookup_arg)
_format_resub)r   r   r   r"   )r   r   r#   format_stringp  s    r   c             C   s   t  |  t  rO d d l m } | d |   j d d  }  t sO |  j d  }  x8 t j j	 t j j
 f D] } | rh |  j | d  }  qh Wt t j d d j |  j      j d	  }  t j d
 k r |  r |  j d  d j   t k r d |  }  |  S)au  Pass it a filename and it will return a secure version of it.  This
    filename can then safely be stored on a regular file system and passed
    to :func:`os.path.join`.  The filename returned is an ASCII only string
    for maximum portability.

    On windows systems the function also makes sure that the file is not
    named after one of the special device files.

    >>> secure_filename("My cool movie.mov")
    'My_cool_movie.mov'
    >>> secure_filename("../../../etc/passwd")
    'etc_passwd'
    >>> secure_filename(u'i contain cool \xfcml\xe4uts.txt')
    'i_contain_cool_umlauts.txt'

    The function might return an empty filename.  It's your responsibility
    to ensure that the filename is unique and that you abort or
    generate a random filename if the function returned an empty one.

    .. versionadded:: 0.5

    :param filename: the filename to secure
    r   )	normalizeZNFKDasciiignorerb   ra   r^   z._nt.)r-   r   unicodedatar   encoder   decodeospathsepaltsepreplacestr_filename_ascii_strip_rer   rj   splitstripr    upper_windows_device_files)filenamer   r   r"   r"   r#   secure_filename  s    '	
r   c             C   s~   |  d k r d St  |  d  r/ t |  j    St |  t  sJ t |   }  |  j d d  j d d  j d d	  j d
 d  S)a  Replace special characters "&", "<", ">" and (") to HTML-safe sequences.

    There is a special handling for `None` which escapes to an empty string.

    .. versionchanged:: 0.9
       `quote` is now implicitly on.

    :param s: the string to escape.
    :param quote: ignored.
    Nra   __html__&z&amp;r]   z&lt;rc   z&gt;r`   z&quot;)hasattrr   r   r-   r   r   )rZ   r"   r"   r#   rY     s    rY   c             C   s   d d   } t  j | |   S)zThe reverse function of `escape`.  This unescapes all the HTML
    entities, not only the XML entities inserted by `escape`.

    :param s: the string to unescape.
    c             S   s   |  j  d  } | t j k r/ t t j |  Sy` | d  d  d k re t t | d d   d   S| j d  r t t | d d     SWn t k
 r Yn Xd S)	Nr   r   #x#X   #ra   )r   r   )r   r8   ry   r   intr{   
ValueError)mr    r"   r"   r#   handle_match  s    zunescape.<locals>.handle_match)rw   r   )rZ   r   r"   r"   r#   unescape  s    r   i.  c             C   s   | d k r d d l  m } t |   } t |  t  rY d d l m } | |  d d }  | d t |   | f | d d	 } |  | j d
 <| S)aa  Returns a response object (a WSGI application) that, if called,
    redirects the client to the target location. Supported codes are
    301, 302, 303, 305, 307, and 308. 300 is not supported because
    it's not a real redirect and 304 because it's the answer for a
    request with a request with defined If-Modified-Since headers.

    .. versionadded:: 0.6
       The location can now be a unicode string that is encoded using
       the :func:`iri_to_uri` function.

    .. versionadded:: 0.10
        The class used for the Response object can now be passed in.

    :param location: the location the response should redirect to.
    :param code: the redirect status code. defaults to 302.
    :param class Response: a Response class to use when instantiating a
        response. The default is :class:`werkzeug.wrappers.Response` if
        unspecified.
    Nr   )Response)
iri_to_uriZsafe_conversionTz<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>Redirecting...</title>
<h1>Redirecting...</h1>
<p>You should be redirected automatically to target URL: <a href="%s">%s</a>.  If not click the link.r~   z	text/htmlLocation)Zwrappersr   rY   r-   r   urlsr   r7   )locationcoder   Zdisplay_locationr   responser"   r"   r#   redirect  s    	r   i-  c             C   sG   |  d j  d  d } |  j d  } | r: | d | 7} t | |  S)a-  Redirects to the same URL but with a slash appended.  The behavior
    of this function is undefined if the path ends with a slash already.

    :param environ: the WSGI environment for the request that triggers
                    the redirect.
    :param code: the status code for the redirect.
    Z	PATH_INFO/QUERY_STRING?)r   r)   r   )r4   r   new_pathZquery_stringr"   r"   r#   append_slash_redirect  s
    r   Fc             C   s)  t  |   j d d  }  y y t |   Wn! t k
 rL d |  k rH   Yn Xt j |  S|  j d d  \ } } t | t   t   | g  } y t	 | |  SWn1 t
 k
 r } z t |   WYd d } ~ Xn XWnN t k
 r$} z. | st t t |  |  t j   d  WYd d } ~ Xn Xd S)aC  Imports an object based on a string.  This is useful if you want to
    use import paths as endpoints or something similar.  An import path can
    be specified either in dotted notation (``xml.sax.saxutils.escape``)
    or with a colon as object delimiter (``xml.sax.saxutils:escape``).

    If `silent` is True the return value will be `None` if the import fails.

    :param import_name: the dotted name for the object to import.
    :param silent: if set to `True` import errors are ignored and
                   `None` is returned instead.
    :return: imported object
    :r   r   Nr   )r   r   
__import__ImportErrorsysmodulesrsplitglobalslocalsr.   rr   r   ImportStringErrorexc_info)import_namesilentmodule_nameZobj_namemoduleer"   r"   r#   import_string%  s$    #r   c       
      c   s   t  |   } t | d d  } | d k r: t d |    | j d } xk t j |  D]Z \ } } } | | } | r | r | V| r x' t | | d  D] }	 |	 Vq WqW | VqW Wd S)a  Finds all the modules below a package.  This can be useful to
    automatically import all views / controllers so that their metaclasses /
    function decorators have a chance to register themselves on the
    application.

    Packages are not returned unless `include_packages` is `True`.  This can
    also recursively list modules but in that case it will import all the
    packages to get the correct load path of that module.

    :param import_path: the dotted name for the package to find child modules.
    :param include_packages: set to `True` if packages should be returned, too.
    :param recursive: set to `True` if recursion should happen.
    :return: generator
    __path__Nz%r is not a packager   T)r   r.   r   r   pkgutiliter_modulesfind_modules)
Zimport_pathZinclude_packages	recursiver   r   basename	_importermodnameispkgitemr"   r"   r#   r   M  s    
r   Tc             C   s   t  |   } | | |  d d  \ } } } } } | rO t t |    n% | s[ | rt | rt t d | |   t |  | f S)a  Checks if the function accepts the arguments and keyword arguments.
    Returns a new ``(args, kwargs)`` tuple that can safely be passed to
    the function without causing a `TypeError` because the function signature
    is incompatible.  If `drop_extra` is set to `True` (which is the default)
    any extra positional or keyword arguments are dropped automatically.

    The exception raised provides three attributes:

    `missing`
        A set of argument names that the function expected but where
        missing.

    `extra`
        A dict of keyword arguments that the function can not handle but
        where provided.

    `extra_positional`
        A list of values that where given by positional argument but the
        function cannot accept.

    This can be useful for decorators that forward user submitted data to
    a view function::

        from werkzeug.utils import ArgumentValidationError, validate_arguments

        def sanitize(f):
            def proxy(request):
                data = request.values.to_dict()
                try:
                    args, kwargs = validate_arguments(f, (request,), data)
                except ArgumentValidationError:
                    raise BadRequest('The browser failed to transmit all '
                                     'the data expected.')
                return f(*args, **kwargs)
            return proxy

    :param func: the function the validation is performed against.
    :param args: a tuple of positional arguments.
    :param kwargs: a dict of keyword arguments.
    :param drop_extra: set to `False` if you don't want extra arguments
                       to be silently dropped.
    :return: tuple in the form ``(args, kwargs)``.
    N   )r   ArgumentValidationErrortuple)r   argskwargsZ
drop_extraparsermissingextraextra_positionalr"   r"   r#   validate_argumentsm  s    ,(r   c             C   s'  t  |   | |  \ } } } } } } } } i  }	 x0 t | |  D] \ \ }
 } } } | |	 |
 <qC W| d k	 r t |  |	 | <n | r t d   | d k	 r t |  t d d   | D  @} | r t d t t t |      | |	 | <n( | r#t d t t t |      |	 S)a>  Bind the arguments provided into a dict.  When passed a function,
    a tuple of arguments and a dict of keyword arguments `bind_arguments`
    returns a dict of names as the function would see it.  This can be useful
    to implement a cache decorator that uses the function arguments to build
    the cache key based on the values of the arguments.

    :param func: the function the arguments should be bound for.
    :param args: tuple of positional arguments.
    :param kwargs: a dict of keyword arguments.
    :return: a :class:`dict` of bound keyword arguments.
    Nztoo many positional argumentsc             S   s   g  |  ] } | d   q S)r   r"   )rd   re   r"   r"   r#   rf     s   	 z"bind_arguments.<locals>.<listcomp>z)got multiple values for keyword argument z got unexpected keyword argument )r   zipr   r0   setreprnextiter)r   r   r   r   r   r   Zarg_specZ
vararg_varZ	kwarg_varvaluesr    Z_has_default_defaultr'   Zmultikwr"   r"   r#   bind_arguments  s"    -%#"r   c               @   s+   e  Z d  Z d Z d d d d d  Z d S)r   z6Raised if :func:`validate_arguments` fails to validateNc             C   sp   t  | p f   |  _ | p i  |  _ | p- g  |  _ t j |  d t |  j  t |  j  t |  j  f  d  S)Nz7function arguments invalid. (%d missing, %d additional))r   r   r   r   r   r$   r   )r   r   r   r   r"   r"   r#   r$     s    z ArgumentValidationError.__init__)r   r   r,   r   r$   r"   r"   r"   r#   r     s   r   c               @   s:   e  Z d  Z d Z d Z d Z d d   Z d d   Z d S)r   zBProvides information about a failed :func:`import_string` attempt.Nc       	      C   s   | |  _  | |  _ d } d } g  } x | j d d  j d  D] } | | oR d | 7} t | d d } | r | j | t | d d   f  q@ d d	   | D } | j d
 |  | | d j |  | j j	 t
 |  f } Pq@ Wt j |  |  d  S)Na1  import_string() failed for %r. Possible reasons are:

- missing __init__.py in a package;
- package or module path not included in sys.path;
- duplicated package or module name taking precedence in sys.path;
- missing module, class, function or variable;

Debugged import:

%s

Original exception:

%s: %sra   r   r   r   T__file__c             S   s&   g  |  ] \ } } d  | | f  q S)z- %r found in %r.r"   )rd   nir"   r"   r#   rf     s   	 z.ImportStringError.__init__.<locals>.<listcomp>z- %r not found.
)r   	exceptionr   r   r   appendr.   rj   r/   r   r   r   r$   )	r   r   r   msgr    ZtrackedpartZimportedtrackr"   r"   r#   r$     s&    		
""	zImportStringError.__init__c             C   s   d |  j  j |  j |  j f S)Nz<%s(%r, %r)>)r/   r   r   r   )r   r"   r"   r#   rt     s    	zImportStringError.__repr__)r   r   r,   r   r   r   r$   rt   r"   r"   r"   r#   r     s
   #r   )r   )r   r   )r   r   r   r   r   r   r   r   r   r   r   )3r   r   r   r   ru   r   _compatr   r   r   r   r   r   Z	_internalr	   r
   r   html.entitiesr   r   htmlentitydefsrv   r   rw   r   r   propertyr   r2   r3   r6   objectr8   rz   r_   r|   r   r   r   r   rY   r   r   r   r   r   r   r   r   r   r   r"   r"   r"   r#   <module>   sv             *y	/2,( 5)