
^VUU                 @   s2  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 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 m Z m Z m Z m Z m Z m Z m Z m Z m Z m Z m Z d d l m Z m  Z  d d	 l! m" Z" d d
 l# m$ Z$ m% Z% e f Z& dW Z' e j(   Z) d d   Z* d d   Z+ d d d  Z, d d   Z- d d   Z. d d   Z/ d d   Z0 d d   Z1 d d d  Z2 d  d!   Z3 d" d#   Z4 d$ d%   Z5 d& d'   Z6 d( d)   Z7 d* d+   Z8 d, d-   Z9 e: d. d/  Z; d0 d1   Z< d2 d3   Z= d4 d5   Z> d6 d7   Z? d8 d9   Z@ d: d;   ZA d< d=   ZB d> d?   ZC d@ dA   ZD dB dC dD  ZE dE dF   ZF dG dH   ZG dI jH dJ  ZI eI dK ZJ eI dL ZK dM dN   ZL dO dP   ZM dQ dR   ZN dJ dS dT  ZO dU dV   ZP d S)Xz
requests.utils
~~~~~~~~~~~~~~

This module provides utility functions that are used within Requests
that are also useful for external consumption.

    N   )__version__)certs)parse_http_list)quoteurlparsebytesstrOrderedDictunquoteis_py2builtin_str
getproxiesproxy_bypass
urlunparse
basestring)RequestsCookieJarcookiejar_from_dict)CaseInsensitiveDict)
InvalidURLFileModeWarning.netrc_netrcc             C   s"   t  |  d  r |  j   }  n  |  S)z/Returns an internal sequence dictionary update.items)hasattrr   )d r   9/tmp/pip-build-9m6vxulb/pip/pip/_vendor/requests/utils.pydict_to_sequence)   s    r   c             C   s  d } d } t  |  d  r* t |   } n t  |  d  rE |  j } n t  |  d  ri t |  j    } nn t  |  d  r y |  j   } Wn t j k
 r Yq Xt j |  j } d |  j	 k r t
 j d t  q n  t  |  d  r |  j   } n  t d | |  S)	Nr   __len__lengetvaluefilenoba%  Requests has determined the content-length for this request using the binary size of the file: however, the file has been opened in text mode (i.e. without the 'b' flag in the mode). This may lead to an incorrect content-length. In Requests 3.0, support will be removed for files in text mode.tell)r   r    r!   r"   ioUnsupportedOperationosfstatst_sizemodewarningswarnr   r$   max)ototal_lengthcurrent_positionr"   r   r   r   	super_len2   s*    r1   Fc             C   sk  yLd d l  m  } m } d } xb t D]Z } y t j j d j |   } Wn t k
 rc d SYn Xt j j |  r& | } Pq& q& W| d k r d St	 |   } d } t
 |  t  r | j d  } n  | j j |  d }	 yG | |  j |	  }
 |
 r#|
 d rd n d } |
 | |
 d f SWn$ | t f k
 rJ| rF  n  Yn XWn t t f k
 rfYn Xd S)	z;Returns the Requests tuple auth for a given url from netrc.r   )netrcNetrcParseErrorNz~/{0}   :asciir      )r2   r3   NETRC_FILESr'   path
expanduserformatKeyErrorexistsr   
isinstancer	   decodenetlocsplitauthenticatorsIOErrorImportErrorAttributeError)urlraise_errorsr2   r3   
netrc_pathflocrisplitstrhostr   login_ir   r   r   get_netrc_auth[   s8    	rN   c             C   s[   t  |  d d  } | rW t | t  rW | d d k rW | d d k rW t j j |  Sd S)z0Tries to guess the filename of the given object.nameNr   <r   >)getattrr=   r   r'   r8   basename)objrO   r   r   r   guess_filename   s    %rV   c             C   sD   |  d k r d St  |  t t t t f  r: t d   n  t |   S)a  Take an object and test to see if it can be represented as a
    dictionary. Unless it can not be represented as such, return an
    OrderedDict, e.g.,

    ::

        >>> from_key_val_list([('key', 'val')])
        OrderedDict([('key', 'val')])
        >>> from_key_val_list('string')
        ValueError: need more than 1 value to unpack
        >>> from_key_val_list({'key': 'val'})
        OrderedDict([('key', 'val')])
    Nz+cannot encode objects that are not 2-tuples)r=   r	   r   boolint
ValueErrorr
   )valuer   r   r   from_key_val_list   s
    r[   c             C   se   |  d k r d St  |  t t t t f  r: t d   n  t  |  t j  r[ |  j   }  n  t	 |   S)az  Take an object and test to see if it can be represented as a
    dictionary. If it can be, return a list of tuples, e.g.,

    ::

        >>> to_key_val_list([('key', 'val')])
        [('key', 'val')]
        >>> to_key_val_list({'key': 'val'})
        [('key', 'val')]
        >>> to_key_val_list('string')
        ValueError: cannot encode objects that are not 2-tuples.
    Nz+cannot encode objects that are not 2-tuples)
r=   r	   r   rW   rX   rY   collectionsMappingr   list)rZ   r   r   r   to_key_val_list   s    r_   c             C   sw   g  } xj t  |   D]\ } | d d  | d d  k oD d k n rb t | d d   } n  | 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   "rR   rR   )_parse_list_headerunquote_header_valueappend)rZ   resultitemr   r   r   parse_list_header   s    0rf   c             C   s   i  } x t  |   D] } d | k r5 d | | <q n  | j d d  \ } }  |  d d  |  d d  k ox d k n r t |  d d   }  n  |  | | <q W| S)aM  Parse lists of key, value pairs as described by RFC 2068 Section 2 and
    convert them into a python dict:

    >>> 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.

    :param value: a string with a dict header.
    :return: :class:`dict`
    =Nr   r`   rR   rR   )ra   r@   rb   )rZ   rd   re   rO   r   r   r   parse_dict_header   s    
0rh   c             C   sz   |  rv |  d |  d	 k o% d k n rv |  d d
  }  | sW |  d d  d k rv |  j  d d  j  d d  Sn  |  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.

    :param value: the header value to unquote.
    r   r   r`   Nr6   z\\\z\"rR   rR   )replace)rZ   is_filenamer   r   r   rb     s
    *rb   c             C   s+   i  } x |  D] } | j  | | j <q W| S)zoReturns a key/value dictionary from a CookieJar.

    :param cj: CookieJar object to extract cookies from.
    )rZ   rO   )cjcookie_dictcookier   r   r   dict_from_cookiejar   s    ro   c             C   s   t  |  } |  j |  |  S)zReturns a CookieJar from a key/value dictionary.

    :param cj: CookieJar to insert cookies into.
    :param cookie_dict: Dict of key/values to insert into CookieJar.
    )r   update)rl   rm   cj2r   r   r   add_dict_to_cookiejar.  s    rr   c             C   sv   t  j d t  t j d d t j } t j d d t j } t j d  } | j |   | j |   | j |   S)zlReturns encodings from given content string.

    :param content: bytestring to extract encodings from.
    zIn requests 3.0, get_encodings_from_content will be removed. For more information, please see the discussion on issue #2266. (This warning should only appear once.)z!<meta.*?charset=["\']*(.+?)["\'>]flagsz+<meta.*?content=["\']*;?charset=(.+?)["\'>]z$^<\?xml.*?encoding=["\']*(.+?)["\'>])r+   r,   DeprecationWarningrecompileIfindall)content
charset_re	pragma_rexml_rer   r   r   get_encodings_from_content:  s    r}   c             C   s_   |  j  d  } | s d St j |  \ } } d | k rK | d j d  Sd | k r[ d Sd S)zmReturns encodings from given HTTP Header Dict.

    :param headers: dictionary to extract encoding from.
    zcontent-typeNcharsetz'"textz
ISO-8859-1)getcgiparse_headerstrip)headerscontent_typeparamsr   r   r   get_encoding_from_headersN  s    r   c             c   s   | j  d k r) x |  D] } | Vq Wd St j | j   d d  } x+ |  D]# } | j |  } | rK | VqK qK W| j d d d } | r | Vn  d S)zStream decodes a iterator.Nerrorsrj       finalT)encodingcodecsgetincrementaldecoderr>   )iteratorrre   decoderchunkrvr   r   r   stream_decode_response_unicodeb  s    	r   c             c   s@   d } x3 | t  |   k  r; |  | | |  V| | 7} q	 Wd S)z Iterate over slices of a string.r   N)r    )stringslice_lengthposr   r   r   iter_slicest  s    r   c             C   s   t  j d t  g  } t |  j  } | rd y t |  j |  SWqd t k
 r` | j |  Yqd Xn  y t |  j | d d SWn t	 k
 r |  j SYn Xd S)zReturns the requested content back in unicode.

    :param r: Response object to get unicode content from.

    Tried:

    1. charset from content-type
    2. fall back and replace all unicode characters

    zIn requests 3.0, get_unicode_from_response will be removed. For more information, please see the discussion on issue #2266. (This warning should only appear once.)r   rj   N)
r+   r,   rt   r   r   r	   ry   UnicodeErrorrc   	TypeError)r   tried_encodingsr   r   r   r   get_unicode_from_response|  s    r   Z4ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzz0123456789-._~c             C   s   |  j  d  } x t d t |   D] } | | d d  } t |  d k r | j   r y t t | d   } Wn" t k
 r t d |   Yn X| t k r | | | d d  | | <q d | | | | <q% d | | | | <q% Wd j	 |  S)	zUn-escape any percent-escape sequences in a URI that are unreserved
    characters. This leaves all reserved, illegal and non-ASCII bytes encoded.
    %r   r   r6      z%Invalid percent-escape sequence: '%s'N )
r@   ranger    isalnumchrrX   rY   r   UNRESERVED_SETjoin)uripartsihcr   r   r   unquote_unreserved  s    r   c             C   sO   d } d } y t  t |   d | SWn" t k
 rJ t  |  d | SYn Xd S)zRe-quote the given URI.

    This function passes the given URI through an unquote/quote cycle to
    ensure that it is fully and consistently quoted.
    z!#$%&'()*+,/:;=?@[]~z!#$&'()*+,/:;=?@[]~safeN)r   r   r   )r   safe_with_percentsafe_without_percentr   r   r   requote_uri  s    r   c             C   s   t  j d t j |    d } | j d  \ } } t  j d t j t t |     d } t  j d t j |   d | @} | | @| | @k S)z
    This function allows you to check if on IP belongs to a network subnet
    Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24
             returns False if ip = 192.168.1.1 and net = 192.168.100.0/24
    z=Lr   /)structunpacksocket	inet_atonr@   dotted_netmaskrX   )ipnetipaddrnetaddrbitsnetmasknetworkr   r   r   address_in_network  s
    +#r   c             C   s/   d d d |  >d A} t  j t j d |   S)zt
    Converts mask from /xx format to xxx.xxx.xxx.xxx
    Example: if mask is 24 function returns 255.255.255.0
    l    r       z>I)r   	inet_ntoar   pack)maskr   r   r   r   r     s    r   c             C   s1   y t  j |   Wn t  j k
 r, d SYn Xd S)NFT)r   r   error)	string_ipr   r   r   is_ipv4_address  s
    	r   c             C   s   |  j  d  d k r y t |  j d  d  } Wn t k
 rJ d SYn X| d k  sc | d k rg d Sy t j |  j d  d  Wq t j k
 r d SYq Xn d Sd S)z9Very simple check of the cidr format in no_proxy variabler   r   Fr   r   T)countrX   r@   rY   r   r   r   )string_networkr   r   r   r   is_valid_cidr  s    	r   c             C   s/  d d   } | d  } t  |   j } | r d d   | j d d  j d  D } | j d	  d
 } t |  r xs | D]( } t |  r{ t | |  r d Sq{ q{ Wq x@ | D]5 } | j |  s | j d	  d
 j |  r d Sq Wn  y t |  } Wn! t	 t
 j f k
 r d } Yn X| r+d Sd S)z:
    Returns whether we should bypass proxies or not.
    c             S   s(   t  j j |   p' t  j j |  j    S)N)r'   environr   upper)kr   r   r   <lambda>  s    z'should_bypass_proxies.<locals>.<lambda>no_proxyc             s   s   |  ] } | r | Vq d  S)Nr   ).0rL   r   r   r   	<genexpr>  s    z(should_bypass_proxies.<locals>.<genexpr> r   ,:r   TF)r   r?   rj   r@   r   r   r   endswithr   r   r   gaierror)rE   	get_proxyr   r?   r   proxy_iprL   bypassr   r   r   should_bypass_proxies  s*    (+r   c             C   s   t  |   r i  St   Sd S)z%Return a dict of environment proxies.N)r   r   )rE   r   r   r   get_environ_proxies0  s    r   c             C   sZ   | p	 i  } t  |   } | j | j d | j  } | d k rV | j | j  } n  | S)zSelect a proxy for the url, if applicable.

    :param url: The url being for the request
    :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs
    z://N)r   r   schemehostname)rE   proxiesurlpartsproxyr   r   r   select_proxy7  s    r   zpython-requestsc             C   s   d |  t  f S)z4Return a string representing the default user agent.z%s/%s)r   )rO   r   r   r   default_user_agentD  s    r   c               C   s2   t  i t   d 6d j d
  d 6d d 6d d	 6 S)Nz
User-Agentz, gzipdeflatezAccept-Encodingz*/*Acceptz
keep-alive
Connection)zgzipzdeflate)r   r   r   r   r   r   r   default_headersI  s
    
r   c       	      C   s   g  } d } x t  j d |   D] } y | j d d  \ } } Wn t k
 rb | d } } Yn Xi  } | j d  | d <xb | j d  D]Q } y | j d  \ } }  Wn t k
 r PYn X|  j |  | | j |  <q W| j |  q W| S)	zReturn a dict of parsed link headers proxies.

    i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg"

    z '"z, *<;r   r   z<> '"rE   rg   )ru   r@   rY   r   rc   )	rZ   linksreplace_charsvalrE   r   linkparamkeyr   r   r   parse_header_linksR  s"     r    r5   r6      c             C   s  |  d  d  } | t  j t  j f k r, d S| d  d  t  j k rI d S| d  d  t  j t  j f k ro d S| j t  } | d k r d S| d k r | d  d  d  t k r d	 S| d
 d  d  t k r d Sn  | d k r| d  d  t	 k r d S| d
 d   t	 k rd Sn  d  S)N   zutf-32r   z	utf-8-sigr6   zutf-16r   zutf-8z	utf-16-ber   z	utf-16-lez	utf-32-bez	utf-32-le)
r   BOM_UTF32_LEBOM32_BEBOM_UTF8BOM_UTF16_LEBOM_UTF16_BEr   _null_null2_null3)datasample	nullcountr   r   r   guess_json_utfz  s*    "r   c             C   sS   t  |  |  \ } } } } } } | s7 | | } } n  t | | | | | | f  S)zGiven a URL that may or may not have a scheme, prepend the given scheme.
    Does not replace a present scheme with the one provided as an argument.)r   r   )rE   
new_schemer   r?   r8   r   queryfragmentr   r   r   prepend_scheme_if_needed  s    !r   c             C   sS   t  |   } y" t | j  t | j  f } Wn t t f k
 rN d } Yn X| S)z_Given a url with authentication components, extract them into a tuple of
    username,password.r   )r   r   )r   r   usernamepasswordrD   r   )rE   parsedauthr   r   r   get_auth_from_url  s    "r  c             C   sI   d } t  |  t  r |  } n' t r6 |  j |  } n |  j |  } | S)z
    Given a string object, regardless of type, returns a representation of that
    string in the native string type, encoding and decoding where necessary.
    This assumes ASCII unless told otherwise.
    N)r=   r   r   encoder>   )r   r   outr   r   r   to_native_string  s    	r  c             C   sf   t  |   \ } } } } } } | s4 | | } } n  | j d d  d } t | | | | | d f  S)zE
    Given a url remove the fragment and the authentication part
    @r   r   rR   )r   rsplitr   )rE   r   r?   r8   r   r   r   r   r   r   urldefragauth  s
    r  )r   z_netrc)Q__doc__r   r   r\   r%   r'   platformru   sysr   r   r+   r   r   r   compatr   ra   r   r   r   r	   r
   r   r   r   r   r   r   r   cookiesr   r   
structuresr   
exceptionsr   r   _hush_pyflakesr7   whereDEFAULT_CA_BUNDLE_PATHr   r1   rN   rV   r[   r_   rf   rh   rb   ro   rr   r}   r   r   r   r   	frozensetr   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   <module>
   sx   R		)3"$
	/	#

