
_              
   @   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 e j d  Z e e d   Z d Z e d d   e D  Z d d   e d  D Z e e d d d d d d g   Z Gd d   d e  Z e Gd  d!   d! e   Z Gd" d#   d# e  Z  e   e i Z! d$ d% d&  Z" d' d(   Z# d$ d) d*  Z$ d d+ d, d-  Z% d. d/ d0 d$ d1 d2  Z& e&   Z' e& d3 d4 d5 d6  Z( d7 d8   Z) d. d/ d0 d$ d9 d:  Z* d. d/ d$ d; d<  Z+ d= d>   Z, d. d? d$ d@ dA  Z- d. d? dB dC  Z. d. dD dE  Z/ d$ j0 dF d   e dG  D  Z1 dH dI   Z2 e j3 dJ e2  d. dJ dK dL  Z4 dM Z5 d. d/ dN dO dP  Z6 d. dN d+ d? dQ d dR dS  Z7 d. dN d+ d? dQ d d dN dT dU  Z8 dV dW   Z9 d. dN dN d dX dY dZ  Z: d d. dN dN d dX d[ d\  Z; d+ d] d^  Z< Gd_ d`   d` e=  Z> d S)aa  
    werkzeug.urls
    ~~~~~~~~~~~~~

    ``werkzeug.urls`` used to provide several wrapper functions for Python 2
    urlparse, whose main purpose were to work around the behavior of the Py2
    stdlib and its lack of unicode support. While this was already a somewhat
    inconvenient situation, it got even more complicated because Python 3's
    ``urllib.parse`` actually does handle unicode properly. In other words,
    this module would wrap two libraries with completely different behavior. So
    now this module contains a 2-and-3-compatible backport of Python 3's
    ``urllib.parse``, which is mostly API-compatible.

    :copyright: 2007 Pallets
    :license: BSD-3-Clause
    N)
namedtuple   )fix_tuple_repr)implements_to_string)make_literal_wrapper)normalize_string_tuple)PY2)	text_type)	to_native)
to_unicode)try_coerce_native)_decode_idna)_encode_idnaz^[a-zA-Z0-9+-.]+$sB   abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~0123456789ABCDEFabcdefc             c   s?   |  ]5 } t  D]( } | | j   t | | d   f Vq q d S)   N)
_hexdigitsencodeint).0ab r   1/tmp/pip-build-5gj8f0j9/Werkzeug/werkzeug/urls.py	<genexpr>2   s    r   c             C   s#   g  |  ] } d  | j  d   q S)z%%%02Xascii)r   )r   charr   r   r   
<listcomp>4   s   	 r      	_URLTupleschemenetlocpathqueryfragmentc               @   s3  e  Z d  Z d Z f  Z d d   Z e d d    Z e d d    Z e d d	    Z	 e d
 d    Z
 e d d    Z e d d    Z e d d    Z e d d    Z d d   Z d d   Z d d   Z d d   Z d d   Z d d   Z d  d! d"  Z d# d$   Z d% d&   Z d' d(   Z d  S))BaseURLz7Superclass of :py:class:`URL` and :py:class:`BytesURL`.c             K   s   |  j  |   S)zReturn an URL with the same values, except for those parameters
        given new values by whichever keyword arguments are specified.)_replace)selfkwargsr   r   r   replaceA   s    zBaseURL.replacec             C   s   |  j    d S)zThe host part of the URL if available, otherwise `None`.  The
        host is either the hostname or the IP address mentioned in the
        URL.  It will not contain the port.
        r   )_split_host)r&   r   r   r   hostF   s    zBaseURL.hostc             C   sk   |  j  } | d k	 r[ t | t  r[ y t |  } Wn$ t k
 rZ | j d d  } Yn Xt | d d  S)a   Works exactly like :attr:`host` but will return a result that
        is restricted to ASCII.  If it finds a netloc that is not ASCII
        it will attempt to idna decode it.  This is useful for socket
        operations when the URL might include internationalized characters.
        Nr   ignore)r*   
isinstancer	   r   UnicodeErrorr   r
   )r&   rvr   r   r   
ascii_hostN   s    	zBaseURL.ascii_hostc             C   s_   y@ t  t |  j   d   } d | k o6 d k n r? | SWn t t f k
 rZ Yn Xd S)z}The port in the URL as an integer if it was present, `None`
        otherwise.  This does not fill in default ports.
        r   r   i  N)r   r
   r)   
ValueError	TypeError)r&   r.   r   r   r   port]   s    zBaseURL.portc             C   s   |  j    d S)zSThe authentication part in the URL if available, `None`
        otherwise.
        r   )_split_netloc)r&   r   r   r   authi   s    zBaseURL.authc             C   s*   |  j    d } | d k	 r& t |  Sd S)zThe username if it was part of the URL, `None` otherwise.
        This undergoes URL decoding and will always be a unicode string.
        r   N)_split_auth_url_unquote_legacy)r&   r.   r   r   r   usernamep   s    zBaseURL.usernamec             C   s   |  j    d S)zThe username if it was part of the URL, `None` otherwise.
        Unlike :attr:`username` this one is not being decoded.
        r   )r5   )r&   r   r   r   raw_usernamey   s    zBaseURL.raw_usernamec             C   s*   |  j    d } | d k	 r& t |  Sd S)zThe password if it was part of the URL, `None` otherwise.
        This undergoes URL decoding and will always be a unicode string.
        r   N)r5   r6   )r&   r.   r   r   r   password   s    zBaseURL.passwordc             C   s   |  j    d S)zThe password if it was part of the URL, `None` otherwise.
        Unlike :attr:`password` this one is not being decoded.
        r   )r5   )r&   r   r   r   raw_password   s    zBaseURL.raw_passwordc             O   s   t  |  j | |  S)zDecodes the query part of the URL.  Ths is a shortcut for
        calling :func:`url_decode` on the query argument.  The arguments and
        keyword arguments are forwarded to :func:`url_decode` unchanged.
        )
url_decoder"   )r&   argsr'   r   r   r   decode_query   s    zBaseURL.decode_queryc             O   s   t  t |  | |   S)zJoins this URL with another one.  This is just a convenience
        function for calling into :meth:`url_join` and then parsing the
        return value again.
        )	url_parseurl_join)r&   r<   r'   r   r   r   join   s    zBaseURL.joinc             C   s
   t  |   S)zReturns a URL string or bytes depending on the type of the
        information stored.  This is just a convenience function
        for calling :meth:`url_unparse` for this URL.
        )url_unparse)r&   r   r   r   to_url   s    zBaseURL.to_urlc             C   s   t  |  j p d  } d | k r+ d | } |  j } | d k	 rP d | | f } d j t d t |  j pk d d  t |  j p d d  g   } | r d | | f } | S)z&Decodes the netloc part into a string. :z[%s]Nz%s:%dz/:%@z%s@%s)r   r*   r2   r@   filterr6   r8   r:   )r&   r.   r2   r4   r   r   r   decode_netloc   s    
	!zBaseURL.decode_netlocc             C   s   t  t |   j d   S)a*  Returns a :class:`BytesURL` tuple that holds a URI.  This will
        encode all the information in the URL properly to ASCII using the
        rules a web browser would follow.

        It's usually more interesting to directly call :meth:`iri_to_uri` which
        will return a string.
        r   )r>   
iri_to_urir   )r&   r   r   r   to_uri_tuple   s    zBaseURL.to_uri_tuplec             C   s   t  t |    S)aS  Returns a :class:`URL` tuple that holds a IRI.  This will try
        to decode as much information as possible in the URL without
        losing information similar to how a web browser does it for the
        URL bar.

        It's usually more interesting to directly call :meth:`uri_to_iri` which
        will return a string.
        )r>   
uri_to_iri)r&   r   r   r   to_iri_tuple   s    	zBaseURL.to_iri_tupleNc             C   s  |  j  d k r d St |  j  } |  j p. d } | d k r[ t j d k rU d } n d } | d k r]| d d  d k r | d d  j   r | d d	  d
 k r | d d  d | d	 d  } | d d	  d k } d d l } | j |  } | r| d k r| j	 d  j
 d d  } t |  d k rJ| \ } } q| d } d } n@ | d k rd d l } | j |  } n t d t |    | d k rd } | | f S)a@  Returns a tuple with the location of the file in the form
        ``(server, location)``.  If the netloc is empty in the URL or
        points to localhost, it's represented as ``None``.

        The `pathformat` by default is autodetection but needs to be set
        when working with URLs of a specific system.  The supported values
        are ``'windows'`` when working with Windows or DOS paths and
        ``'posix'`` when working with posix paths.

        If the URL does not point to a local file, the server and location
        are both represented as ``None``.

        :param pathformat: The expected format of the path component.
                           Currently ``'windows'`` and ``'posix'`` are
                           supported.  Defaults to ``None`` which is
                           autodetect.
        fileNntZwindowsposixr   /      z|:rD   \r   rC   zInvalid path format %s	127.0.0.1::1	localhost)NN\\\///)rU   rV   )rR   rS   rT   )r   url_unquoter!   r    osnameisalphantpathnormpathlstripsplitlen	posixpathr1   repr)r&   Z
pathformatr!   r*   Zwindows_sharer[   partsr`   r   r   r   get_file_location   s6    	B"
	zBaseURL.get_file_locationc             C   s5   |  j  |  j k r( |  j j |  j  d  Sd  |  j f S)Nr   )_atr    r^   )r&   r   r   r   r3     s    zBaseURL._split_netlocc             C   sF   |  j    d } | s d S|  j | k r3 | d  f S| j |  j d  S)Nr   r   )NN)r3   _colonr^   )r&   r4   r   r   r   r5     s    
zBaseURL._split_authc             C   s   |  j    d } | s d S| j |  j  sX |  j | k rN | j |  j d  S| d  f S| j |  j  } | d k  r | d  f S| d |  } | | d d   } | j |  j  r | | d d   f S| d  f S)Nr   r   )NN)r3   
startswith	_lbracketre   r^   find	_rbracket)r&   r.   idxr*   restr   r   r   r)     s    

zBaseURL._split_host)__name__
__module____qualname____doc__	__slots__r(   propertyr*   r/   r2   r4   r7   r8   r9   r:   r=   r@   rB   rF   rH   rJ   rc   r3   r5   r)   r   r   r   r   r$   <   s*   		
<r$   c               @   s^   e  Z d  Z d Z f  Z d Z d Z d Z d Z d d   Z	 d d	   Z
 d
 d d d  Z d S)URLzRepresents a parsed URL.  This behaves like a regular tuple but
    also has some extra attributes that give further insight into the
    URL.
    @rD   []c             C   s
   |  j    S)N)rB   )r&   r   r   r   __str__;  s    zURL.__str__c          	   C   s   |  j  p d } d | k r% d | } |  j } | d k	 rJ d | | f } d j t d t |  j pe d d d d  t |  j p d d d d  g   } | r d	 | | f } t |  S)
z6Encodes the netloc part to an ASCII safe URL as bytes.rC   rD   z[%s]Nz%s:%dzutf-8strictz/:%z%s@%s)r/   r2   r@   rE   	url_quoter8   r:   r
   )r&   r.   r2   r4   r   r   r   encode_netloc>  s    
	'zURL.encode_netloczutf-8r(   c             C   sU   t  |  j j d  |  j   |  j j | |  |  j j | |  |  j j | |   S)zEncodes the URL to a tuple made out of bytes.  The charset is
        only being used for the path, query and fragment.
        r   )BytesURLr   r   ry   r!   r"   r#   )r&   charseterrorsr   r   r   r   S  s    	z
URL.encodeN)rl   rm   rn   ro   rp   rd   re   rg   ri   rv   ry   r   r   r   r   r   rr   .  s   rr   c               @   s^   e  Z d  Z d Z f  Z d Z d Z d Z d Z d d   Z	 d d	   Z
 d
 d d d  Z d S)rz   z!Represents a parsed URL in bytes.   @   :   [   ]c             C   s   |  j    j d d  S)Nzutf-8r(   )rB   decode)r&   r   r   r   rv   i  s    zBytesURL.__str__c             C   s   |  j  S)z&Returns the netloc unchanged as bytes.)r    )r&   r   r   r   ry   l  s    zBytesURL.encode_netloczutf-8r(   c             C   sU   t  |  j j d  |  j   |  j j | |  |  j j | |  |  j j | |   S)zDecodes the URL to a tuple made out of strings.  The charset is
        only being used for the path, query and fragment.
        r   )rr   r   r   rF   r!   r"   r#   )r&   r{   r|   r   r   r   r   p  s    	zBytesURL.decodeN)rl   rm   rn   ro   rp   rd   re   rg   ri   rv   ry   r   r   r   r   r   rz   `  s   rz   rC   c                s>  t  |  t  r |  j d  }  t    t  r<   j d    t t       t |  j d   } t t | d   } y t   } Wn9 t	 k
 r   f d d   t
 j   D } t   <Yn Xxo | D]g } | d  d  } | | k r| j | |  | j | d d    q | j d  | j |  q Wt |  S)Nzutf-8   %    c                s+   i  |  ]! \ } } |   k r | |  q Sr   r   )r   hr   )unsafer   r   
<dictcomp>  s   	z%_unquote_to_bytes.<locals>.<dictcomp>rO   %   )r,   r	   r   	frozenset	bytearrayiterr^   next_unquote_mapsKeyError
_hextobyteitemsappendextendbytes)stringr   groupsresultZhex_to_bytegroupcoder   )r   r   _unquote_to_bytes  s(    r   c             c   s   d d l  m } | |   } | r4 t | d | } x | D]| \ } } | d  k rV q; t | t  sz t |  j |  } t | t  s t |  j |  } t |  d t |  Vq; Wd  S)Nr   )iter_multi_itemskey=)datastructuresr   sortedr,   r   r	   r   _fast_url_quote_plus)objr{   encode_keyssortr   r   iterablevaluer   r   r   _url_encode_impl  s    r   c             C   sO   y  t  |  d d d d d | SWn( t k
 rJ t  |  d d d | SYn Xd  S)Nr{   zutf-8r|   rw   r   latin1)rW   r-   )r   r   r   r   r   r6     s     r6   Tc                sS  t  |     t |  t  } | d k r3   d  }   d  } } } |  j   d   } | d k r t j t |  d |  d d  r |  | d d  } | s t   f d d	   | D  r |  d |  j   | } }  |  d d
    d  k rt	 |   }	 xA   d  D]3 }
 |  j |
 d
  } | d k rt
 |	 |  }	 qW|  d
 |	  |  |	 d  } }    d  | k r  d  | k s  d  | k r  d  | k rt d   | r  d  |  k r|  j   d  d  \ }  }   d  |  k r+|  j   d  d  \ }  } | r7t n t } | | | |  | |  S)a  Parses a URL from a string into a :class:`URL` tuple.  If the URL
    is lacking a scheme it can be provided as second argument. Otherwise,
    it is ignored.  Optionally fragments can be stripped from the URL
    by setting `allow_fragments` to `False`.

    The inverse of this function is :func:`url_unparse`.

    :param url: the URL to parse.
    :param scheme: the default schema to use if the URL is schemaless.
    :param allow_fragments: if set to `False` a fragment will be removed
                            from the URL.
    NrC   rD   r   r|   r(   r   c             3   s!   |  ] } |   d   k Vq d S)
0123456789Nr   )r   c)sr   r   r     s    zurl_parse.<locals>.<genexpr>rO   z//z/?#rt   ru   zInvalid IPv6 URL#?)r   r,   r	   rh   
_scheme_rematchr
   anylowerr_   minr0   r^   rr   rz   )urlr   allow_fragmentsZis_text_basedr    r"   r#   irk   delimr   wdelimZresult_typer   )r   r   r>     s4    1&!$$r>   zutf-8rw   z/:c                s   t    t  r!   j |  |    t  | t  rB | j |  |  } t t     t Bt t |       f d d   t d  D  t s  f d d   } n  f d d   } | S)a  Precompile the translation table for a URL encoding function.

    Unlike :func:`url_quote`, the generated function only takes the
    string to quote.

    :param charset: The charset to encode the result with.
    :param errors: How to handle encoding errors.
    :param safe: An optional sequence of safe characters to never encode.
    :param unsafe: An optional sequence of unsafe characters to always encode.
    c                s2   g  |  ]( } |   k r$ t  |  n d  |  q S)z%%%02X)chr)r   r   )safer   r   r     s   	 z(_make_fast_url_quote.<locals>.<listcomp>r   c                s    d j    f d d   |  D  S)NrC   c                s   g  |  ] }   |  q Sr   r   )r   r   )tabler   r   r     s   	 z7_make_fast_url_quote.<locals>.quote.<locals>.<listcomp>)r@   )r   )r   r   r   quote  s    z#_make_fast_url_quote.<locals>.quotec                s&   d j    f d d   t |   D  S)NrC   c                s   g  |  ] }   |  q Sr   r   )r   r   )r   r   r   r     s   	 z7_make_fast_url_quote.<locals>.quote.<locals>.<listcomp>)r@   r   )r   )r   r   r   r     s    )r,   r	   r   r   r   _always_saferanger   )r{   r|   r   r   r   r   )r   r   r   _make_fast_url_quote  s    &r   r    r   +c             C   s   t  |   j d d  S)Nr   r   )_fast_quote_plusr(   )r   r   r   r   r     s    r   c             C   s
  t  |  t t t f  s$ t |   }  t  |  t  rE |  j | |  }  t  | t  rf | j | |  } t  | t  r | j | |  } t t |   t Bt t |   } t   } xA t |   D]3 } | | k r | j |  q | j t	 |  q Wt
 t |   S)aD  URL encode a single string with a given encoding.

    :param s: the string to quote.
    :param charset: the charset to be used.
    :param safe: an optional sequence of safe characters.
    :param unsafe: an optional sequence of unsafe characters.

    .. versionadded:: 0.9.2
       The `unsafe` parameter was added.
    )r,   r	   r   r   r   r   r   r   r   
_bytetohexr
   )r   r{   r|   r   r   r.   r   r   r   r   rx     s    &	rx   c             C   s&   t  |  | | | d d  j d d  S)zURL encode a single string with the given encoding and convert
    whitespace to "+".

    :param s: The string to quote.
    :param charset: The charset to be used.
    :param safe: An optional sequence of safe characters.
    r   r   )rx   r(   )r   r{   r|   r   r   r   r   url_quote_plus-  s    r   c             C   s  t  |   \ } } } } } t |  } | d  } | sT | r | j | d   r | r | d d  | d  k r | d  | } | d  | p | d  | } n | r | | 7} | r | | d  | } | r | | d  | } | r| | d  | } | S)	zThe reverse operation to :meth:`url_parse`.  This accepts arbitrary
    as well as :class:`URL` tuples and returns a URL as a string.

    :param components: the parsed URL as tuple which should be converted
                       into a URL string.
    rC   rN   Nr   z//rD   r   r   )r   r   rf   )
componentsr   r    r!   r"   r#   r   r   r   r   r   rA   8  s     !"#
rA   r(   c             C   s1   t  |  |  } | d k	 r- | j | |  } | S)a  URL decode a single string with a given encoding.  If the charset
    is set to `None` no unicode decoding is performed and raw bytes
    are returned.

    :param s: the string to unquote.
    :param charset: the charset of the query string.  If set to `None`
                    no unicode decoding will take place.
    :param errors: the error handling for the charset decoding.
    N)r   r   )r   r{   r|   r   r.   r   r   r   rW   V  s    
rW   c             C   sF   t  |  t  r$ |  j d d  }  n |  j d d  }  t |  | |  S)a  URL decode a single string with the given `charset` and decode "+" to
    whitespace.

    Per default encoding errors are ignored.  If you want a different behavior
    you can set `errors` to ``'replace'`` or ``'strict'``.  In strict mode a
    :exc:`HTTPUnicodeError` is raised.

    :param s: The string to unquote.
    :param charset: the charset of the query string.  If set to `None`
                    no unicode decoding will take place.
    :param errors: The error handling for the `charset` decoding.
    r   r      +    )r,   r	   r(   rW   )r   r{   r|   r   r   r   url_unquote_plusf  s    r   c             C   s   t  |  | d  j d d  }  |  j d  rm |  d d  j   rm |  d d  d k rm d
 |  d d  }  t |   } t | j | d d } t | j | d d } t | j	 | d d } t
 t | j | j   | | | f   S)a  Sometimes you get an URL by a user that just isn't a real URL because
    it contains unsafe characters like ' ' and so on. This function can fix
    some of the problems in a similar way browsers handle data entered by the
    user:

    >>> url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffskl\xe4rung)')
    'http://de.wikipedia.org/wiki/Elf%20(Begriffskl%C3%A4rung)'

    :param s: the string with the URL to fix.
    :param charset: The target charset for the URL if the url was given as
                    unicode string.
    r(   rQ   rN   zfile://      
   :/|/zfile:///Nr   z
/%+$!*'(),z:&%=+$!*'(),)r   r   )r   r(   rf   rZ   r>   rx   r!   r   r"   r#   r
   rA   r   ry   )r   r{   r   r!   qsanchorr   r   r   url_fixz  s    ;r   c             C   s(   g  |  ] } | t  k r t |   q Sr   )r   r   )r   r   r   r   r   r     s   	    c             C   sA   t  |  j |  j |  j   } t r4 | j d  } | |  j f S)zRUsed in :func:`uri_to_iri` after unquoting to re-quote any
    invalid bytes.
    zutf-8)_fast_url_quoteobjectstartendr   r   )eoutr   r   r   _codec_error_url_quote  s    r   zwerkzeug.url_quotec             C   s   t  |  t  r t |   }  t t |  |   }  t |  j | | t  } t |  j | | t  } t |  j	 | | t  } t |  j
 |  j   | | | f  S)a  Convert a URI to an IRI. All valid UTF-8 characters are unquoted,
    leaving all reserved and invalid characters quoted. If the URL has
    a domain, it is decoded from Punycode.

    >>> uri_to_iri("http://xn--n3h.net/p%C3%A5th?q=%C3%A8ry%DF")
    'http://\u2603.net/p\xe5th?q=\xe8ry%DF'

    :param uri: The URI to convert.
    :param charset: The encoding to encode unquoted bytes with.
    :param errors: Error handler to use during ``bytes.encode``. By
        default, invalid bytes are left quoted.

    .. versionchanged:: 0.15
        All reserved and invalid characters remain quoted. Previously,
        only some reserved characters were preserved, and invalid bytes
        were replaced instead of left quoted.

    .. versionadded:: 0.6
    )r,   tuplerA   r>   r   rW   r!   _to_iri_unsafer"   r#   r   rF   )urir{   r|   r!   r"   r#   r   r   r   rI     s    rI   z:/?#[]@!$&'()*+,;=%Fc       	      C   s   t  |  t  r t |   }  | rq y; t |   } | j d  } t | j    d k r[ | SWn t k
 rp Yn Xt t	 |  | |   }  t
 |  j | | t  } t
 |  j | | t  } t
 |  j | | t  } t t |  j |  j   | | | f   S)a  Convert an IRI to a URI. All non-ASCII and unsafe characters are
    quoted. If the URL has a domain, it is encoded to Punycode.

    >>> iri_to_uri('http://\u2603.net/p\xe5th?q=\xe8ry%DF')
    'http://xn--n3h.net/p%C3%A5th?q=%C3%A8ry%DF'

    :param iri: The IRI to convert.
    :param charset: The encoding of the IRI.
    :param errors: Error handler to use during ``bytes.encode``.
    :param safe_conversion: Return the URL unchanged if it only contains
        ASCII characters and no whitespace. See the explanation below.

    There is a general problem with IRI conversion with some protocols
    that are in violation of the URI specification. Consider the
    following two IRIs::

        magnet:?xt=uri:whatever
        itms-services://?action=download-manifest

    After parsing, we don't know if the scheme requires the ``//``,
    which is dropped if empty, but conveys different meanings in the
    final URL if it's present or not. In this case, you can use
    ``safe_conversion``, which will return the URL unchanged if it only
    contains ASCII characters and no whitespace. This can result in a
    URI with unquoted characters if it was not already quoted correctly,
    but preserves the URL's semantics. Werkzeug uses this for the
    ``Location`` header for redirects.

    .. versionchanged:: 0.15
        All reserved characters remain unquoted. Previously, only some
        reserved characters were left unquoted.

    .. versionchanged:: 0.9.6
       The ``safe_conversion`` parameter was added.

    .. versionadded:: 0.6
    r   r   )r,   r   rA   r
   r   r_   r^   r-   r>   r   rx   r!   _to_uri_safer"   r#   r   ry   )	Zirir{   r|   Zsafe_conversionZ
native_iriZ	ascii_irir!   r"   r#   r   r   r   rG     s     &rG   &c             C   s   | d k r" d d l  m } | } t |  t  rY t | t  rY | j | pP d  } n4 t |  t  r t | t  r | j | p d  } | t |  j |  | | | |   S)a  
    Parse a querystring and return it as :class:`MultiDict`.  There is a
    difference in key decoding on different Python versions.  On Python 3
    keys will always be fully decoded whereas on Python 2, keys will
    remain bytestrings if they fit into ASCII.  On 2.x keys can be forced
    to be unicode by setting `decode_keys` to `True`.

    If the charset is set to `None` no unicode decoding will happen and
    raw bytes will be returned.

    Per default a missing value for a key will default to an empty key.  If
    you don't want that behavior you can set `include_empty` to `False`.

    Per default encoding errors are ignored.  If you want a different behavior
    you can set `errors` to ``'replace'`` or ``'strict'``.  In strict mode a
    `HTTPUnicodeError` is raised.

    .. versionchanged:: 0.5
       In previous versions ";" and "&" could be used for url decoding.
       This changed in 0.5 where only "&" is supported.  If you want to
       use ";" instead a different `separator` can be provided.

       The `cls` parameter was added.

    :param s: a string with the query string to decode.
    :param charset: the charset of the query string.  If set to `None`
                    no unicode decoding will take place.
    :param decode_keys: Used on Python 2.x to control whether keys should
                        be forced to be unicode objects.  If set to `True`
                        then keys will be unicode in all cases. Otherwise,
                        they remain `str` if they fit into ASCII.
    :param include_empty: Set to `False` if you don't want empty values to
                          appear in the dict.
    :param errors: the decoding error behavior.
    :param separator: the pair separator to be used, defaults to ``&``
    :param cls: an optional dict class to use.  If this is not specified
                       or `None` the default :class:`MultiDict` is used.
    Nr   )	MultiDictr   )	r   r   r,   r	   r   r   r   _url_decode_implr^   )r   r{   decode_keysinclude_emptyr|   	separatorclsr   r   r   r   r;     s    /r;   c	             C   sp   d d l  m }	 |	 |  | |  }
 t |
 | | | |  } | rD | S| d k rf d d l m } | } | |  S)a  Works like :func:`url_decode` but decodes a stream.  The behavior
    of stream and limit follows functions like
    :func:`~werkzeug.wsgi.make_line_iter`.  The generator of pairs is
    directly fed to the `cls` so you can consume the data while it's
    parsed.

    .. versionadded:: 0.8

    :param stream: a stream with the encoded querystring
    :param charset: the charset of the query string.  If set to `None`
                    no unicode decoding will take place.
    :param decode_keys: Used on Python 2.x to control whether keys should
                        be forced to be unicode objects.  If set to `True`,
                        keys will be unicode in all cases. Otherwise, they
                        remain `str` if they fit into ASCII.
    :param include_empty: Set to `False` if you don't want empty values to
                          appear in the dict.
    :param errors: the decoding error behavior.
    :param separator: the pair separator to be used, defaults to ``&``
    :param cls: an optional dict class to use.  If this is not specified
                       or `None` the default :class:`MultiDict` is used.
    :param limit: the content length of the URL data.  Not necessary if
                  a limited stream is provided.
    :param return_iterator: if set to `True` the `cls` argument is ignored
                            and an iterator over all decoded pairs is
                            returned
    r   )make_chunk_iterN)r   )Zwsgir   r   r   r   )streamr{   r   r   r|   r   r   limitZreturn_iteratorr   	pair_iterdecoderr   r   r   r   url_decode_streamJ  s    &r   c       
      c   s   x |  D] } | s q t  |  } | d  } | | k rU | j | d  \ } }	 n | s^ q | } | d  }	 t | | |  } | d  k	 r t r | r t |  } | t |	 | |  f Vq Wd  S)Nr   r   rC   )r   r^   r   r   r   )
r   r{   r   r   r|   pairr   equalr   r   r   r   r   r     s    r      &c             C   s.   t  | d  } | j t |  | | | |   S)a  URL encode a dict/`MultiDict`.  If a value is `None` it will not appear
    in the result string.  Per default only values are encoded into the target
    charset strings.  If `encode_keys` is set to ``True`` unicode keys are
    supported too.

    If `sort` is set to `True` the items are sorted by `key` or the default
    sorting algorithm.

    .. versionadded:: 0.5
        `sort`, `key`, and `separator` were added.

    :param obj: the object to encode into a query string.
    :param charset: the charset of the query string.
    :param encode_keys: set to `True` if you have unicode keys. (Ignored on
                        Python 3.x)
    :param sort: set to `True` if you want parameters to be sorted by `key`.
    :param separator: the separator to be used for the pairs.
    :param key: an optional function to be used for sorting.  For more details
                check out the :func:`sorted` documentation.
    r   )r
   r@   r   )r   r{   r   r   r   r   r   r   r   
url_encode  s    r   c       
      C   sx   t  | d  } t |  | | | |  } | d k r7 | Sx: t |  D], \ } }	 | rc | j |  | j |	  qD Wd S)a  Like :meth:`url_encode` but writes the results to a stream
    object.  If the stream is `None` a generator over all encoded
    pairs is returned.

    .. versionadded:: 0.8

    :param obj: the object to encode into a query string.
    :param stream: a stream to write the encoded object into or `None` if
                   an iterator over the encoded pairs should be returned.  In
                   that case the separator argument is ignored.
    :param charset: the charset of the query string.
    :param encode_keys: set to `True` if you have unicode keys. (Ignored on
                        Python 3.x)
    :param sort: set to `True` if you want parameters to be sorted by `key`.
    :param separator: the separator to be used for the pairs.
    :param key: an optional function to be used for sorting.  For more details
                check out the :func:`sorted` documentation.
    r   N)r
   r   	enumeratewrite)
r   r   r{   r   r   r   r   genrj   chunkr   r   r   url_encode_stream  s    r   c                s  t  |  t  r t |   }  t  | t  r6 t |  } t |  | f  \ }  } t |     |  sd | S| sn |  St |  d | \ } } } } } t | | |  \ } }	 }
 } } | | k r | S|	 r t | |	 |
 | | f  S| }	 |
 d d    d  k r|
 j   d   } n\ |
 sC| j   d   } | su| } n2 | j   d   d d  |
 j   d   } | d   d  k r  d  | d <  f d d   | D } x d } t |  d } xm | | k  r;| |   d	  k r.| | d   d    d	  f k r.| | d | d  =P| d 7} qWPqW  d    d	  g } x! | d d
  | k r|| d =q\W  d  j |  }
 t | |	 |
 | | f  S)a	  Join a base URL and a possibly relative URL to form an absolute
    interpretation of the latter.

    :param base: the base URL for the join operation.
    :param url: the URL to join.
    :param allow_fragments: indicates whether fragments should be allowed.
    r   Nr   rN   .rC   c                s(   g  |  ] } |   d   k r |  q S)r   r   )r   Zsegment)r   r   r   r     s   	 zurl_join.<locals>.<listcomp>z..rO   r   r   )	r,   r   rA   r   r   r>   r^   r_   r@   )baser   r   bschemebnetlocbpathbquery	bfragmentr   r    r!   r"   r#   segmentsr   nZunwanted_markerr   )r   r   r?     sT    !	2<r?   c               @   sF   e  Z d  Z d Z d d d d d d  Z d d	   Z d
 d   Z d S)Hrefa  Implements a callable that constructs URLs with the given base. The
    function can be called with any number of positional and keyword
    arguments which than are used to assemble the URL.  Works with URLs
    and posix paths.

    Positional arguments are appended as individual segments to
    the path of the URL:

    >>> href = Href('/foo')
    >>> href('bar', 23)
    '/foo/bar/23'
    >>> href('foo', bar=23)
    '/foo/foo?bar=23'

    If any of the arguments (positional or keyword) evaluates to `None` it
    will be skipped.  If no keyword arguments are given the last argument
    can be a :class:`dict` or :class:`MultiDict` (or any other dict subclass),
    otherwise the keyword arguments are used for the query parameters, cutting
    off the first trailing underscore of the parameter name:

    >>> href(is_=42)
    '/foo?is=42'
    >>> href({'foo': 'bar'})
    '/foo?foo=bar'

    Combining of both methods is not allowed:

    >>> href({'foo': 'bar'}, bar=42)
    Traceback (most recent call last):
      ...
    TypeError: keyword arguments and query-dicts can't be combined

    Accessing attributes on the href object creates a new href object with
    the attribute name as prefix:

    >>> bar_href = href.bar
    >>> bar_href("blub")
    '/foo/bar/blub'

    If `sort` is set to `True` the items are sorted by `key` or the default
    sorting algorithm:

    >>> href = Href("/", sort=True)
    >>> href(a=1, b=2, c=3)
    '/?a=1&b=2&c=3'

    .. versionadded:: 0.5
        `sort` and `key` were added.
    z./zutf-8FNc             C   s4   | s d } | |  _  | |  _ | |  _ | |  _ d  S)Nz./)r   r{   r   r   )r&   r   r{   r   r   r   r   r   __init__I  s    			zHref.__init__c             C   sp   | d  d  d k r" t  |   |  j } | d d   d k rK | d 7} t t | |  |  j |  j |  j  S)NrO   __r   rN   r   )AttributeErrorr   r   r?   r{   r   r   )r&   rY   r   r   r   r   __getattr__Q  s    	
zHref.__getattr__c          
      s  | rI t  | d t  rI | r+ t d   | d | d  d  } } n% | rn t d d   | j   D  } d j   f d d   | D  j d  }   j } | r | j d  s | d 7} t | d |  } | r| d t	 t
 |   j d	   j d
   j d  7} t |  S)Nr   z3keyword arguments and query-dicts can't be combinedc             S   sA   g  |  ]7 \ } } | j  d   r1 | d d  p4 | | f  q S)_Nr   r   )endswith)r   kvr   r   r   r   `  s   	 z!Href.__call__.<locals>.<listcomp>rN   c                s7   g  |  ]- } | d  k	 r t  t |   j  d   q S)Nr   )r   rx   r{   )r   x)r&   r   r   r   d  s   	z./r   r   r   r   r   r   r   )r,   dictr1   r   r@   r]   r   r   r?   r   r   r{   r   r   r
   )r&   r!   r"   r.   r   )r&   r   __call__Y  s(    		
	,zHref.__call__)rl   rm   rn   ro   r   r   r  r   r   r   r   r     s   1r   )?ro   codecsrX   recollectionsr   _compatr   r   r   r   r   r	   r
   r   r   Z	_internalr   r   compiler   r   r   r   r   r  r   r   r   r   r$   rr   rz   r   r   r   r6   r>   r   r   r   r   rx   r   rA   rW   r   r   r@   r   r   register_errorrI   r   rG   r;   r   r   r   r   r?   r   r   r   r   r   r   <module>   s   !11!	"A9-C