
    t                        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 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/m0Z0m1Z1 ddl2m3Z3 ddlm4Z4 ejj                  dk(  r	 ejl                  Z7nej                  Z7efdZ:efdZ; G d de<      Z= G d de=      Z>d Z?y# e8$ r ejr                  Z7Y 7w xY w)z
requests.sessions
~~~~~~~~~~~~~~~~~

This module provides a Session object to manage and persist settings across
requests (cookies, auth, proxies).
    N)	timedelta)OrderedDict   )_basic_auth_str)	cookielibis_py3urljoinurlparseMapping)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DEFAULT_PORTS)TooManyRedirectsInvalidSchemaChunkedEncodingErrorContentDecodingError)CaseInsensitiveDict)HTTPAdapter)requote_uriget_environ_proxiesget_netrc_authshould_bypass_proxiesget_auth_from_urlrewind_bodyresolve_proxies)codes)REDIRECT_STATIwin32c                    || S | |S t        |t              rt        | t              s| S  |t        |            }|j                  t        |              |j	                         D cg c]
  \  }}|	| }}}|D ]  }||=  |S c c}}w )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`
    )
isinstancer   r   updateitems)request_settingsession_setting
dict_classmerged_settingkv	none_keyskeys           ,platform/bq/third_party/requests/sessions.pymerge_settingr6   3   s      00 @AN//:; "0!5!5!7E!7v119!7IE3  	 Fs   )
B4Bc                 |    ||j                  d      g k(  r| S | | j                  d      g k(  r|S t        | ||      S )zProperly merges both requests and session hooks.

    This is necessary because when request_hooks == {'response': []}, the
    merge breaks Session hooks entirely.
    response)getr6   )request_hookssession_hooksr/   s      r5   merge_hooksr<   R   sO      1 1* = C 1 1* = CzBB    c                   6    e Zd Zd Zd Z	 	 ddZd Zd Zd Zy)	SessionRedirectMixinc                     |j                   r2|j                  d   }t        r|j                  d      }t	        |d      S y)z7Receives a Response. Returns a redirect URI or ``None``locationlatin1utf8N)is_redirectheadersr   encoder   )selfresprA   s      r5   get_redirect_targetz(SessionRedirectMixin.get_redirect_targetc   s>     ||J/H #??84#Hf55r=   c                    t        |      }t        |      }|j                  |j                  k7  ry|j                  dk(  r,|j                  dv r|j                  dk(  r|j                  dv ry|j                  |j                  k7  }|j                  |j                  k7  }t	        j
                  |j                  d      df}|s|j                  |v r|j                  |v ry|xs |S )zFDecide whether Authorization header should be removed when redirectingThttp)P   Nhttps)i  NFN)r
   hostnameschemeportr   r9   )rG   old_urlnew_url
old_parsed
new_parsedchanged_portchanged_schemedefault_ports           r5   should_strip_authz&SessionRedirectMixin.should_strip_authx   s    g&
g&
*"5"55
 'JOOz,I%%0Z__5S "*//9#**j.?.??%))**;*;TBDI:??l#BOO|3 -~-r=   Nc	           
   +     K   g }
| j                  |      }t        |j                        j                  }|r|j	                         }|
j                  |       |
dd |_        	 |j                   t        |j                        | j                  k\  r&t        dj!                  | j                        |      |j#                          |j%                  d      r;t        |j                        }dj'                  t)        |j*                        |g      }t        |      }|j                  d	k(  r|r|j-                  |
      }n|j                  r|j                  }|j/                         }|j0                  s t3        |j                  t5        |            }nt5        |      }t)        |      |_        | j7                  ||       |j8                  t:        j<                  t:        j>                  fvr,d}|D ]  }|j@                  jC                  |d         d|_"        |j@                  }|jC                  dd       tG        |jH                  ||j                         tK        |jH                  | jL                         |jO                  |jH                         | jQ                  ||      }| jS                  ||       |jT                  duxr
 d|v xs d|v }|rtW        |       |}|r| nP | jX                  |f|||||dd|	}tG        | jL                  ||j                         | j                  |      }| |ryy# t        t        t        f$ r  |j                  j                  d       Y w xY ww)zBReceives a Response. Returns a generator of Responses or Requests.r   NF)decode_contentzExceeded {} redirects.)r8   z//: )fragment)Content-LengthzContent-TypeTransfer-EncodingCookier^   r_   )streamtimeoutverifycertproxiesallow_redirects)-rI   r
   urlr]   copyappendhistorycontentr   r   RuntimeErrorrawreadlenmax_redirectsr   formatclose
startswithjoinr   rO   _replacegeturlnetlocr	   r   rebuild_methodstatus_coder&   temporary_redirectpermanent_redirectrE   popbodyr   _cookiesr   cookiesprepare_cookiesrebuild_proxiesrebuild_auth_body_positionr$   send)rG   rH   reqra   rb   rc   rd   re   yield_requestsadapter_kwargshistrg   previous_fragmentprepared_requestparsed_rurlparsedpurged_headersheaderrE   
rewindables                       r5   resolve_redirectsz&SessionRedirectMixin.resolve_redirects   s%     &&t,$SWW-66"xxz KK8DL4 4<< D$6$66&'?'F'FtGYGY'Zeijj JJL ~~d#&txx0hh 01C1C DcJK c]F"$):2CD$*OO!--/C
 ==dhhC(89!#&#3C#8  0$7 (@(@%BZBZ'[[!X,F$,,00> -(, %&..GKK$'
 ##3#<#<c488L*33T\\B,,-=-F-FG **+;WEG.5 !//t; P!W,N0Cw0N  ,- #C	 !tyy	!#!#$)	 %	 't||5EtxxP ..t4
I  )*>M 4U34s1   A!M7$M  0KM7>M7 0M40M73M44M7c                     |j                   }|j                  }d|v r)| j                  |j                  j                  |      r|d= | j                  rt        |      nd}||j                  |       yy)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.
        AuthorizationN)rE   rg   rX   request	trust_envr!   prepare_auth)rG   r   r8   rE   rg   new_auths         r5   r   z!SessionRedirectMixin.rebuild_auth   su    
 #**""g%$*@*@AQAQAUAUWZ*[ ( +/..>#&d))(3  r=   c                 
   |j                   }t        |j                        j                  }t	        ||| j
                        }d|v r|d= 	 t        ||         \  }}|r|rt        ||      |d<   |S # t        $ r d\  }}Y %w xY w)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
        zProxy-AuthorizationNN)	rE   r
   rg   rO   r%   r   r#   KeyErrorr   )rG   r   re   rE   rO   new_proxiesusernamepasswords           r5   r   z$SessionRedirectMixin.rebuild_proxies  s     #***../66%&6P G+-.	,!2;v3F!GHh -<Xx-PG)*  	,!+Hh	,s   A1 1BBc                    |j                   }|j                  t        j                  k(  r|dk7  rd}|j                  t        j                  k(  r|dk7  rd}|j                  t        j
                  k(  r|dk(  rd}||_         y)zWhen being redirected we may want to change the method of the request
        based on certain specs or browser behavior.
        HEADGETPOSTN)methodry   r&   	see_otherfoundmoved)rG   r   r8   r   s       r5   rx   z#SessionRedirectMixin.rebuild_method.  sx     "(( 5??2v7GF 5;;.6V3CF 5;;.6V3CF"(r=   )FNTNNF)	__name__
__module____qualname__rI   rX   r   r   r   rx    r=   r5   r?   r?   a   s,    *.2 BFOTl\4$:)r=   r?   c                       e Zd ZdZg dZd Zd Zd Zd Z	 	 	 ddZ	d	 Z
d
 Zd ZddZddZddZd Zd Zd Zd Zd Zd Zd Zd Zy)Sessiona  A Requests session.

    Provides cookie persistence, connection-pooling, and configuration.

    Basic Usage::

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

    Or as a context manager::

      >>> with requests.Session() as s:
      ...     s.get('https://httpbin.org/get')
      <Response [200]>
    )rE   r   authre   hooksparamsrc   rd   adaptersra   r   rp   c                 ^   t               | _        d | _        i | _        t	               | _        i | _        d| _        d| _        d | _	        t        | _        d| _        t        i       | _        t               | _        | j#                  dt%                      | j#                  dt%                      y )NFTzhttps://zhttp://)r   rE   r   re   r   r   r   ra   rc   rd   r   rp   r   r   r   r   r   mountr   rG   s    r5   __init__zSession.__init__^  s    
 '( 	
  #_

    	 4  +2. $

:{}-

9km,r=   c                     | S Nr   r   s    r5   	__enter__zSession.__enter__  s    r=   c                 $    | j                          y r   )rr   )rG   argss     r5   __exit__zSession.__exit__  s    

r=   c                    |j                   xs i }t        |t        j                        st	        |      }t        t        t               | j                         |      }|j                  }| j                  r#|s!| j                  st        |j                        }t               }|j                  |j                  j                         |j                  |j                  |j                   |j"                  t%        |j&                  | j&                  t(              t%        |j*                  | j*                        t%        || j                        |t-        |j.                  | j.                        
       |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/   )
r   rg   filesdatajsonrE   r   r   r   r   )r   r*   r   	CookieJarr   r   r   r   r   r!   rg   r   preparer   upperr   r   r   r6   rE   r   r   r<   r   )rG   r   r   merged_cookiesr   ps         r5   prepare_requestzSession.prepare_request  s    //'R '9#6#67)'2G '+-t||<gG ||>>$tyy!'++.D			>>'')--!'//4<<L_` =tTYY/"gmmTZZ8 	 	
 r=   Nc                    t        |j                         ||||xs i ||xs i |||
      }| j                  |      }|xs i }| j                  |j                  ||||      }|	|
d}|j                  |        | j                  |fi |}|S )ax	  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, list of tuples, 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``. When set to
            ``False``, requests will accept any TLS certificate presented by
            the server, and will ignore hostname mismatches and/or expired
            certificates, which will make your application vulnerable to
            man-in-the-middle (MitM) attacks. Setting verify to ``False`` 
            may be useful during local development or testing.
        :param cert: (optional) if String, path to ssl client cert file (.pem).
            If Tuple, ('cert', 'key') pair.
        :rtype: requests.Response
        )
r   rg   rE   r   r   r   r   r   r   r   )rb   rf   )r   r   r   merge_environment_settingsrg   r+   r   )rG   r   rg   r   r   rE   r   r   r   rb   rf   re   r   ra   rc   rd   r   r   prepsettingssend_kwargsrH   s                         r5   r   zSession.request  s    \ <<><R
 ##C(-R22HHgvvt
 .
 	8$tyy--r=   c                 N    |j                  dd        | j                  d|fi |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
        rf   Tr   
setdefaultr   rG   rg   kwargss      r5   r9   zSession.get  s-     	+T2t||E31&11r=   c                 N    |j                  dd        | j                  d|fi |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
        rf   TOPTIONSr   r   s      r5   optionszSession.options!  s-     	+T2t||Is5f55r=   c                 N    |j                  dd        | j                  d|fi |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
        rf   Fr   r   r   s      r5   headzSession.head,  s-     	+U3t||FC2622r=   c                 0     | 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, list of tuples, 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
        r   )r   r   r   )rG   rg   r   r   r   s        r5   postzSession.post7  s#     t||FCHdHHHr=   c                 .     | j                   d|fd|i|S )au  Sends a PUT request. Returns :class:`Response` object.

        :param url: URL for the new :class:`Request` object.
        :param data: (optional) Dictionary, list of tuples, bytes, or file-like
            object to send in the body of the :class:`Request`.
        :param \*\*kwargs: Optional arguments that ``request`` takes.
        :rtype: requests.Response
        PUTr   r   rG   rg   r   r   s       r5   putzSession.putD  s!     t||E3<T<V<<r=   c                 .     | j                   d|fd|i|S )aw  Sends a PATCH request. Returns :class:`Response` object.

        :param url: URL for the new :class:`Request` object.
        :param data: (optional) Dictionary, list of tuples, bytes, or file-like
            object to send in the body of the :class:`Request`.
        :param \*\*kwargs: Optional arguments that ``request`` takes.
        :rtype: requests.Response
        PATCHr   r   r   s       r5   patchzSession.patchP  s!     t||GS>t>v>>r=   c                 *     | j                   d|fi |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
        DELETEr   r   s      r5   deletezSession.delete\  s     t||Hc4V44r=   c                 f   |j                  d| j                         |j                  d| j                         |j                  d| j                         d|vr$t	        || j
                  | j                        |d<   t        |t              rt        d      |j                  dd      }|j                  d      }|j                  }| j                  |j                        }t               } |j                   |fi |}t               |z
  }	t#        |		      |_        t'        d
||fi |}|j(                  r<|j(                  D ]-  }
t+        | j,                  |
j.                  |
j0                         / t+        | j,                  ||j0                         |r$ | j2                  ||fi |}|D 
cg c]  }
|
 }}
ng }|r)|j5                  d|       |j                         }||_        |s%	 t7         | j2                  ||fddi|      |_        |s|j<                   |S c c}
w # t:        $ r Y  w xY w)zISend a given PreparedRequest.

        :rtype: requests.Response
        ra   rc   rd   re   z#You can only send PreparedRequests.rf   T)rg   )secondsr8   r   r   )r   ra   rc   rd   r%   re   r   r*   r   
ValueErrorr|   r9   r   get_adapterrg   preferred_clockr   r   elapsedr   rj   r   r   r   rm   r   insertnext_nextStopIterationrk   )rG   r   r   rf   ra   r   adapterstartrr   rH   genrj   s                r5   r   zSession.sendf  s    	(DKK0(DKK0&$)),F" /t~~!F9 gw'BCC !**%6=H% ""w{{"3  ! GLL+F+ "#e+g.	 *eQ9&9 99 		&t||T\\488L " 	t||Waee< ($((G>v>C(+,tG,G NN1a AAI 5t55a`QU`Y_`a II- -  ! s   /	H+$H$ $	H0/H0c                    | j                   r||j                  d      nd}t        ||      }|j                         D ]  \  }}	|j	                  ||	        |du s|@t
        j                  j                  d      xs t
        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
        Nno_proxy)r   TREQUESTS_CA_BUNDLECURL_CA_BUNDLE)rc   re   ra   rd   )r   r9   r    r,   r   osenvironr6   re   ra   rc   rd   )
rG   rg   re   ra   rc   rd   r   env_proxiesr1   r2   s
             r5   r   z"Session.merge_environment_settings  s     >>292Ew{{:.4H-cHEK%++-A""1a( .
 ~**..)=> ;**..)9:   6vt{{3vt{{3T499- W 	r=   c                     | j                   j                         D ]6  \  }}|j                         j                  |j                               s4|c S  t	        dj                  |            )z~
        Returns the appropriate connection adapter for the given URL.

        :rtype: requests.adapters.BaseAdapter
        z*No connection adapters were found for {!r})r   r,   lowerrs   r   rq   )rG   rg   prefixr   s       r5   r   zSession.get_adapter  sY     "&!4!4!6VWyy{%%flln5 "7 HOOPSTUUr=   c                 b    | j                   j                         D ]  }|j                           y)z+Closes all adapters and as such the sessionN)r   valuesrr   )rG   r2   s     r5   rr   zSession.close  s"    %%'AGGI (r=   c                     || j                   |<   | j                   D cg c]  }t        |      t        |      k  s| }}|D ]*  }| j                   j                  |      | j                   |<   , yc c}w )zwRegisters a connection adapter to a prefix.

        Adapters are sorted in descending order by prefix length.
        N)r   ro   r|   )rG   r   r   r1   keys_to_mover4   s         r5   r   zSession.mount  sf    
 !(f#'==I=aCFS[4H=IC!%!2!23!7DMM#   Js
   A1A1c           	      Z    | j                   D ci c]  }|t        | |d        }}|S c c}w r   )	__attrs__getattr)rG   attrstates      r5   __getstate__zSession.__getstate__  s3    =A^^L^TwtT400^L Ms   (c                 N    |j                         D ]  \  }}t        | ||        y r   )r,   setattr)rG   r   r   values       r5   __setstate__zSession.__setstate__  s"     ;;=KD%D$& )r=   )NNNNNNNTNNNNNNr   r   )r   r   r   __doc__r   r   r   r   r   r   r9   r   r   r   r   r   r   r   r   r   rr   r   r   r  r   r=   r5   r   r   E  s    $I<-|&R GKCGBFJX	2	6	3I
=
?5L\:V
	8'r=   r   c                      t               S )aZ  
    Returns a :class:`Session` for context-management.

    .. deprecated:: 1.0.0

        This method has been deprecated since version 1.0.0 and is only kept for
        backwards compatibility. New code should use :class:`~requests.sessions.Session`
        to create a session. This may be removed at a future date.

    :rtype: Session
    )r   r   r=   r5   sessionr    s     9r=   )@r  r   systimedatetimer   collectionsr   r   r   compatr   r   r	   r
   r   r   r   r   r   r   modelsr   r   r   r   r   r   _internal_utilsr   utilsr   r   r   
exceptionsr   r   r   r   
structuresr   r   r   r   r    r!   r"   r#   r$   r%   status_codesr&   r'   platformperf_counterr   AttributeErrorclockr6   r<   objectr?   r   r  r   r=   r5   <module>r     s    
 
   # ! A AS S D D / - B BQ Q , !  
   # <<7%++ iiO @K > :E Ca)6 a)Hp'" p'fW  %**%s   #C   C43C4