
    ]<              	          S r SSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKJ	r	  SSK
Jr  SSKJr  SSKJr   SSKJr  / S	QrS
rSr\	R.                  \	R0                  \	R2                  \	R4                  \4r\R8                  " S/ SQ5      r\R<                  S S j5       r " S S\ 5      r! " S S\R8                  " S/ SQ5      5      r"S r#S r$S r%S r&SSS\&\#4S jr'S\#4S jr(/ r)S r*S r+g! \ a	    SSKJr   Nf = f)!zpHTTP wrapper for apitools.

This library wraps the underlying http library we use, which is
currently httplib2.
    N)http_client)parse)
exceptions)util)HttpAccessTokenRefreshError)AccessTokenRefreshError)CheckResponseGetHttp)HandleExceptionsAndRebuildHttpConnectionsMakeRequestRebuildHttpConnectionsRequestResponseRethrowExceptionHandler4  i  ExceptionRetryArgs)httphttp_requestexcnum_retriesmax_retry_waittotal_wait_secc              #     #    U R                   c  Sv   g[        R                  n0 nU[        l        UbJ  UR                  R	                  5        H,  u  pVSU;  a  M  UR                  XE'   UR                  U5        M.     Sv   U[        l        UbI  UR	                  5        H4  u  pSXRR                  ;   d  M  UR                  U   R                  U5        M6     gg7f)a  Temporarily change the value of httplib2.debuglevel, if necessary.

If http_request has a `loggable_body` distinct from `body`, then we
need to prevent httplib2 from logging the full body. This sets
httplib2.debuglevel for the duration of the `with` block; however,
that alone won't change the value of existing HTTP connections. If
an httplib2.Http object is provided, we'll also change the level on
any cached connections attached to it.

Args:
  http_request: a Request we're logging.
  level: (int) the debuglevel for logging.
  http: (optional) an httplib2.Http whose connections we should
    set the debuglevel on.

Yields:
  None.
N:)loggable_bodyhttplib2
debuglevelconnectionsitemsset_debuglevel)r   levelr   	old_levelhttp_levelsconnection_key
connections          0lib/third_party/apitools/base/py/http_wrapper.py_Httplib2Debuglevelr'   K   s     ( !!)##IKH*.*:*:*@*@*B&N
 .(*4*?*?K'%%e, +C 
#H)4):):)<%N!1!11  0??	J *= s   B1C7$Cc                       \ rS rSrSrS
S jr\S 5       r\R                  S 5       r\S 5       r	\	R                  S 5       r	S	r
g)r   w   z1Class encapsulating the data for an HTTP request.Nc                 d    Xl         X l        U=(       d    0 U l        S U l        S U l        X@l        g N)urlhttp_methodheaders_Request__body_Request__loggable_bodybody)selfr,   r-   r.   r1   s        r&   __init__Request.__init__{   s,    &}"#	    c                     U R                   $ r+   )r0   r2   s    r&   r   Request.loggable_body   s    ###r5   c                 V    U R                   c  [        R                  " S5      eXl        g )Nz0Cannot set loggable body on request with no body)r1   r   RequestErrorr0   )r2   values     r&   r   r8      s*    99))BD D$r5   c                     U R                   $ r+   )r/   r7   s    r&   r1   Request.body   s    {{r5   c                 J   Xl         UbL  [        U R                   SS5      =(       d    [        U R                   5      n[        U5      U R                  S'   OU R                  R                  SS5        [        U[        S5      [        R                  45      (       d  SU l
        gg)z>Sets the request body; handles logging and length measurement.Nlengthcontent-lengthz<media body>)r/   getattrlenstrr.   pop
isinstancetypesixstring_typesr   )r2   r;   body_lengths      r&   r1   r=      s     !Xt- A03DKK0@ -0-=DLL)*LL-t4%$t*c.>.>!?@@!/D Ar5   )__body__loggable_bodyr1   r.   r-   r   r,   ) GETNrL   )__name__
__module____qualname____firstlineno____doc__r3   propertyr   setterr1   __static_attributes__ r5   r&   r   r   w   sd    ; $ $ % %   
[[0 0r5   r   c                   b    \ rS rSrSrSrS r\S 5       r\S 5       r	\S 5       r
\S 5       rSrg	)
r      z.Class encapsulating data for an HTTP response.rV   c                     U R                   $ r+   )r?   r7   s    r&   __len__Response.__len__   s    {{r5   c                 N   S nSU R                   ;   a%  SU R                   ;   a  U" U R                   S   5      $ SU R                   ;   a$  [        U R                   R                  S5      5      $ SU R                   ;   a  U" U R                   S   5      $ [        U R                  5      $ )zReturn the length of this response.

We expose this as an attribute since using len() directly can fail
for responses larger than sys.maxint.

Returns:
  Response length (as int or long)
c                     U R                  S5      u    pUR                  S5      u  n  nUR                  S5      u  pAn[        U5      [        U5      -
  S-   $ )N /-   )	partitionint)content_range_
range_spec
byte_rangestartends         r&   ProcessContentRange,Response.length.<locals>.ProcessContentRange   sZ    ,66s;Aq)33C8J1&005MEcs8c%j(1,,r5   z-content-encodingzcontent-ranger@   )inforc   getrB   content)r2   rj   s     r&   r?   Response.length   s    	- $))+4990L 'tyy'ABB*tyy}}%5677		)&tyy'ABB4<<  r5   c                 2    [        U R                  S   5      $ )Nstatus)rc   rl   r7   s    r&   status_codeResponse.status_code   s    499X&''r5   c                 T    SU R                   ;   a  [        U R                   S   5      $ g )Nzretry-after)rl   rc   r7   s    r&   retry_afterResponse.retry_after   s'    DII%tyy/00 &r5   c                 T    U R                   [        ;   =(       a    SU R                  ;   $ )Nlocation)rr   _REDIRECT_STATUS_CODESrl   r7   s    r&   is_redirectResponse.is_redirect   s'      $:: (dii'	)r5   N)rN   rO   rP   rQ   rR   	__slots__rZ   rS   r?   rr   ru   rz   rU   rV   r5   r&   r   r      sa     9I ! !4 ( ( 1 1 ) )r5   r   HttpResponse)rl   rn   request_urlc                 6   U c#  [         R                  " SU R                  -  5      eU R                  S:  d  U R                  [        :X  a  [         R
                  R                  U 5      eU R                  (       a  [         R                  R                  U 5      eg )Nz,Request to url %s did not return a response.  )	r   r:   r~   rr   TOO_MANY_REQUESTSBadStatusCodeErrorFromResponseru   RetryAfterError)responses    r&   r	   r	      s    %%:  !" 	" 

#
%


"3
3++88BB			((55h?? 
r5   c                     [        U SS5      (       a@  [        U R                  R                  5       5       H  nSU;   d  M  U R                  U	 M     gg)a  Rebuilds all http connections in the httplib2.Http instance.

httplib2 overloads the map in http.connections to contain two different
types of values:
{ scheme string:  connection class } and
{ scheme + authority string : actual http connection }
Here we remove all of the entries for actual connections so that on the
next request httplib2 will rebuild them from the connection types.

Args:
  http: An httplib2.Http instance.
r   Nr   )rA   listr   keys)r   conn_keys     r&   r   r      sK     t]D))T--2245Hh$$X. 6 *r5   c                      e r+   rV   )unused_argss    r&   r   r      s    	r5   c                 6   Sn[        U R                  [        R                  [        R                  [        R
                  45      (       aA  [        R                  " S[        U R                  5      R                  U R                  5        GO[        U R                  [        R                  5      (       a#  [        R                  " SU R                  5        GO[        U R                  [        R                  5      (       a#  [        R                  " SU R                  5        GOe[        U R                  [        R                  5      (       a#  [        R                  " SU R                  5        GO[        U R                  [        R                  5      (       a#  [        R                  " SU R                  5        GO[        U R                  [         5      (       a#  [        R                  " SU R                  5        GO[        U R                  ["        5      (       au  [%        U R                  S5      (       aZ  U R                  R&                  [(        :X  d  U R                  R&                  S	:  a"  [        R                  " S
U R                  5        O[        U R                  [*        R,                  5      (       a  [        R                  " S5        O[        U R                  [*        R.                  5      (       a,  [        R                  " SU R                  R0                  5        Ob[        U R                  [*        R2                  5      (       a-  [        R                  " S5        U R                  R4                  nOU R                  e[7        U R8                  5        [        R                  " SU R:                  R<                  U R                  5        [>        R@                  " U=(       d)    [B        RD                  " U RF                  U RH                  S95        g)zException handler for http failures.

This catches known failures and rebuilds the underlying HTTP connections.

Args:
  retry_args: An ExceptionRetryArgs tuple.
Nz"Caught HTTP error %s, retrying: %sz!Caught socket error, retrying: %sz)Caught socket address error, retrying: %sz)Caught socket timeout error, retrying: %sz+Caught server not found error, retrying: %sz+Response content was invalid (%s), retryingrq   r   z8Caught transient credential refresh error (%s), retryingz&Request returned no response, retryingz%Response returned status %s, retryingz0Response returned a retry-after header, retryingz-Retrying request to url %s after exception %s)max_wait)%rE   r   r   BadStatusLineIncompleteReadResponseNotReadyloggingdebugrF   rN   socketerrorgaierrortimeoutr   ServerNotFoundError
ValueErrorTokenRefreshErrorhasattrrq   r   r   r:   r   rr   r   ru   r   r   r   r,   timesleepr   CalculateWaitForRetryr   r   )
retry_argsru   s     r&   r   r      s    K *..;#<#<#.#=#=#.#?#?#A B B 	::>>*33Z^^	E	JNNFLL	1	19:>>J	JNNFOO	4	47	I	JNNFNN	3	37	I	JNNH$@$@	A	A9:>>	K	JNNJ	/	/ 	C nn	&
Z^^%6
7
7
*..(
+
+>>  $55>>  C'FNN	 
JNNJ$;$;	<	<>?	JNNJ$A$A	B	B= nn00	2	JNNJ$>$>	?	?HI nn00nn:??+MMA))--z~~?JJ 	Ht11""Z-F-FHIr5      <      c                 F   Sn[         R                   " 5       n[        U S5      (       a  [        U R                  5      S1-
  U l          [	        XUUS9$ ! [
         a@  n	US-  nXr:  a  e [         R                   " 5       U-
  n
U" [        XXX:5      5         Sn	A	OSn	A	ff = fM[  )aD  Send http_request via the given http, performing error/retry handling.

Args:
  http: An httplib2.Http instance, or a http multiplexer that delegates to
      an underlying http, for example, HTTPMultiplexer.
  http_request: A Request to send.
  retries: (int, default 7) Number of retries to attempt on retryable
      replies (such as 429 or 5XX).
  max_retry_wait: (int, default 60) Maximum number of seconds to wait
      when retrying.
  redirections: (int, default 5) Number of redirects to follow.
  retry_func: Function to handle retries on exceptions. Argument is an
      ExceptionRetryArgs tuple.
  check_response_func: Function to validate the HTTP response.
      Arguments are (Response, response content, url).

Raises:
  InvalidDataFromServerError: if there is no response after retries.

Returns:
  A Response object.

r   redirect_codesr   )redirectionscheck_response_funcra   N)r   r   setr   _MakeRequestNoRetry	Exceptionr   )r   r   retriesr   r   
retry_funcr   retryfirst_req_timeer   s              r&   r   r   9  s    6 EYY[N t%&&!$"5"56#>
	O&$79 9
  	OQJE!%~!=-d!.<N O O	O s   	
A 
B6BBc           
      P   Sn[        U SS5      (       aO  [        R                  " UR                  5      R                  nU(       a  XPR
                  ;   a  U R
                  U   n[        R                  S:X  a  SOSn[        XU S9   U R                  [        UR                  5      [        UR                  5      UR                  UR                  X$S9u  pxSSS5        Wc  [        R                  " 5       e[!        UWUR                  5      n	U" U	5        U	$ ! , (       d  f       NG= f)ah  Send http_request via the given http.

This wrapper exists to handle translation between the plain httplib2
request/response types and the Request and Response types above.

Args:
  http: An httplib2.Http instance, or a http multiplexer that delegates to
      an underlying http, for example, HTTPMultiplexer.
  http_request: A Request to send.
  redirections: (int, default 5) Number of redirects to follow.
  check_response_func: Function to validate the HTTP response.
      Arguments are (Response, response content, url).

Returns:
  A Response object.

Raises:
  RequestError if no response could be parsed.

Nr      r   )r   )methodr1   r.   r   connection_type)rA   r   urlsplitr,   schemer   r   r   r'   requestrC   r-   r1   r.   r   r:   r   )
r   r   r   r   r   
url_schemenew_debuglevelrl   rn   r   s
             r&   r   r   k  s    , O t]D))^^L$4$45<<
*(8(88"..z:O #--2QN	\	E  !#l.F.F*G""L,@,@% % H 
F |%%''g|'7'78H!O 
F	Es   AD
D%c                 .    [         R                  U 5        g r+   )_HTTP_FACTORIESappend)factorys    r&   _RegisterHttpFactoryr     s    7#r5   c                  f    [          H  nU" S0 U D6nUc  M  Us  $    [        R                  " S0 U D6$ )NrV   )r   r   Http)kwdsr   r   s      r&   r
   r
     s6    "K # == 4  r5   r+   ),rR   collections
contextlibr   r   r   r   rG   	six.movesr   six.moves.urllibr   apitools.base.pyr   r   oauth2client.clientr   r   ImportErrorr   __all__RESUME_INCOMPLETEr   MOVED_PERMANENTLYFOUND	SEE_OTHERTEMPORARY_REDIRECTry   
namedtupler   contextmanagerr'   objectr   r   r	   r   r   r   r   r   r   r   r
   rV   r5   r&   <module>r      sB  "       
 ! " ' !QT	   !!""  !++ ?@ 
 (K (KV(0f (0Z0){%%:< 0)f
@/&

:Iz -.bD$1/Od :;,9,^ $!s  QPQs   C- -C<;C<