
    G              	          S r SSKrSSKJr  SSKJs  Jr  SSKJs  J	r
  SSKJ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/r " S	 S
\R4                  " S
/ SQ5      5      r " S S\5      r " S S\5      rg)z6Library for handling batch HTTP requests for apitools.    N)http_client)urllib_parse)range)
exceptions)http_wrapperBatchApiRequestc                       \ rS rSrSrSrg)RequestResponseAndHandler)   a'  Container for data related to completing an HTTP request.

This contains an HTTP request, its response, and a callback for handling
the response from the server.

Attributes:
  request: An http_wrapper.Request object representing the HTTP request.
  response: The http_wrapper.Response object returned from the server.
  handler: A callback function accepting two arguments, response
    and exception. Response is an http_wrapper.Response object, and
    exception is an apiclient.errors.HttpError object if an error
    occurred, or otherwise None.
 N)__name__
__module____qualname____firstlineno____doc____static_attributes__r       )lib/third_party/apitools/base/py/batch.pyr
   r
   )   s    r   r
   )requestresponsehandlerc                   T    \ rS rSrSr " S S\5      r  S
S jrSS jr  SS jr	S	r
g)r   ;   z4Batches multiple api requests into a single request.c                   t    \ rS rSrSrS r\S 5       r\S 5       r\S 5       r	\S 5       r
\S 5       rS	 rS
rg)BatchApiRequest.ApiCall>   a  Holds request and response information for each request.

ApiCalls are ultimately exposed to the client once the HTTP
batch request has been completed.

Attributes:
  http_request: A client-supplied http_wrapper.Request to be
      submitted to the server.
  response: A http_wrapper.Response object given by the server as a
      response to the user request, or None if an error occurred.
  exception: An apiclient.errors.HttpError object if an error
      occurred, or None.

c                     [        [        U[        R                  /-   5      5      U l        SU l        X0l        X@l        Xl        SU l	        SU l
        g)a  Initialize an individual API request.

Args:
  request: An http_wrapper.Request object.
  retryable_codes: A list of integer HTTP codes that can
      be retried.
  service: A service inheriting from base_api.BaseApiService.
  method_config: Method config for the desired API request.

N)listsetr   UNAUTHORIZED_ApiCall__retryable_codes_ApiCall__http_response_ApiCall__service_ApiCall__method_confighttp_request_ApiCall__response_ApiCall__exception)selfr   retryable_codesservicemethod_configs        r   __init__ BatchApiRequest.ApiCall.__init__O   sP     &*O{'?'?&@@A&CD"#'D $N#0  '"DO#Dr   c                     U R                   S L$ N)	exceptionr(   s    r   is_error BatchApiRequest.ApiCall.is_errore   s    >>--r   c                     U R                   $ r/   )r&   r1   s    r   r    BatchApiRequest.ApiCall.responsei   s    ??"r   c                     U R                   $ r/   )r'   r1   s    r   r0   !BatchApiRequest.ApiCall.exceptionm   s    ###r   c                 v    U R                   =(       a'    U R                   R                  [        R                  :H  $ r/   )r"   status_coder   r    r1   s    r   authorization_failed,BatchApiRequest.ApiCall.authorization_failedq   s1    (( N$$00K4L4LLOr   c                 f    U R                   c  gU R                   R                  nXR                  ;  $ )NF)r"   r9   r!   )r(   response_codes     r   terminal_state&BatchApiRequest.ApiCall.terminal_statev   s1    ##+ 00<<M (>(>>>r   c                     Xl         X l        U R                  (       aH  U R                  (       d6  U R                  R	                  U R
                  U R                   5      U l        ggg)a  Handles incoming http response to the request in http_request.

This is intended to be used as a callback function for
BatchHttpRequest.Add.

Args:
  http_response: Deserialized http_wrapper.Response object.
  exception: apiclient.errors.HttpError object if an error
      occurred.

N)r"   r'   r>   r#   ProcessHttpResponser$   r&   )r(   http_responser0   s      r   HandleResponse&BatchApiRequest.ApiCall.HandleResponse}   sQ     $1 (""4+;+;"&.."D"D(($*>*>#@ ,<"r   )__exception__http_response__method_config
__response__retryable_codes	__servicer%   N)r   r   r   r   r   r,   propertyr2   r   r0   r:   r>   rC   r   r   r   r   ApiCallr   >   sx    		$, 
	. 
	. 
	# 
	# 
	$ 
	$ 
	O 
	O 
	? 
	?	@r   rL   Nc                 ^    / U l         U=(       d    / U l        U=(       d    SU l        X0l        g)zInitialize a batch API request object.

Args:
  batch_url: Base URL for batch API calls.
  retryable_codes: A list of integer HTTP codes that can be retried.
  response_encoding: The encoding type of response content.
z https://www.googleapis.com/batchN)api_requestsr)   	batch_urlresponse_encoding)r(   rO   r)   rP   s       r   r,   BatchApiRequest.__init__   s,     .4""H&H!2r   c                     UR                  U5      nUR                  U5      nUR                  XSUUS9nU R                  XpR                  X5      nU R
                  R                  U5        g)a  Add a request to the batch.

Args:
  service: A class inheriting base_api.BaseApiService.
  method: A string indicated desired method from the service. See
      the example in the class docstring.
  request: An input message appropriate for the specified
      service.method.
  global_params: Optional additional parameters to pass into
      method.PrepareHttpRequest.

Returns:
  None

)global_paramsupload_configN)GetMethodConfigGetUploadConfigPrepareHttpRequestrL   r)   rN   append)	r(   r*   methodr   rS   r+   rT   r%   api_requests	            r   AddBatchApiRequest.Add   ss    "  //7//7 11-' 2 )
 ll..H  -r   c                    U R                    Vs/ s H  nUR                  (       a  M  UPM     nnU=(       d    [        U5      n[        U5       GHk  n	U	(       a  [        R
                  " U5        [        S[        U5      U5       H  n
[        U R                  UU R                  S9n[        R                  " UXU-   5       H)  nUR                  UR                  UR                  5        M+     UR                  U5        [        UR                   S5      (       d  M  [#        S [        R                  " UXU-   5       5       5      (       d  M  UR                   R$                  R'                  U5        M     U R                    Vs/ s H  nUR                  (       a  M  UPM     nnU(       a  GMa    U R                   $    U R                   $ s  snf s  snf )ai  Execute all of the requests in the batch.

Args:
  http: httplib2.Http object for use in the request.
  sleep_between_polls: Integer number of seconds to sleep between
      polls.
  max_retries: Max retries. Any requests that have not succeeded by
      this number of retries simply report the last response or
      exception, whatever it happened to be.
  max_batch_size: int, if specified requests will be split in batches
      of given size.
  batch_request_callback: function of (http_response, exception) passed
      to BatchHttpRequest which will be run on any given results.

Returns:
  List of ApiCalls.
r   )rO   callbackrP   credentialsc              3   :   #    U  H  nUR                   v   M     g 7fr/   )r:   ).0r   s     r   	<genexpr>*BatchApiRequest.Execute.<locals>.<genexpr>   s$      O+Nw #77+Ns   )rN   r>   lenr   timesleepBatchHttpRequestrO   rP   	itertoolsislicer[   r%   rC   Executehasattrr   anyr_   refresh)r(   httpsleep_between_pollsmax_retriesmax_batch_sizebatch_request_callbackr   requests
batch_sizeattemptibatch_http_requests               r   rj   BatchApiRequest.Execute   s   & ,0+<+< 3+<"11 +< 3#4s8}
[)G

./1c(mZ8 &6"nn3&*&<&<&"
  )//01z> CG&**,,g.D.DF C #**404<<77 O*3*:*:8;<*n+NO O O 0088>% 9* 04/@/@ 0/@G..  /@H 08   = *<    E3:0s   GGGG)rN   rO   rP   r)   )NNNr/   )   ry   NN)r   r   r   r   r   objectrL   r,   r[   rj   r   r   r   r   r   r   ;   s7    >O@& O@b 8<#'3.< @A<@5!r   c                   `    \ rS rSrSrSS jrS r\S 5       rS r	S r
S	 rSS
 jrS rS rSrg)rg      zDBatches multiple http_wrapper.Request objects into a single request.Nc                     Xl         X l        X0l        0 U l        [        R
                  " 5       U l        [        R                  " 5       U l	        g)a  Constructor for a BatchHttpRequest.

Args:
  batch_url: URL to send batch requests to.
  callback: A callback to be called for each response, of the
      form callback(response, exception). The first parameter is
      the deserialized Response object. The second is an
      apiclient.errors.HttpError exception object if an HTTP error
      occurred while processing the request, or None if no error
      occurred.
  response_encoding: The encoding type of response content.
N)
_BatchHttpRequest__batch_url_BatchHttpRequest__callback$_BatchHttpRequest__response_encoding,_BatchHttpRequest__request_response_handlersrh   count_BatchHttpRequest__last_auto_iduuiduuid4_BatchHttpRequest__base_id)r(   rO   r^   rP   s       r   r,   BatchHttpRequest.__init__   sC     % # $5  ,.( (oo/ r   c                 T    SU R                   < S[        R                  " U5      < S3$ )a  Convert an id to a Content-ID header value.

Args:
  request_id: String identifier for a individual request.

Returns:
  A Content-ID header with the id_ encoded into it. A UUID is
  prepended to the value because Content-ID headers are
  supposed to be universally unique.

<+>)r   r   quote)r(   
request_ids     r   _ConvertIdToHeader#BatchHttpRequest._ConvertIdToHeader  s     !NNL,>,>z,JKKr   c                 $   U R                  S5      (       d/  U R                  S5      (       d  [        R                  " SU -  5      eSU ;  a  [        R                  " SU -  5      eU SS R	                  SS5      u  p[
        R                  " U5      $ )a/  Convert a Content-ID header value to an id.

Presumes the Content-ID header conforms to the format that
_ConvertIdToHeader() returns.

Args:
  header: A string indicating the Content-ID header value.

Returns:
  The extracted id value.

Raises:
  BatchError if the header is not in the expected format.
r   r   z Invalid value for Content-ID: %sr      )
startswithendswithr   
BatchErrorrsplitr   unquote)header_r   s      r   _ConvertHeaderToId#BatchHttpRequest._ConvertHeaderToId%  s      !!#&&&//#*>*>''2V;= =f''2V;= =q++C3##J//r   c                 L   [         R                  " UR                  5      n[         R                  " SSUR                  UR
                  S45      n[        U[        R                  5      (       d  UR                  S5      nSR                  UR                  US45      nUR                  R                  SS5      R                  S5      u  pV[        R                   " XV5      nUR                  R#                  5        H  u  pUS:X  a  M  XU'   M     UR$                  US'   UR'                  S	5        UR(                  b  UR+                  UR(                  5        [        R,                  " 5       n
[.        R0                  " U
S
S9nUR3                  USS9  U
R5                  5       nXL-   $ )zConvert a http_wrapper.Request object into a string.

Args:
  request: A http_wrapper.Request to serialize.

Returns:
  The request as a string in application/http format.
 zutf-8 z	HTTP/1.1
content-typezapplication/json/HostNr   )maxheaderlenF)unixfrom)r   urlspliturl
urlunsplitpathquery
isinstancesix	text_typedecodejoinhttp_methodheadersgetsplitmime_nonmultipartMIMENonMultipartitemsnetlocset_unixfrombodyset_payloadStringIO	generator	Generatorflattengetvalue)r(   r   parsedrequest_linestatus_linemajorminormsgkeyvaluestr_iogenr   s                r   _SerializeRequest"BatchHttpRequest._SerializeRequest?  sc    &&w{{3#..V[[&,,35,66'..w7Lii!
 
 **.005c
 	00> "////1JCn$H 2
 mmF<<#OOGLL) !!&q9C%( !!r   c                     UR                  SS5      u  p!UR                  SS5      u  p4n[        R                  " 5       nUR                  U5      n[	        U5      nXGS'   UR                  5       n[        R                  " XxU R                  5      $ )zConvert string into Response and content.

Args:
  payload: Header and body string to be deserialized.

Returns:
  A Response object

r   r      status)	r   email_parserParserparsestrdictget_payloadr   Responser~   )	r(   payloadr   r   r   parserr   infocontents	            r   _DeserializeResponse%BatchHttpRequest._DeserializeResponsem  s      '}}T15"((a01 $$&oog& CyX //#$$TD4D4DEEr   c                 >    [        [        U R                  5      5      $ )z}Create a new id.

Auto incrementing number that avoids conflicts with ids already used.

Returns:
   A new unique id string.
)strnextr   r1   s    r   _NewIdBatchHttpRequest._NewId  s     4++,--r   c                 V    [        USU5      nX0R                  U R                  5       '   g)a  Add a new request.

Args:
  request: A http_wrapper.Request to add to the batch.
  callback: A callback to be called for this response, of the
      form callback(response, exception). The first parameter is the
      deserialized response object. The second is an
      apiclient.errors.HttpError exception object if an HTTP error
      occurred while processing the request, or None if no errors
      occurred.

Returns:
  None
N)r
   r   r   )r(   r   r^   r   s       r   r[   BatchHttpRequest.Add  s&     ,GT8D:A((7r   c                    [         R                  " S5      n[        USS 5        U R                   H}  n[        R
                  " SS5      nSUS'   U R                  U5      US'   U R                  U R                  U   R                  5      nUR                  U5        UR                  U5        M     [        R                  " U R                  S	5      nUR                  5       Ul        S
UR!                  5       -  UR"                  S'   [        R$                  " X5      nUR&                  S:  a  [(        R*                  R-                  U5      eSUR.                  S   -  nUR0                  n	[3        U	[4        5      (       a6  U R6                  (       a%  UR0                  R9                  U R6                  5      n	[:        R<                  " 5       n
U
R?                  X-   5      nURA                  5       (       d  [(        RB                  " S5      eURE                  5        H_  nU RG                  US   5      nU RI                  URE                  5       5      nU R                  U   RK                  US9U R                  U'   Ma     g)a  Serialize batch request, send to server, process response.

Args:
  http: A httplib2.Http object to be used to make the request with.

Raises:
  httplib2.HttpLib2Error if a transport error has occured.
  apiclient.errors.BatchError if the response is the wrong format.
mixed_write_headersc                     g r/   r   r1   s    r   <lambda>+BatchHttpRequest._Execute.<locals>.<lambda>  s    r   applicationrn   binaryzContent-Transfer-Encodingz
Content-IDPOSTzmultipart/mixed; boundary="%s"r   ,  zcontent-type: %s

z'Response not in multipart/mixed format.)r   N)&mime_multipartMIMEMultipartsetattrr   r   r   r   r   r   r   attachr   Requestr~   	as_stringr   get_boundaryr   MakeRequestr9   r   	HttpErrorFromResponser   r   r   bytesr   r   r   r   r   is_multipartr   r   r   r   _replace)r(   rn   messager   r   r   r   r   r   r   r   mime_responsepartr   s                 r   _ExecuteBatchHttpRequest._Execute  s.    !..w7)+<= 33C#44]FKC/7C+, $ 7 7 <C))005==?DOOD!NN3 4 &&t'7'7@((*,0D0D0F+G'  ++D:3&&&33H== ,hmmN.KK""gu%%$*B*B&&--d.F.FGG$$&(89))++''9; ; "--/D00l1CDJ001A1A1CDH 00<EE% F ' ,,Z8 0r   c                 h   U R                  U5        U R                   H  nU R                  U   R                  nU R                  U   R                  nSnUR                  S:  a  [
        R                  R                  U5      nUb  U" X55        U R                  c  M  U R                  X55        M     g)zExecute all the requests as a single batched HTTP request.

Args:
  http: A httplib2.Http object to be used with the request.

Returns:
  None

Raises:
  BatchError if the response is the wrong format.
Nr   )	r   r   r   r   r9   r   r   r   r   )r(   rn   r   r   r^   r0   s         r   rj   BatchHttpRequest.Execute  s     	d33C77<EEH77<DDHI##s*&00==hG	#-*4 4r   )	__base_id__batch_url
__callback__last_auto_id__request_response_handlers__response_encoding)NNr/   )r   r   r   r   r   r,   r   staticmethodr   r   r   r   r[   r   rj   r   r   r   r   rg   rg      sG    N&@L 0 02,"\F4.B$:(x5r   rg   )r   collectionsemail.generatorr   email.mime.multipartmime	multipartr   email.mime.nonmultipartnonmultipartr   email.parserr   r   rh   re   r   r   	six.movesr   r   r   apitools.base.pyr   r   __all__
namedtupler
   rz   r   rg   r   r   r   <module>r     s   " =  # - - 3 3 #    
 ! "  ' ) 
 6 6#%G!I $u!f u!pG5v G5r   