B
    @)H[Œo  ã               @   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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mZ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# dd
l$m%Z% ddl&m'Z'm(Z(m)Z)m*Z* dZ+e ,¡ Z-e .¡ dk�r&dd„ Z/dd„ Zdd„ Z0dd„ Z1dadd„Z2dd„ Z3dd„ Z4dd„ Z5dd „ Z6d!d"„ Z7dbd#d$„Z8d%d&„ Z9d'd(„ Z:d)d*„ Z;d+d,„ Z<d-d.„ Z=d/d0„ Z>d1d2„ Z?e@d3ƒZAd4d5„ ZBd6d7„ ZCd8d9„ ZDd:d;„ ZEd<d=„ ZFd>d?„ ZGejHd@dA„ ƒZIdBdC„ ZJdcdDdE„ZKdFdG„ ZLdddIdJ„ZMdKdL„ ZNdMdN„ ZOdO PdP¡ZQeQdQ ZReQdR ZSdSdT„ ZTdUdV„ ZUdWdX„ ZVe WdY¡ZXe WdZ¡ZYd[d\„ ZZd]d^„ Z[d_d`„ Z\dS )ez”
requests.utils
~~~~~~~~~~~~~~

This module provides utility functions that are used within Requests
that are also useful for external consumption.
é    Né   )Ú__version__)Úcerts)Úto_native_string)Úparse_http_list)ÚquoteÚurlparseÚbytesÚstrÚOrderedDictÚunquoteÚ
getproxiesÚproxy_bypassÚ
urlunparseÚ
basestringÚinteger_typesÚis_py3Úproxy_bypass_environmentÚgetproxies_environment)Úcookiejar_from_dict)ÚCaseInsensitiveDict)Ú
InvalidURLÚInvalidHeaderÚFileModeWarningÚUnrewindableBodyError)z.netrcÚ_netrcÚWindowsc             C   sÒ   t rdd l}ndd l}y2| |jd¡}| |d¡d }| |d¡d }W n tk
r\   dS X |rf|sjdS | d¡}xX|D ]P}|dkr’d| kr’d	S | dd
¡}| dd¡}| dd¡}t	 
|| t	j¡rzd	S qzW dS )Nr   z;Software\Microsoft\Windows\CurrentVersion\Internet SettingsÚProxyEnableÚProxyOverrideFú;z<local>Ú.Tz\.Ú*z.*ú?)r   ÚwinregÚ_winregÚOpenKeyÚHKEY_CURRENT_USERÚQueryValueExÚOSErrorÚsplitÚreplaceÚreÚmatchÚI)Úhostr#   ÚinternetSettingsÚproxyEnableÚproxyOverrideÚtest© r3   ú[C:\Users\HIRONO~1\AppData\Local\Temp\pip-install-qz7kpjmn\pip\pip\_vendor\requests\utils.pyÚproxy_bypass_registry-   s2    



r5   c             C   s   t ƒ rt| ƒS t| ƒS dS )zšReturn True, if the host should be bypassed.

        Checks proxy settings gathered from the environment, if specified,
        or the registry.
        N)r   r   r5   )r.   r3   r3   r4   r   N   s    r   c             C   s   t | dƒr|  ¡ } | S )z/Returns an internal sequence dictionary update.Úitems)Úhasattrr6   )Údr3   r3   r4   Údict_to_sequenceZ   s    
r9   c          	   C   s4  d }d}t | dƒrt| ƒ}nbt | dƒr.| j}nPt | dƒr~y|  ¡ }W n tjk
rZ   Y n$X t |¡j}d| jkr~t	 
dt¡ t | dƒ�ry|  ¡ }W n$ ttfk
rº   |d k	r¶|}Y n^X t | dƒ�r|d k�ry&|  dd	¡ |  ¡ }|  |pòd¡ W n ttfk
�r   d}Y nX |d k�r&d}td|| ƒS )
Nr   Ú__len__ÚlenÚ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Úseeké   )r7   r;   r<   ÚioÚUnsupportedOperationÚosÚfstatÚst_sizeÚmodeÚwarningsÚwarnr   r>   r(   ÚIOErrorr?   Úmax)ÚoÚtotal_lengthÚcurrent_positionr<   r3   r3   r4   Ú	super_lenc   s@    







rN   Fc          	   C   s  yöddl m }m} d}xJtD ]B}ytj d |¡¡}W n tk
rJ   dS X tj |¡r|}P qW |dkrndS t	| ƒ}d}t
| tƒrŽ| d¡}|j |¡d }	y6||ƒ |	¡}
|
rÒ|
d r¾dnd}|
| |
d fS W n |tfk
rò   |rî‚ Y nX W n ttfk
�r   Y nX dS )	z;Returns the Requests tuple auth for a given url from netrc.r   )ÚnetrcÚNetrcParseErrorNz~/{0}ó   :Úasciir   r@   )rO   rP   ÚNETRC_FILESrC   ÚpathÚ
expanduserÚformatÚKeyErrorÚexistsr   Ú
isinstancer
   ÚdecodeÚnetlocr)   ÚauthenticatorsrI   ÚImportErrorÚAttributeError)ÚurlÚraise_errorsrO   rP   Ú
netrc_pathÚfÚlocÚriÚsplitstrr.   r   Úlogin_ir3   r3   r4   Úget_netrc_auth    s8    


rg   c             C   sB   t | ddƒ}|r>t|tƒr>|d dkr>|d dkr>tj |¡S dS )z0Tries to guess the filename of the given object.ÚnameNr   ú<éÿÿÿÿú>)ÚgetattrrY   r   rC   rT   Úbasename)Úobjrh   r3   r3   r4   Úguess_filenameÓ   s    ro   c             C   s.   | dkrdS t | ttttfƒr&tdƒ‚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')])

    :rtype: OrderedDict
    Nz+cannot encode objects that are not 2-tuples)rY   r
   r	   ÚboolÚintÚ
ValueErrorr   )Úvaluer3   r3   r4   Úfrom_key_val_listÛ   s
    rt   c             C   sB   | dkrdS t | ttttfƒr&tdƒ‚t | tjƒr:|  ¡ } t	| ƒS )aŒ  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.

    :rtype: list
    Nz+cannot encode objects that are not 2-tuples)
rY   r
   r	   rp   rq   rr   ÚcollectionsÚMappingr6   Úlist)rs   r3   r3   r4   Úto_key_val_listô   s    rx   c             C   s\   g }xRt | ƒD ]F}|dd… |dd…   kr6dkrJn nt|dd… ƒ}| |¡ 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`
    :rtype: list
    Nr   rj   ú")Ú_parse_list_headerÚunquote_header_valueÚappend)rs   ÚresultÚitemr3   r3   r4   Úparse_list_header  s    (r   c             C   s|   i }xrt | ƒD ]f}d|kr$d||< q| dd¡\}} | dd… | dd…   krXdkrln nt| dd… ƒ} | ||< qW |S )a^  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`
    :rtype: dict
    ú=Nr   rj   ry   )rz   r)   r{   )rs   r}   r~   rh   r3   r3   r4   Úparse_dict_header0  s    (r�   c             C   s\   | rX| d | d   kr dkrXn n4| dd… } |rD| dd… dkrX|   dd¡  d	d¡S | S )
zçUnquotes a header value.  (Reversal of :func:`quote_header_value`).
    This does not use the real unquoting but what browsers are actually
    using for quoting.

    :param value: the header value to unquote.
    :rtype: str
    r   rj   ry   r   Nr@   z\\ú\z\")r*   )rs   Úis_filenamer3   r3   r4   r{   S  s
    $r{   c             C   s"   i }x| D ]}|j ||j< q
W |S )z€Returns a key/value dictionary from a CookieJar.

    :param cj: CookieJar object to extract cookies from.
    :rtype: dict
    )rs   rh   )ÚcjÚcookie_dictÚcookier3   r3   r4   Údict_from_cookiejarl  s    
r‡   c             C   s
   t || ƒS )zÂReturns 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.
    :rtype: CookieJar
    )r   )r„   r…   r3   r3   r4   Úadd_dict_to_cookiejar{  s    rˆ   c             C   sT   t  dt¡ tjdtjd�}tjdtjd�}t d¡}| | ¡| | ¡ | | ¡ S )zlReturns encodings from given content string.

    :param content: bytestring to extract encodings from.
    z¤In 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=["\']*(.+?)["\'>])rG   rH   ÚDeprecationWarningr+   Úcompiler-   Úfindall)ÚcontentÚ
charset_reÚ	pragma_reÚxml_rer3   r3   r4   Úget_encodings_from_content†  s    
r‘   c             C   sF   |   d¡}|sdS t |¡\}}d|kr6|d  d¡S d|krBdS dS )z}Returns encodings from given HTTP Header Dict.

    :param headers: dictionary to extract encoding from.
    :rtype: str
    zcontent-typeNÚcharsetz'"Útextz
ISO-8859-1)ÚgetÚcgiÚparse_headerÚstrip)ÚheadersÚcontent_typeÚparamsr3   r3   r4   Úget_encoding_from_headersš  s    
r›   c             c   sr   |j dkr"x| D ]
}|V  qW dS t |j ¡dd�}x | D ]}| |¡}|r:|V  q:W |jddd�}|rn|V  dS )zStream decodes a iterator.Nr*   )Úerrorsó    T)Úfinal)ÚencodingÚcodecsÚgetincrementaldecoderrZ   )ÚiteratorÚrr~   ÚdecoderÚchunkÚrvr3   r3   r4   Ústream_decode_response_unicode¯  s    





r§   c             c   sL   d}|dks|dkrt | ƒ}x*|t | ƒk rF| ||| … V  ||7 }qW dS )z Iterate over slices of a string.r   N)r;   )ÚstringÚslice_lengthÚposr3   r3   r4   Úiter_slicesÁ  s    r«   c             C   sv   t  dt¡ g }t| jƒ}|rJyt| j|ƒS  tk
rH   | |¡ Y nX yt| j|dd�S  t	k
rp   | jS X dS )zâReturns 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

    :rtype: str
    z£In 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*   )rœ   N)
rG   rH   rŠ   r›   r˜   r
   r�   ÚUnicodeErrorr|   Ú	TypeError)r£   Útried_encodingsrŸ   r3   r3   r4   Úget_unicode_from_responseË  s    
r¯   zBABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~c          	   C   sÈ   |   d¡}x²tdt|ƒƒD ] }|| dd… }t|ƒdkrª| ¡ rªytt|dƒƒ}W n  tk
rt   td| ƒ‚Y nX |tkr˜||| dd…  ||< qºd||  ||< qd||  ||< qW d 	|¡S )	z¨Un-escape any percent-escape sequences in a URI that are unreserved
    characters. This leaves all reserved, illegal and non-ASCII bytes encoded.

    :rtype: str
    ú%r   r   r@   é   z%Invalid percent-escape sequence: '%s'NÚ )
r)   Úranger;   ÚisalnumÚchrrq   rr   r   ÚUNRESERVED_SETÚjoin)ÚuriÚpartsÚiÚhÚcr3   r3   r4   Úunquote_unreservedô  s    
r½   c             C   s:   d}d}yt t| ƒ|d�S  tk
r4   t | |d�S X dS )z¬Re-quote the given URI.

    This function passes the given URI through an unquote/quote cycle to
    ensure that it is fully and consistently quoted.

    :rtype: str
    z!#$%&'()*+,/:;=?@[]~z!#$&'()*+,/:;=?@[]~)ÚsafeN)r   r½   r   )r¸   Úsafe_with_percentÚsafe_without_percentr3   r3   r4   Úrequote_uri  s    rÁ   c             C   sl   t  dt | ¡¡d }| d¡\}}t  dt tt|ƒƒ¡¡d }t  dt |¡¡d |@ }||@ ||@ kS )zïThis function allows you to check if an 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

    :rtype: bool
    z=Lr   ú/)ÚstructÚunpackÚsocketÚ	inet_atonr)   Údotted_netmaskrq   )ÚipÚnetÚipaddrÚnetaddrÚbitsÚnetmaskÚnetworkr3   r3   r4   Úaddress_in_network"  s
    rÏ   c             C   s&   ddd|  > d A }t  t d|¡¡S )z�Converts mask from /xx format to xxx.xxx.xxx.xxx

    Example: if mask is 24 function returns 255.255.255.0

    :rtype: str
    l   ÿÿ r   é    z>I)rÅ   Ú	inet_ntoarÃ   Úpack)ÚmaskrÌ   r3   r3   r4   rÇ   1  s    rÇ   c             C   s*   yt  | ¡ W n t jk
r$   dS X dS )z
    :rtype: bool
    FT)rÅ   rÆ   Úerror)Ú	string_ipr3   r3   r4   Úis_ipv4_address<  s
    rÖ   c             C   sˆ   |   d¡dkr€yt|  d¡d ƒ}W n tk
r8   dS X |dk sJ|dkrNdS yt |  d¡d ¡ W q„ tjk
r|   dS X ndS dS )zV
    Very simple check of the cidr format in no_proxy variable.

    :rtype: bool
    rÂ   r   FrÐ   r   T)Úcountrq   r)   rr   rÅ   rÆ   rÔ   )Ústring_networkrÓ   r3   r3   r4   Úis_valid_cidrG  s    rÙ   c          	   c   sT   |dk	}|r"t j | ¡}|t j| < z
dV  W d|rN|dkrDt j| = n
|t j| < X dS )zÎSet the environment variable 'env_name' to 'value'

    Save previous value, yield, and then restore the previous value stored in
    the environment variable 'env_name'.

    If 'value' is None, do nothingN)rC   Úenvironr”   )Úenv_namers   Úvalue_changedÚ	old_valuer3   r3   r4   Úset_environ_  s    


rÞ   c       	   
   C   s  dd„ }|}|dkr|dƒ}t | ƒj}|rÀdd„ | dd¡ d	¡D ƒ}| d
¡d }t|ƒr�xb|D ](}t|ƒr~t||ƒrŠdS qb||krbdS qbW n0x.|D ]&}| |¡s¸| d
¡d  |¡r–dS q–W td|ƒ�2 yt	|ƒ}W n t
tjfk
rö   d}Y nX W dQ R X |�rdS dS )zL
    Returns whether we should bypass proxies or not.

    :rtype: bool
    c             S   s   t j | ¡pt j |  ¡ ¡S )N)rC   rÚ   r”   Úupper)Úkr3   r3   r4   Ú<lambda>{  s    z'should_bypass_proxies.<locals>.<lambda>NÚno_proxyc             s   s   | ]}|r|V  qd S )Nr3   )Ú.0r.   r3   r3   r4   ú	<genexpr>ˆ  s    z(should_bypass_proxies.<locals>.<genexpr>ú r²   ú,ú:r   TF)r   r[   r*   r)   rÖ   rÙ   rÏ   ÚendswithrÞ   r   r­   rÅ   Úgaierror)	r_   râ   Ú	get_proxyÚno_proxy_argr[   rÈ   Úproxy_ipr.   Úbypassr3   r3   r4   Úshould_bypass_proxiesu  s4    




rî   c             C   s   t | |d�ri S tƒ S dS )zA
    Return a dict of environment proxies.

    :rtype: dict
    )râ   N)rî   r   )r_   râ   r3   r3   r4   Úget_environ_proxies®  s    rï   c             C   sv   |pi }t | ƒ}|jdkr.| |j| d¡¡S |jd |j |jd|j dg}d}x|D ]}||krX|| }P qXW |S )z­Select 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
    NÚallz://zall://)r   Úhostnamer”   Úscheme)r_   ÚproxiesÚurlpartsÚ
proxy_keysÚproxyÚ	proxy_keyr3   r3   r4   Úselect_proxyº  s    

rø   úpython-requestsc             C   s   d| t f S )zO
    Return a string representing the default user agent.

    :rtype: str
    z%s/%s)r   )rh   r3   r3   r4   Údefault_user_agentÔ  s    rú   c               C   s   t tƒ d d¡dddœƒS )z9
    :rtype: requests.structures.CaseInsensitiveDict
    z, )ÚgzipÚdeflatez*/*z
keep-alive)z
User-AgentzAccept-EncodingÚAcceptÚ
Connection)r   rú   r·   r3   r3   r3   r4   Údefault_headersÝ  s
    rÿ   c       	   
   C   sÀ   g }d}x²t  d| ¡D ]¢}y| dd¡\}}W n tk
rL   |d }}Y nX d| d¡i}xP| d¡D ]B}y| d¡\}} W n tk
r”   P Y nX |  |¡|| |¡< qhW | |¡ qW |S )	z¼Return 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"

    :rtype: list
    z '"z, *<r   r   r²   r_   z<> '"r€   )r+   r)   rr   r—   r|   )	rs   ÚlinksÚreplace_charsÚvalr_   rš   ÚlinkÚparamÚkeyr3   r3   r4   Úparse_header_linksé  s     r  ú rR   r@   é   c             C   sÐ   | dd… }|t jt jfkr dS |dd… t jkr6dS |dd… t jt jfkrRdS | t¡}|dkrhd	S |dkrœ|ddd… tkr†d
S |ddd… tkrœdS |dkrÌ|dd… t	kr¸dS |dd… t	krÌdS dS )z
    :rtype: str
    Né   zutf-32r  z	utf-8-sigr@   zutf-16r   zutf-8z	utf-16-ber   z	utf-16-lez	utf-32-bez	utf-32-le)
r    ÚBOM_UTF32_LEÚBOM_UTF32_BEÚBOM_UTF8ÚBOM_UTF16_LEÚBOM_UTF16_BEr×   Ú_nullÚ_null2Ú_null3)ÚdataÚsampleÚ	nullcountr3   r3   r4   Úguess_json_utf  s*    
r  c             C   s8   t | |ƒ\}}}}}}|s$|| }}t||||||fƒS )zªGiven 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.

    :rtype: str
    )r   r   )r_   Ú
new_schemerò   r[   rT   rš   ÚqueryÚfragmentr3   r3   r4   Úprepend_scheme_if_needed0  s    
r  c          	   C   sB   t | ƒ}yt|jƒt|jƒf}W n ttfk
r<   d}Y nX |S )z{Given a url with authentication components, extract them into a tuple of
    username,password.

    :rtype: (str,str)
    )r²   r²   )r   r   ÚusernameÚpasswordr^   r­   )r_   ÚparsedÚauthr3   r3   r4   Úget_auth_from_urlA  s    
r  s   ^\S[^\r\n]*$|^$z^\S[^\r\n]*$|^$c          	   C   sf   | \}}t |tƒrt}nt}y| |¡s4td| ƒ‚W n* tk
r`   td||t|ƒf ƒ‚Y nX dS )zÕVerifies that header value is a string which doesn't contain
    leading whitespace or return characters. This prevents unintended
    header injection.

    :param header: tuple, in the format (name, value).
    z7Invalid return character or leading space in header: %sz>Value for header {%s: %s} must be of type str or bytes, not %sN)rY   r	   Ú_CLEAN_HEADER_REGEX_BYTEÚ_CLEAN_HEADER_REGEX_STRr,   r   r­   Útype)Úheaderrh   rs   Úpatr3   r3   r4   Úcheck_header_validityV  s    

r$  c             C   sF   t | ƒ\}}}}}}|s"|| }}| dd¡d }t|||||dfƒS )zW
    Given a url remove the fragment and the authentication part.

    :rtype: str
    ú@r   rj   r²   )r   Úrsplitr   )r_   rò   r[   rT   rš   r  r  r3   r3   r4   Úurldefragauthk  s
    
r'  c          	   C   s`   t | jddƒ}|dk	rTt| jtƒrTy|| jƒ W q\ ttfk
rP   tdƒ‚Y q\X ntdƒ‚dS )zfMove file pointer back to its recorded starting position
    so it can be read again on redirect.
    r?   Nz;An error occurred when rewinding request body for redirect.z+Unable to rewind request body for redirect.)rl   ÚbodyrY   Ú_body_positionr   rI   r(   r   )Úprepared_requestÚ	body_seekr3   r3   r4   Úrewind_body|  s    r,  )F)F)N)rù   )]Ú__doc__r•   r    ru   Ú
contextlibrA   rC   Úplatformr+   rÅ   rÃ   rG   r   r²   r   Ú_internal_utilsr   Úcompatr   rz   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   Úcookiesr   Ú
structuresr   Ú
exceptionsr   r   r   r   rS   ÚwhereÚDEFAULT_CA_BUNDLE_PATHÚsystemr5   r9   rN   rg   ro   rt   rx   r   r�   r{   r‡   rˆ   r‘   r›   r§   r«   r¯   Ú	frozensetr¶   r½   rÁ   rÏ   rÇ   rÖ   rÙ   ÚcontextmanagerrÞ   rî   rï   rø   rú   rÿ   r  Úencoder  r  r  r  r  r  r‹   r  r   r$  r'  r,  r3   r3   r3   r4   Ú<module>	   s„   @!	=
3 #

%9

	"
 

