U
    "d́                     @   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mZ ddlmZ ddlmZ ddlmZmZ dd	lmZmZmZmZmZmZ dd
lmZ ddlm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z& ddl'm(Z( ddl)m*Z*m+Z+m,Z,m-Z- ddl.m/Z/ dZ0e1 Z2dddZ3d4e5deddd Z6ej7dkrndd Z8dd Z dd Z9dd  Z:dtd"d#Z;d$d% Z<d&d' Z=ej>d(d) Z?d*d+ Z@d,d- ZAd.d/ ZBd0d1 ZCdud2d3ZDd4d5 ZEd6d7 ZFd8d9 ZGd:d; ZHd<d= ZId>d? ZJd@dA ZKdBdC ZLeMdDZNdEdF ZOdGdH ZPdIdJ ZQdKdL ZRdMdN ZSdOdP ZTej>dQdR ZUdSdT ZVdvdUdVZWdWdX ZXdwdYdZZYdxd\d]ZZd^d_ Z[d`da Z\db]dcZ^e^dd Z_e^de Z`dfdg Zadhdi Zbdjdk Zcdldm Zddndo Zedpdq Zfdrds ZgdS )yz
requests.utils
~~~~~~~~~~~~~~

This module provides utility functions that are used within Requests
that are also useful for external consumption.
    N)OrderedDict)make_headers	parse_url   )certs__version__)HEADER_VALIDATORSto_native_string)Mapping
basestringbytes
getproxiesgetproxies_environmentinteger_types)parse_http_list)proxy_bypassproxy_bypass_environmentquotestrunquoteurlparse
urlunparsecookiejar_from_dict)FileModeWarningInvalidHeader
InvalidURLUnrewindableBodyError)CaseInsensitiveDict)z.netrc_netrcP   i  )httphttpsz, z,\s*T)accept_encodingzaccept-encodingwin32c              	   C   s   zdd l }W n tk
r"   Y dS X z6||jd}t||dd }||dd }W n ttfk
rt   Y dS X |r~|sdS |d}|D ]T}|dkrd| kr d	S |	dd
}|	dd}|	dd}t
|| t
jr d	S qdS )Nr   Fz;Software\Microsoft\Windows\CurrentVersion\Internet SettingsZProxyEnableZProxyOverride;z<local>.Tz\.*z.*?)winregImportErrorOpenKeyHKEY_CURRENT_USERintQueryValueExOSError
ValueErrorsplitreplacerematchI)hostr*   ZinternetSettingsZproxyEnableZproxyOverridetest r9   2/tmp/pip-unpacked-wheel-vkc8huhg/requests/utils.pyproxy_bypass_registryG   s4    
r;   c                 C   s   t  rt| S t| S dS )zReturn True, if the host should be bypassed.

        Checks proxy settings gathered from the environment, if specified,
        or the registry.
        N)r   r   r;   )r7   r9   r9   r:   r   k   s    r   c                 C   s   t | dr|  } | S )z/Returns an internal sequence dictionary update.items)hasattrr<   )dr9   r9   r:   dict_to_sequencew   s    
r?   c              	   C   s0  d }d}t | drt| }nft | dr.| j}nTt | drz|  }W n tjtfk
r^   Y n$X t|j}d| j	krt
dt t | drz|  }W n  tk
r   |d k	r|}Y nZX t | dr|d krz&| dd	 |  }| |pd W n t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   )r=   rA   rB   ioUnsupportedOperationAttributeErrorosfstatst_sizemodewarningswarnr   rD   r0   rE   max)ototal_lengthcurrent_positionrB   r9   r9   r:   	super_len   sB    







rT   Fc              	   C   sL  t jd}|dk	r|f}ndd tD }z ddlm}m} d}|D ]D}zt j|}W n tk
rt   Y  W dS X t j	|rF|} qqF|dkrW dS t
| }	d}
t| tr|
d}
|	j|
d }z<|||}|r|d rdnd	}|| |d
 fW W S W n" |tfk
r(   |r$ Y nX W n ttfk
rF   Y nX dS )z;Returns the Requests tuple auth for a given url from netrc.ZNETRCNc                 s   s   | ]}d | V  qdS )z~/Nr9   ).0fr9   r9   r:   	<genexpr>   s     z!get_netrc_auth.<locals>.<genexpr>r   )NetrcParseErrornetrc   :asciir   rF   )rJ   environgetNETRC_FILESrY   rX   path
expanduserKeyErrorexistsr   
isinstancer   decodenetlocr2   authenticatorsr0   r+   rI   )urlraise_errorsZ
netrc_fileZnetrc_locationsrX   rY   
netrc_pathrV   locrisplitstrr7   r    login_ir9   r9   r:   get_netrc_auth   s@    

rn   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   <>)getattrrc   r   rJ   r_   basename)objro   r9   r9   r:   guess_filename   s    &rv   c              	   C   s   t j| r| S t j| \}}|rVt j|sVt j|\}}|sFqVd||g}q t|sd| S t|}|| kr~| S t	
 }t j||dd }t j|st|}||| W 5 Q R X |S )zReplace nonexistent paths that look like they refer to a member of a zip
    archive with the location of an extracted copy of the target, or else
    just return the provided path unchanged.
    /rq   )rJ   r_   rb   r2   joinzipfile
is_zipfileZipFilenamelisttempfile
gettempdiratomic_openwriteread)r_   archivememberprefixzip_filetmpextracted_pathZfile_handlerr9   r9   r:   extract_zipped_paths  s&    


r   c              	   c   sl   t jtj| d\}}z.t|d}|V  W 5 Q R X t||  W n  tk
rf   t|  Y nX dS )z-Write a file to the disk in an atomic fashion)dirwbN)	r}   mkstemprJ   r_   dirnamefdopenr3   BaseExceptionremove)filenameZtmp_descriptorZtmp_nameZtmp_handlerr9   r9   r:   r   '  s    
r   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')
        Traceback (most recent call last):
        ...
        ValueError: cannot encode objects that are not 2-tuples
        >>> from_key_val_list({'key': 'val'})
        OrderedDict([('key', 'val')])

    :rtype: OrderedDict
    N+cannot encode objects that are not 2-tuples)rc   r   r   boolr.   r1   r   valuer9   r9   r:   from_key_val_list4  s
    r   c                 C   s@   | dkrdS t | ttttfr&tdt | tr8|  } 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')
        Traceback (most recent call last):
        ...
        ValueError: cannot encode objects that are not 2-tuples

    :rtype: list
    Nr   )	rc   r   r   r   r.   r1   r   r<   listr   r9   r9   r:   to_key_val_listO  s    
r   c                 C   sX   g }t | D ]F}|dd |dd   kr4dkrHn nt|dd }|| q|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   rq   ")_parse_list_headerunquote_header_valueappend)r   resultitemr9   r9   r:   parse_list_headerm  s    (r   c                 C   sx   i }t | D ]f}d|kr"d||< q|dd\}} | dd | dd   krVdkrjn nt| dd } | ||< q|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   rq   r   )r   r2   r   )r   r   r   ro   r9   r9   r:   parse_dict_header  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 )
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.
    :rtype: str
    r   rq   r   r   NrF   z\\\z\")r3   )r   is_filenamer9   r9   r:   r     s
    $r   c                 C   s   i }| D ]}|j ||j< q|S )zReturns a key/value dictionary from a CookieJar.

    :param cj: CookieJar object to extract cookies from.
    :rtype: dict
    )r   ro   )cjcookie_dictcookier9   r9   r:   dict_from_cookiejar  s    r   c                 C   s
   t || 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.
    :rtype: CookieJar
    r   )r   r   r9   r9   r:   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.
    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=["\']*(.+?)["\'>])rN   rO   DeprecationWarningr4   compiler6   findall)content
charset_re	pragma_rexml_rer9   r9   r:   get_encodings_from_content  s    	
r   c           
      C   s   |  d}|d  |dd  }}i }d}|D ]`}| }|r0|d }}|d}	|	dkr|d|	 |}||	d d |}||| < q0||fS )	zReturns content type and parameters from given header

    :param header: string
    :return: tuple containing content type and dictionary of
         parameters
    r&   r   r   Nz"' Tr   rq   )r2   stripfindlower)
headertokenscontent_typeparamsparams_dictitems_to_stripparamkeyr   index_of_equalsr9   r9   r:   _parse_content_type_header  s    


r   c                 C   sP   |  d}|sdS t|\}}d|kr4|d dS d|kr@dS d|krLd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-1zapplication/jsonutf-8)r]   r   r   )headersr   r   r9   r9   r:   get_encoding_from_headers  s    
r   c                 c   sd   |j dkr| E dH  dS t|j dd}| D ]}||}|r.|V  q.|jddd}|r`|V  dS )zStream decodes an iterator.Nr3   errors    T)final)encodingcodecsgetincrementaldecoderrd   )iteratorrdecoderchunkrvr9   r9   r:   stream_decode_response_unicode.  s    


r   c                 c   sH   d}|dks|dkrt | }|t | k rD| |||  V  ||7 }qdS )z Iterate over slices of a string.r   N)rA   )stringslice_lengthposr9   r9   r:   iter_slices?  s    r   c                 C   s~   t dt g }t| j}|rLzt| j|W S  tk
rJ   || Y nX zt| j|ddW S  t	k
rx   | j Y S X d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

    :rtype: str
    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.)r3   r   N)
rN   rO   r   r   r   r   r   UnicodeErrorr   	TypeError)r   tried_encodingsr   r9   r9   r:   get_unicode_from_responseI  s    	
r   zBABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~c              	   C   s   |  d}tdt|D ]}|| dd }t|dkr| rztt|d}W n$ tk
rv   td| dY nX |tkr||| dd  ||< qd||  ||< qd||  ||< qd		|S )
zUn-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   rF      z"Invalid percent-escape sequence: ''N )
r2   rangerA   isalnumchrr.   r1   r   UNRESERVED_SETrx   )uripartsihcr9   r9   r:   unquote_unreservedv  s    
r   c                 C   s@   d}d}zt t| |dW S  tk
r:   t | |d Y S X d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.

    :rtype: str
    z!#$%&'()*+,/:;=?@[]~z!#$&'()*+,/:;=?@[]~)safeN)r   r   r   )r   safe_with_percentsafe_without_percentr9   r9   r:   requote_uri  s    r   c                 C   sl   t dt| d }|d\}}t dttt|d }t dt|d |@ }||@ ||@ kS )zThis 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   rw   )structunpacksocket	inet_atonr2   dotted_netmaskr.   )ipnetipaddrnetaddrbitsnetmasknetworkr9   r9   r:   address_in_network  s
    r   c                 C   s&   ddd|  > d A }t td|S )zConverts 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   r9   r9   r:   r     s    r   c                 C   s*   zt |  W n tk
r$   Y dS X dS )z
    :rtype: bool
    FT)r   r   r0   )	string_ipr9   r9   r:   is_ipv4_address  s
    r   c                 C   s   |  ddkrzt| dd }W n tk
r:   Y dS X |dk sL|dkrPdS zt| dd  W q tk
r~   Y dS X ndS dS )zV
    Very simple check of the cidr format in no_proxy variable.

    :rtype: bool
    rw   r   Fr   r   T)countr.   r2   r1   r   r   r0   )string_networkr   r9   r9   r:   is_valid_cidr  s    
r   c              	   c   sT   |dk	}|r"t j| }|t j| < z
dV  W 5 |rN|dkrDt j| = n
|t j| < X dS )zSet 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)rJ   r\   r]   )env_namer   value_changed	old_valuer9   r9   r:   set_environ  s    


r  c           	   
   C   s*  dd }|}|dkr|d}t | }|jdkr2dS |rdd |dd	d
D }t|jr|D ]0}t|rt|j|r dS q`|j|kr` dS q`nB|j}|jr|d|j 7 }|D ] }|j|s||r dS qt	d|6 zt
|j}W n  ttjfk
r   d}Y nX W 5 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)rJ   r\   r]   upper)r   r9   r9   r:   	get_proxy  s    z(should_bypass_proxies.<locals>.get_proxyNno_proxyTc                 s   s   | ]}|r|V  qd S r  r9   )rU   r7   r9   r9   r:   rW     s      z(should_bypass_proxies.<locals>.<genexpr> r   ,:F)r   hostnamer3   r2   r   r   r   portendswithr  r   r   r   gaierror)	rg   r  r  no_proxy_argparsedproxy_iphost_with_portr7   bypassr9   r9   r:   should_bypass_proxies  s<    



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   )rg   r  r9   r9   r:   get_environ_proxies3  s    r  c                 C   st   |pi }t | }|jdkr.||j|dS |jd |j |jd|j dg}d}|D ]}||krV|| } qpqV|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
    Nallz://zall://)r   r  r]   scheme)rg   proxiesurlparts
proxy_keysproxy	proxy_keyr9   r9   r:   select_proxy?  s    
r  c           	      C   st   |dk	r|ni }| j }t|j}|d}| }|rpt||dspt||d}|||d}|rp||| |S )a  This method takes proxy information from a request and configuration
    input to resolve a mapping of target proxies. This will consider settings
    such a NO_PROXY to strip proxy configurations.

    :param request: Request or PreparedRequest
    :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs
    :param trust_env: Boolean declaring whether to trust environment configs

    :rtype: dict
    Nr  r  r  )rg   r   r  r]   copyr  r  
setdefault)	requestr  	trust_envrg   r  r  new_proxiesenviron_proxiesr  r9   r9   r:   resolve_proxiesY  s    

r%  python-requestsc                 C   s   |  dt  S )zO
    Return a string representing the default user agent.

    :rtype: str
    rw   r   )ro   r9   r9   r:   default_user_agentt  s    r'  c                   C   s   t t tdddS )z9
    :rtype: requests.structures.CaseInsensitiveDict
    z*/*z
keep-alive)z
User-AgentzAccept-EncodingAccept
Connection)r   r'  DEFAULT_ACCEPT_ENCODINGr9   r9   r9   r:   default_headers}  s    r+  c           	   
   C   s   g }d}|  |} | s|S td| D ]}z|dd\}}W n tk
r\   |d }}Y nX d| di}|dD ]F}z|d\}} W n tk
r   Y  qY nX |  ||| |< qv|| q&|S )	zReturn a list 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   rg   z<> '"r   )r   r4   r2   r1   r   )	r   linksreplace_charsvalrg   r   linkr   r   r9   r9   r:   parse_header_links  s&    
r0   r[   rF      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rd
S |ddd tkrdS |dkr|dd t	krdS |dd t	krdS dS )z
    :rtype: str
    N   zutf-32r2  z	utf-8-sigrF   zutf-16r   r   z	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	nullcountr9   r9   r:   guess_json_utf  s*    
r?  c                 C   sl   t | }|\}}}}}}}	|j}
|
s.||
 }
}|r@d||
g}
|dkrL|}|dkrXd}t||
|d||	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.

    :rtype: str
    @Nr   )r   re   rx   r   )rg   
new_schemer  r  authr7   r  r_   queryfragmentre   r9   r9   r:   prepend_scheme_if_needed  s    
rE  c              	   C   sB   t | }z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passwordrI   r   )rg   r  rB  r9   r9   r:   get_auth_from_url  s    
rH  c                 C   sv   | \}}| D ]4}t |tkrtd|d|d|dt | qt|dtt | d  t|dtt | d  d	S )
zVerifies that header parts don't contain leading whitespace
    reserved characters, or return characters.

    :param header: tuple, in the format (name, value).
    zHeader part (z) from {: z$} must be of type str or bytes, not ro   r   r   r   N)typer	   r   _validate_header_part)r   ro   r   partr9   r9   r:   check_header_validity  s    rM  c                 C   s"   | | std| d| d S )NzSInvalid leading whitespace, reserved character(s), or returncharacter(s) in header rI  )r5   r   )Zheader_partZheader_kindZ	validatorr9   r9   r:   rK    s    
rK  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@  r   rq   r   )r   rsplitr   )rg   r  re   r_   r   rC  rD  r9   r9   r:   urldefragauth  s
    
rO  c                 C   s\   t | jdd}|dk	rPt| jtrPz|| j W qX tk
rL   tdY qXX ntddS )zfMove file pointer back to its recorded starting position
    so it can be read again on redirect.
    rE   Nz;An error occurred when rewinding request body for redirect.z+Unable to rewind request body for redirect.)rs   bodyrc   _body_positionr   r0   r   )prepared_request	body_seekr9   r9   r:   rewind_body/  s    
 rT  )F)F)N)T)r&  )h__doc__r   
contextlibrG   rJ   r4   r   r   sysr}   rN   ry   collectionsr   Zurllib3.utilr   r   r   r   r   _internal_utilsr	   r
   compatr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   cookiesr   
exceptionsr   r   r   r   
structuresr   r^   whereDEFAULT_CA_BUNDLE_PATHDEFAULT_PORTSrx   r2   r*  platformr;   r?   rT   rn   rv   r   contextmanagerr   r   r   r   r   r   r   r   r   r   r   r   r   r   	frozensetr   r   r   r   r   r   r   r  r  r  r  r%  r'  r+  r0  encoder9  r:  r;  r?  rE  rH  rM  rK  rO  rT  r9   r9   r9   r:   <module>   s    $	
$	B
9%
 #

(
<


	&
 