3
#b[n                 @   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mZmZmZmZ ddlmZmZmZmZ dd	l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  ddl!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-m.Z.m/Z/ ddl0m1Z1 ddlm2Z2 ej3 dkrTy
ej4Z5W n e6k
rP   ej7Z5Y nX nejZ5efddZ8efddZ9G dd de:Z;G dd de;Z<dd Z=dS )z
requests.session
~~~~~~~~~~~~~~~~

This module provides a Session object to manage and persist settings across
requests (cookies, auth, proxies).
    N)Mapping)	timedelta   )_basic_auth_str)	cookielibis_py3OrderedDicturljoinurlparse)cookiejar_from_dictextract_cookies_to_jarRequestsCookieJarmerge_cookies)RequestPreparedRequestDEFAULT_REDIRECT_LIMIT)default_hooksdispatch_hook)to_native_string)to_key_val_listdefault_headers)TooManyRedirectsInvalidSchemaChunkedEncodingErrorContentDecodingError)CaseInsensitiveDict)HTTPAdapter)requote_uriget_environ_proxiesget_netrc_authshould_bypass_proxiesget_auth_from_urlrewind_body)codes)REDIRECT_STATIZWindowsc             C   st   |dkr| S | dkr|S t |to*t | ts0| S |t|}|jt|  dd |j D }x|D ]
}||= qbW |S )zDetermines appropriate setting for a given request, taking into account
    the explicit setting on that request, and the setting in the session. If a
    setting is a dictionary, they will be merged together using `dict_class`
    Nc             S   s   g | ]\}}|d kr|qS )N ).0kvr%   r%   3/usr/lib/python3/dist-packages/requests/sessions.py
<listcomp>J   s    z!merge_setting.<locals>.<listcomp>)
isinstancer   r   updateitems)Zrequest_settingZsession_setting
dict_classZmerged_settingZ	none_keyskeyr%   r%   r)   merge_setting2   s    



r0   c             C   s@   |dks|j dg kr| S | dks0| j dg kr4|S t| ||S )zProperly merges both requests and session hooks.

    This is necessary because when request_hooks == {'response': []}, the
    merge breaks Session hooks entirely.
    Nresponse)getr0   )Zrequest_hooksZsession_hooksr.   r%   r%   r)   merge_hooksQ   s
    r3   c               @   s>   e Zd Zdd Zdd Zddd	Zd
d Zdd Zdd ZdS )SessionRedirectMixinc             C   s,   |j r(|jd }tr|jd}t|dS dS )z7Receives a Response. Returns a redirect URI or ``None``locationlatin1utf8N)Zis_redirectheadersr   encoder   )selfrespr5   r%   r%   r)   get_redirect_targetb   s    


z(SessionRedirectMixin.get_redirect_targetc             C   sd   t |}t |}|j|jkr dS |jdkrL|jdkrL|jdkrL|jd	krLdS |j|jkpb|j|jkS )
zFDecide whether Authorization header should be removed when redirectingTZhttpP   NZhttps  F)r=   N)r>   N)r
   ZhostnameschemeZport)r:   Zold_urlZnew_urlZ
old_parsedZ
new_parsedr%   r%   r)   should_strip_authw   s    z&SessionRedirectMixin.should_strip_authFNTc	             k   s.  g }
| j |}x|r(|j }|
j| |
dd |_y
|j W n( tttfk
rj   |jj	dd Y nX t
|j| jkrtd| j |d|j  |jdrt|j}dt|j|f }t|}|j }|jst|jt|}nt|}t||_| j|| |jtjtjfkr>d}x|D ]}|jj|d q W d|_|j}y
|d= W n tk
rd   Y nX t |j!||j t"|j!| j# |j$|j! | j%||}| j&|| |j'dk	od	|kpd|k}|rt(| |}|r|V  q| j)|f|||||dd|	}t | j#||j | j |}|V  qW dS )zBReceives a Response. Returns a generator of Responses or Requests.r   NF)Zdecode_contentzExceeded %s redirects.)r1   z//z%s:%sContent-LengthContent-TypeTransfer-EncodingZCookie)streamtimeoutverifycertproxiesallow_redirects)rA   rB   rC   )*r<   copyappendhistorycontentr   r   RuntimeErrorrawreadlenmax_redirectsr   close
startswithr
   urlr   r?   ZgeturlZnetlocr	   r   rebuild_methodstatus_coder#   Ztemporary_redirectZpermanent_redirectr8   popZbodyKeyErrorr   Z_cookiesr   cookiesZprepare_cookiesrebuild_proxiesrebuild_authZ_body_positionr"   send)r:   r;   reqrD   rE   rF   rG   rH   yield_requestsZadapter_kwargsZhistrU   prepared_requestZparsed_rurlZparsedZpurged_headersheaderr8   Z
rewindabler%   r%   r)   resolve_redirects   sr    









z&SessionRedirectMixin.resolve_redirectsc             C   sR   |j }|j}d|kr*| j|jj|r*|d= | jr8t|nd}|dk	rN|j| dS )zWhen being redirected we may want to strip authentication from the
        request to avoid leaking credentials. This method intelligently removes
        and reapplies authentication where possible to avoid credential loss.
        ZAuthorizationN)r8   rU   r@   request	trust_envr   Zprepare_auth)r:   r`   r1   r8   rU   Znew_authr%   r%   r)   r\      s    
z!SessionRedirectMixin.rebuild_authc             C   s   |dk	r|ni }|j }|j}t|j}|j }|jd}t||d}| jr~| r~t||d}	|	j||	jd}
|
r~|j	||
 d|kr|d= yt
|| \}}W n tk
r   d\}}Y nX |r|rt|||d< |S )a  This method re-evaluates the proxy configuration by considering the
        environment variables. If we are redirected to a URL covered by
        NO_PROXY, we strip the proxy configuration. Otherwise, we set missing
        proxy keys for this URL (in case they were stripped by a previous
        redirect).

        This method also replaces the Proxy-Authorization header where
        necessary.

        :rtype: dict
        Nno_proxy)re   allzProxy-Authorization)NN)r8   rU   r
   r?   rJ   r2   r    rd   r   
setdefaultr!   rY   r   )r:   r`   rH   r8   rU   r?   Znew_proxiesre   Zbypass_proxyZenviron_proxiesproxyZusernameZpasswordr%   r%   r)   r[     s*    

z$SessionRedirectMixin.rebuild_proxiesc             C   sX   |j }|jtjkr|dkrd}|jtjkr6|dkr6d}|jtjkrN|dkrNd}||_ dS )zWhen being redirected we may want to change the method of the request
        based on certain specs or browser behavior.
        HEADGETPOSTN)methodrW   r#   Z	see_otherfoundZmoved)r:   r`   r1   rl   r%   r%   r)   rV   0  s    z#SessionRedirectMixin.rebuild_method)FNTNNF)	__name__
__module____qualname__r<   r@   rb   r\   r[   rV   r%   r%   r%   r)   r4   `   s    
k)r4   c               @   s   e Zd ZdZdddddddd	d
ddddgZdd Zdd Zdd Zdd Zd7ddZ	dd Z
dd Zdd  Zd8d!d"Zd9d#d$Zd:d%d&Zd'd( Zd)d* Zd+d, Zd-d. Zd/d0 Zd1d2 Zd3d4 Zd5d6 ZdS );Sessiona~  A Requests session.

    Provides cookie persistence, connection-pooling, and configuration.

    Basic Usage::

      >>> import requests
      >>> s = requests.Session()
      >>> s.get('http://httpbin.org/get')
      <Response [200]>

    Or as a context manager::

      >>> with requests.Session() as s:
      >>>     s.get('http://httpbin.org/get')
      <Response [200]>
    r8   rZ   authrH   hooksparamsrF   rG   ZprefetchadaptersrD   rd   rR   c             C   sr   t  | _d | _i | _t | _i | _d| _d| _d | _	t
| _d| _ti | _t | _| jdt  | jdt  d S )NFTzhttps://zhttp://)r   r8   rr   rH   r   rs   rt   rD   rF   rG   r   rR   rd   r   rZ   r   ru   mountr   )r:   r%   r%   r)   __init__`  s    
zSession.__init__c             C   s   | S )Nr%   )r:   r%   r%   r)   	__enter__  s    zSession.__enter__c             G   s   | j   d S )N)rS   )r:   argsr%   r%   r)   __exit__  s    zSession.__exit__c             C   s   |j pi }t|tjst|}ttt | j |}|j}| jrV| rV| j rVt	|j
}t }|j|jj |j
|j|j|jt|j| jtdt|j| jt|| j|t|j| jd
 |S )a  Constructs a :class:`PreparedRequest <PreparedRequest>` for
        transmission and returns it. The :class:`PreparedRequest` has settings
        merged from the :class:`Request <Request>` instance and those of the
        :class:`Session`.

        :param request: :class:`Request` instance to prepare with this
            session's settings.
        :rtype: requests.PreparedRequest
        )r.   )
rl   rU   filesdatajsonr8   rt   rr   rZ   rs   )rZ   r+   r   Z	CookieJarr   r   r   rr   rd   r   rU   r   Zpreparerl   upperr{   r|   r}   r0   r8   r   rt   r3   rs   )r:   rc   rZ   Zmerged_cookiesrr   pr%   r%   r)   prepare_request  s*    



zSession.prepare_requestNTc             C   st   t |j ||||pi ||pi |||d
}| j|}|p8i }| j|j||||}|	|
d}|j| | j|f|}|S )a  Constructs a :class:`Request <Request>`, prepares it and sends it.
        Returns :class:`Response <Response>` object.

        :param method: method for the new :class:`Request` object.
        :param url: URL for the new :class:`Request` object.
        :param params: (optional) Dictionary or bytes to be sent in the query
            string for the :class:`Request`.
        :param data: (optional) Dictionary, bytes, or file-like object to send
            in the body of the :class:`Request`.
        :param json: (optional) json to send in the body of the
            :class:`Request`.
        :param headers: (optional) Dictionary of HTTP Headers to send with the
            :class:`Request`.
        :param cookies: (optional) Dict or CookieJar object to send with the
            :class:`Request`.
        :param files: (optional) Dictionary of ``'filename': file-like-objects``
            for multipart encoding upload.
        :param auth: (optional) Auth tuple or callable to enable
            Basic/Digest/Custom HTTP Auth.
        :param timeout: (optional) How long to wait for the server to send
            data before giving up, as a float, or a :ref:`(connect timeout,
            read timeout) <timeouts>` tuple.
        :type timeout: float or tuple
        :param allow_redirects: (optional) Set to True by default.
        :type allow_redirects: bool
        :param proxies: (optional) Dictionary mapping protocol or protocol and
            hostname to the URL of the proxy.
        :param stream: (optional) whether to immediately download the response
            content. Defaults to ``False``.
        :param verify: (optional) Either a boolean, in which case it controls whether we verify
            the server's TLS certificate, or a string, in which case it must be a path
            to a CA bundle to use. Defaults to ``True``.
        :param cert: (optional) if String, path to ssl client cert file (.pem).
            If Tuple, ('cert', 'key') pair.
        :rtype: requests.Response
        )
rl   rU   r8   r{   r|   r}   rt   rr   rZ   rs   )rE   rI   )r   r~   r   merge_environment_settingsrU   r,   r]   )r:   rl   rU   rt   r|   r8   rZ   r{   rr   rE   rI   rH   rs   rD   rF   rG   r}   r^   ZprepZsettingsZsend_kwargsr;   r%   r%   r)   rc     s(    )

zSession.requestc             K   s   |j dd | jd|f|S )zSends a GET request. Returns :class:`Response` object.

        :param url: URL for the new :class:`Request` object.
        :param \*\*kwargs: Optional arguments that ``request`` takes.
        :rtype: requests.Response
        rI   Trj   )rg   rc   )r:   rU   kwargsr%   r%   r)   r2     s    zSession.getc             K   s   |j dd | jd|f|S )zSends a OPTIONS request. Returns :class:`Response` object.

        :param url: URL for the new :class:`Request` object.
        :param \*\*kwargs: Optional arguments that ``request`` takes.
        :rtype: requests.Response
        rI   TZOPTIONS)rg   rc   )r:   rU   r   r%   r%   r)   options  s    zSession.optionsc             K   s   |j dd | jd|f|S )zSends a HEAD request. Returns :class:`Response` object.

        :param url: URL for the new :class:`Request` object.
        :param \*\*kwargs: Optional arguments that ``request`` takes.
        :rtype: requests.Response
        rI   Fri   )rg   rc   )r:   rU   r   r%   r%   r)   head"  s    zSession.headc             K   s   | j d|f||d|S )a  Sends a POST request. Returns :class:`Response` object.

        :param url: URL for the new :class:`Request` object.
        :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
        :param json: (optional) json to send in the body of the :class:`Request`.
        :param \*\*kwargs: Optional arguments that ``request`` takes.
        :rtype: requests.Response
        rk   )r|   r}   )rc   )r:   rU   r|   r}   r   r%   r%   r)   post-  s    
zSession.postc             K   s   | j d|fd|i|S )aY  Sends a PUT request. Returns :class:`Response` object.

        :param url: URL for the new :class:`Request` object.
        :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
        :param \*\*kwargs: Optional arguments that ``request`` takes.
        :rtype: requests.Response
        ZPUTr|   )rc   )r:   rU   r|   r   r%   r%   r)   put9  s    	zSession.putc             K   s   | j d|fd|i|S )a[  Sends a PATCH request. Returns :class:`Response` object.

        :param url: URL for the new :class:`Request` object.
        :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
        :param \*\*kwargs: Optional arguments that ``request`` takes.
        :rtype: requests.Response
        ZPATCHr|   )rc   )r:   rU   r|   r   r%   r%   r)   patchD  s    	zSession.patchc             K   s   | j d|f|S )zSends a DELETE request. Returns :class:`Response` object.

        :param url: URL for the new :class:`Request` object.
        :param \*\*kwargs: Optional arguments that ``request`` takes.
        :rtype: requests.Response
        ZDELETE)rc   )r:   rU   r   r%   r%   r)   deleteO  s    zSession.deletec             K   s~  |j d| j |j d| j |j d| j |j d| j t|trJtd|jdd}|j	d}|j
}| j|jd}t }|j|f|}t | }	t|	d	|_td
||f|}|jrx |jD ]}
t| j|
j|
j qW t| j||j | j||f|}|r
dd |D ng }|r.|jd| |j }||_|sny"t| j||fddi||_W n tk
rl   Y nX |sz|j |S )zISend a given PreparedRequest.

        :rtype: requests.Response
        rD   rF   rG   rH   z#You can only send PreparedRequests.rI   T)rU   )Zsecondsr1   c             S   s   g | ]}|qS r%   r%   )r&   r;   r%   r%   r)   r*     s    z Session.send.<locals>.<listcomp>r   r_   )rg   rD   rF   rG   rH   r+   r   
ValueErrorrX   r2   rs   get_adapterrU   preferred_clockr]   r   elapsedr   rL   r   rZ   rc   rO   rb   insertnextZ_nextStopIterationrM   )r:   rc   r   rI   rD   rs   adapterstartrr   r;   genrL   r%   r%   r)   r]   Y  sB    


"zSession.sendc       
      C   s   | j rr|dk	r|jdnd}t||d}x |j D ]\}}	|j||	 q2W |dksZ|dkrrtjjdpptjjd}t|| j}t|| j	}t|| j
}t|| j}||||dS )z^
        Check the environment and merge it with some settings.

        :rtype: dict
        Nre   )re   TZREQUESTS_CA_BUNDLEZCURL_CA_BUNDLE)rF   rH   rD   rG   )rd   r2   r   r-   rg   osenvironr0   rH   rD   rF   rG   )
r:   rU   rH   rD   rF   rG   re   Zenv_proxiesr'   r(   r%   r%   r)   r     s    z"Session.merge_environment_settingsc             C   s:   x(| j j D ]\}}|j j|r|S qW td| dS )z~
        Returns the appropriate connection adapter for the given URL.

        :rtype: requests.adapters.BaseAdapter
        z*No connection adapters were found for '%s'N)ru   r-   lowerrT   r   )r:   rU   prefixr   r%   r%   r)   r     s    zSession.get_adapterc             C   s    x| j j D ]}|j  qW dS )z+Closes all adapters and as such the sessionN)ru   valuesrS   )r:   r(   r%   r%   r)   rS     s    zSession.closec                sB   || j  <  fdd| j D }x|D ]}| j j|| j |< q$W dS )zwRegisters a connection adapter to a prefix.

        Adapters are sorted in descending order by prefix length.
        c                s    g | ]}t |t  k r|qS r%   )rQ   )r&   r'   )r   r%   r)   r*     s    z!Session.mount.<locals>.<listcomp>N)ru   rX   )r:   r   r   Zkeys_to_mover/   r%   )r   r)   rv     s    

zSession.mountc                s   t  fdd jD }|S )Nc             3   s   | ]}|t  |d fV  qd S )N)getattr)r&   attr)r:   r%   r)   	<genexpr>  s    z'Session.__getstate__.<locals>.<genexpr>)dict	__attrs__)r:   stater%   )r:   r)   __getstate__  s    zSession.__getstate__c             C   s&   x |j  D ]\}}t| || q
W d S )N)r-   setattr)r:   r   r   valuer%   r%   r)   __setstate__  s    zSession.__setstate__)NNNNNNNTNNNNNN)NN)N)N)rn   ro   rp   __doc__r   rw   rx   rz   r   rc   r2   r   r   r   r   r   r   r]   r   r   rS   rv   r   r   r%   r%   r%   r)   rq   G  s2   
7)  
D



Irq   c               C   s   t  S )zQ
    Returns a :class:`Session` for context-management.

    :rtype: Session
    )rq   r%   r%   r%   r)   session  s    r   )>r   r   platformZtimecollectionsr   Zdatetimer   rr   r   compatr   r   r   r	   r
   rZ   r   r   r   r   Zmodelsr   r   r   rs   r   r   Z_internal_utilsr   Zutilsr   r   
exceptionsr   r   r   r   Z
structuresr   ru   r   r   r   r   r    r!   r"   Zstatus_codesr#   r$   systemZperf_counterr   AttributeErrorZclockr0   r3   objectr4   rq   r   r%   r%   r%   r)   <module>	   sB    
 h   "