
^Yc           @@  s  d  Z  d d l m Z d d l Z d d l m Z d d l m Z d Z d d l m Z m	 Z	 d d l
 m Z m Z m Z m 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 Z d d l Z y d d l Z Wn e k
 rHe   Z n
 Xe j  Z d d	 l! m" Z" d d
 l# m$ Z$ d d l% m& Z& d d l' m( Z( y d d l) m* Z* Wn! e k
 rd d l) m+ Z* n Xd d l, m- Z- d d l. m/ Z/ d d l. m0 Z0 d d l. m1 Z1 d d l. m2 Z2 d d l. m3 Z3 d d l. m4 Z4 d d l5 m6 Z6 e j7 e8  Z9 d d Z: d Z; d Z< d Z= d   Z> d   Z? d e f d     YZ@ d  e f d!     YZA d" e f d#     YZB d$ eB f d%     YZC d& eC f d'     YZD d( eC f d)     YZE d* e f d+     YZF d, e f d-     YZG d. e f d/     YZH d0 e f d1     YZI d2 e f d3     YZJ d4 e f d5     YZK d6 e f d7     YZL d8 e f d9     YZM d:   ZN d;   ZO d<   ZP d S(=   s   Classes to encapsulate a single HTTP request.

The classes implement a command pattern, with every
object supporting an execute() method that does the
actuall HTTP request.
i    (   t   absolute_importN(   t   http_client(   t   ranges$   jcgregorio@google.com (Joe Gregorio)(   t   BytesIOt   StringIO(   t   urlparset
   urlunparset   quotet   unquote(   t	   Generator(   t   MIMEMultipart(   t   MIMENonMultipart(   t
   FeedParser(   t   util(   t   _helpers(   t	   mimeparse(   t
   BatchError(   t	   HttpError(   t   InvalidChunkSizeError(   t   ResumableUploadError(   t   UnexpectedBodyError(   t   UnexpectedMethodError(   t	   JsonModeli   i   i   i  i<   c         C@  s   |  d k r t  S|  t k r  t  S|  t j j j k r | s? t Sy2 t j | j	 d   } | d d d d } Wn+ t
 t t f k
 r t j d |  t SXt j d |  | d k r t  Sn  t S(   s   Determines whether a response should be retried.

  Args:
    resp_status: The response status received.
    content: The response content body. 

  Returns:
    True if the response should be retried, otherwise False.
  i  s   utf-8t   errort   errorsi    t   reasons&   Invalid JSON content from response: %ss*   Encountered 403 Forbidden with reason "%s"t   userRateLimitExceededt   rateLimitExceeded(   R   R   (   t   Truet   _TOO_MANY_REQUESTSt   sixt   movesR   t	   FORBIDDENt   Falset   jsont   loadst   decodet   UnicodeDecodeErrort
   ValueErrort   KeyErrort   LOGGERt   warning(   t   resp_statust   contentt   dataR   (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyt   _should_retry_responseV   s"    c      
   O@  sF  d	 }	 d	 }
 x-t | d  D]} | d k r~ |   d | } t j d | | | | | | |	 rj |	 j n |  | |  n  y( d	 } |  j | | | |  \ }	 }
 WnX t k
 r } | } n@ t j k
 r } t j	 j
 j | j	  d
 k r   n  | } n X| r"| | k r |  q"q n  t |	 j |
  s Pq q W|	 |
 f S(   s  Retries an HTTP request multiple times while handling errors.

  If after all retries the request still fails, last error is either returned as
  return value (for HTTP 5xx errors) or thrown (for ssl.SSLError).

  Args:
    http: Http object to be used to execute request.
    num_retries: Maximum number of retries.
    req_type: Type of the request (used for logging retries).
    sleep, rand: Functions to sleep for random time between retries.
    uri: URI to be requested.
    method: HTTP method to be used.
    args, kwargs: Additional arguments passed to http.request.

  Returns:
    resp, content - Response from the http request (may be HTTP 5xx).
  i   i    i   sC   Sleeping %.2f seconds before retry %d of %d for %s: %s %s, after %st   WSAETIMEDOUTt	   ETIMEDOUTt   EPIPEt   ECONNABORTEDN(   R.   R/   s   EPIPEs   ECONNABORTED(   t   NoneR   R(   R)   t   statust   requestt   _ssl_SSLErrort   socketR   t   errnot	   errorcodet   getR-   (   t   httpt   num_retriest   req_typet   sleept   randt   urit   methodt   argst   kwargst   respR+   t	   retry_numt
   sleep_timet	   exceptiont	   ssl_errort   socket_error(    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyt   _retry_request   s6    "		
	t   MediaUploadProgressc           B@  s    e  Z d  Z d   Z d   Z RS(   s   Status of a resumable upload.c         C@  s   | |  _  | |  _ d S(   s   Constructor.

    Args:
      resumable_progress: int, bytes sent so far.
      total_size: int, total bytes in complete upload, or None if the total
        upload size isn't known ahead of time.
    N(   t   resumable_progresst
   total_size(   t   selfRK   RL   (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyt   __init__   s    	c         C@  s1   |  j  d k	 r) t |  j  t |  j   Sd Sd S(   s   Percent of upload completed, as a float.

    Returns:
      the percentage complete as a float, returning 0.0 if the total size of
      the upload is unknown.
    g        N(   RL   R2   t   floatRK   (   RM   (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyt   progress   s    (   t   __name__t
   __module__t   __doc__RN   RP   (    (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyRJ      s   	t   MediaDownloadProgressc           B@  s    e  Z d  Z d   Z d   Z RS(   s   Status of a resumable download.c         C@  s   | |  _  | |  _ d S(   s   Constructor.

    Args:
      resumable_progress: int, bytes received so far.
      total_size: int, total bytes in complete download.
    N(   RK   RL   (   RM   RK   RL   (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyRN      s    	c         C@  s1   |  j  d k	 r) t |  j  t |  j   Sd Sd S(   s   Percent of download completed, as a float.

    Returns:
      the percentage complete as a float, returning 0.0 if the total size of
      the download is unknown.
    g        N(   RL   R2   RO   RK   (   RM   (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyRP      s    (   RQ   RR   RS   RN   RP   (    (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyRT      s   	
t   MediaUploadc           B@  s   e  Z d  Z d   Z d   Z d   Z d   Z d   Z d   Z d   Z	 e
 j d  d d	   Z d
   Z e d    Z RS(   s  Describes a media object to upload.

  Base class that defines the interface of MediaUpload subclasses.

  Note that subclasses of MediaUpload may allow you to control the chunksize
  when uploading a media object. It is important to keep the size of the chunk
  as large as possible to keep the upload efficient. Other factors may influence
  the size of the chunk you use, particularly if you are working in an
  environment where individual HTTP requests may have a hardcoded time limit,
  such as under certain classes of requests under Google App Engine.

  Streams are io.Base compatible objects that support seek(). Some MediaUpload
  subclasses support using streams directly to upload data. Support for
  streaming may be indicated by a MediaUpload sub-class and if appropriate for a
  platform that stream will be used for uploading the media object. The support
  for streaming is indicated by has_stream() returning True. The stream() method
  should return an io.Base object that supports seek(). On platforms where the
  underlying httplib module supports streaming, for example Python 2.6 and
  later, the stream will be passed into the http library which will result in
  less memory being used and possibly faster uploads.

  If you need to upload media that can't be uploaded using any of the existing
  MediaUpload sub-class then you can sub-class MediaUpload for your particular
  needs.
  c         C@  s   t     d S(   sO   Chunk size for resumable uploads.

    Returns:
      Chunk size in bytes.
    N(   t   NotImplementedError(   RM   (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyt	   chunksize	  s    c         C@  s   d S(   s:   Mime type of the body.

    Returns:
      Mime type.
    s   application/octet-stream(    (   RM   (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyt   mimetype  s    c         C@  s   d S(   sZ   Size of upload.

    Returns:
      Size of the body, or None of the size is unknown.
    N(   R2   (   RM   (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyt   size  s    c         C@  s   t  S(   s]   Whether this upload is resumable.

    Returns:
      True if resumable upload or False.
    (   R!   (   RM   (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyt	   resumable!  s    c         C@  s   t     d S(   s   Get bytes from the media.

    Args:
      begin: int, offset from beginning of file.
      length: int, number of bytes to read, starting at begin.

    Returns:
      A string of bytes read. May be shorter than length if EOF was reached
      first.
    N(   RV   (   RM   t   begint   end(    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyt   getbytes)  s    c         C@  s   t  S(   s  Does the underlying upload support a streaming interface.

    Streaming means it is an io.IOBase subclass that supports seek, i.e.
    seekable() returns True.

    Returns:
      True if the call to stream() will return an instance of a seekable io.Base
      subclass.
    (   R!   (   RM   (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyt
   has_stream6  s    
c         C@  s   t     d S(   s   A stream interface to the data being uploaded.

    Returns:
      The returned value is an io.IOBase subclass that supports seek, i.e.
      seekable() returns True.
    N(   RV   (   RM   (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyt   streamB  s    i   c         C@  sl   t  |   } t j |  j  } | d k	 rE x | D] } | | =q1 Wn  | j | d <| j | d <t j |  S(   s  Utility function for creating a JSON representation of a MediaUpload.

    Args:
      strip: array, An array of names of members to not include in the JSON.

    Returns:
       string, a JSON representation of this instance, suitable to pass to
       from_json().
    t   _classt   _moduleN(   t   typet   copyt   __dict__R2   RQ   RR   R"   t   dumps(   RM   t   stript   tt   dt   member(    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyt   _to_jsonK  s    c         C@  s
   |  j    S(   s   Create a JSON representation of an instance of MediaUpload.

    Returns:
       string, a JSON representation of this instance, suitable to pass to
       from_json().
    (   Rj   (   RM   (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyt   to_json_  s    c         C@  sd   t  j |  } | d } t | d | j d  d  } t | | d  } t | d  } | |  S(   s  Utility class method to instantiate a MediaUpload subclass from a JSON
    representation produced by to_json().

    Args:
      s: string, JSON from to_json().

    Returns:
      An instance of the subclass of MediaUpload that was serialized with
      to_json().
    Ra   t   fromlistt   .iR`   t	   from_json(   R"   R#   t
   __import__t   splitt   getattr(   t   clst   sR,   t   modulet   mt   klsRn   (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyt   new_from_jsonh  s    
N(   RQ   RR   RS   RW   RX   RY   RZ   R]   R^   R_   R   t
   positionalR2   Rj   Rk   t   classmethodRw   (    (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyRU      s   										t   MediaIoBaseUploadc           B@  st   e  Z d  Z e j d  e e d   Z d   Z d   Z	 d   Z
 d   Z d   Z d   Z d	   Z d
   Z RS(   s  A MediaUpload for a io.Base objects.

  Note that the Python file object is compatible with io.Base and can be used
  with this class also.

    fh = BytesIO('...Some data to upload...')
    media = MediaIoBaseUpload(fh, mimetype='image/png',
      chunksize=1024*1024, resumable=True)
    farm.animals().insert(
        id='cow',
        name='cow.png',
        media_body=media).execute()

  Depending on the platform you are working on, you may pass -1 as the
  chunksize, which indicates that the entire file should be uploaded in a single
  request. If the underlying platform supports streams, such as Python 2.6 or
  later, then this can be very efficient as it avoids multiple connections, and
  also avoids loading the entire file into memory before sending it. Note that
  Google App Engine has a 5MB limit on request size, so you should never set
  your chunksize larger than 5MB, or to -1.
  i   c         C@  s   t  t |   j   | |  _ | |  _ | d k p: | d k sI t    n  | |  _ | |  _ |  j j d t	 j
  |  j j   |  _ d S(   s  Constructor.

    Args:
      fd: io.Base or file object, The source of the bytes to upload. MUST be
        opened in blocking mode, do not use streams opened in non-blocking mode.
        The given stream must be seekable, that is, it must be able to call
        seek() on fd.
      mimetype: string, Mime-type of the file.
      chunksize: int, File will be uploaded in chunks of this many bytes. Only
        used if resumable=True. Pass in a value of -1 if the file is to be
        uploaded as a single chunk. Note that Google App Engine has a 5MB limit
        on request size, so you should never set your chunksize larger than 5MB,
        or to -1.
      resumable: bool, True if this is a resumable upload. False means upload
        in a single request.
    ii    N(   t   superRz   RN   t   _fdt	   _mimetypeR   t
   _chunksizet
   _resumablet   seekt   ost   SEEK_ENDt   tellt   _size(   RM   t   fdRX   RW   RZ   (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyRN     s    				c         C@  s   |  j  S(   sO   Chunk size for resumable uploads.

    Returns:
      Chunk size in bytes.
    (   R~   (   RM   (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyRW     s    c         C@  s   |  j  S(   s:   Mime type of the body.

    Returns:
      Mime type.
    (   R}   (   RM   (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyRX     s    c         C@  s   |  j  S(   sZ   Size of upload.

    Returns:
      Size of the body, or None of the size is unknown.
    (   R   (   RM   (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyRY     s    c         C@  s   |  j  S(   s]   Whether this upload is resumable.

    Returns:
      True if resumable upload or False.
    (   R   (   RM   (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyRZ     s    c         C@  s    |  j  j |  |  j  j |  S(   s   Get bytes from the media.

    Args:
      begin: int, offset from beginning of file.
      length: int, number of bytes to read, starting at begin.

    Returns:
      A string of bytes read. May be shorted than length if EOF was reached
      first.
    (   R|   R   t   read(   RM   R[   t   length(    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyR]     s    c         C@  s   t  S(   s  Does the underlying upload support a streaming interface.

    Streaming means it is an io.IOBase subclass that supports seek, i.e.
    seekable() returns True.

    Returns:
      True if the call to stream() will return an instance of a seekable io.Base
      subclass.
    (   R   (   RM   (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyR^     s    
c         C@  s   |  j  S(   s   A stream interface to the data being uploaded.

    Returns:
      The returned value is an io.IOBase subclass that supports seek, i.e.
      seekable() returns True.
    (   R|   (   RM   (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyR_     s    c         C@  s   t  d   d S(   s%   This upload type is not serializable.s&   MediaIoBaseUpload is not serializable.N(   RV   (   RM   (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyRk     s    (   RQ   RR   RS   R   Rx   t   DEFAULT_CHUNK_SIZER!   RN   RW   RX   RY   RZ   R]   R^   R_   Rk   (    (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyRz   }  s   								t   MediaFileUploadc           B@  sG   e  Z d  Z e j d  d e e d   Z d   Z	 e
 d    Z RS(   s  A MediaUpload for a file.

  Construct a MediaFileUpload and pass as the media_body parameter of the
  method. For example, if we had a service that allowed uploading images:


    media = MediaFileUpload('cow.png', mimetype='image/png',
      chunksize=1024*1024, resumable=True)
    farm.animals().insert(
        id='cow',
        name='cow.png',
        media_body=media).execute()

  Depending on the platform you are working on, you may pass -1 as the
  chunksize, which indicates that the entire file should be uploaded in a single
  request. If the underlying platform supports streams, such as Python 2.6 or
  later, then this can be very efficient as it avoids multiple connections, and
  also avoids loading the entire file into memory before sending it. Note that
  Google App Engine has a 5MB limit on request size, so you should never set
  your chunksize larger than 5MB, or to -1.
  i   c         C@  s}   | |  _  t |  j  d  } | d k rT t j |  \ } } | d k rT d } qT n  t t |   j | | d | d | d S(   sw  Constructor.

    Args:
      filename: string, Name of the file.
      mimetype: string, Mime-type of the file. If None then a mime-type will be
        guessed from the file extension.
      chunksize: int, File will be uploaded in chunks of this many bytes. Only
        used if resumable=True. Pass in a value of -1 if the file is to be
        uploaded in a single chunk. Note that Google App Engine has a 5MB limit
        on request size, so you should never set your chunksize larger than 5MB,
        or to -1.
      resumable: bool, True if this is a resumable upload. False means upload
        in a single request.
    t   rbs   application/octet-streamRW   RZ   N(   t	   _filenamet   openR2   t	   mimetypest
   guess_typeR{   R   RN   (   RM   t   filenameRX   RW   RZ   R   t   _(    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyRN     s    	c         C@  s   |  j  d d g  S(   s   Creating a JSON representation of an instance of MediaFileUpload.

    Returns:
       string, a JSON representation of this instance, suitable to pass to
       from_json().
    Rf   R|   (   Rj   (   RM   (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyRk   -  s    c      	   C@  s;   t  j |   } t | d d | d d | d d | d S(   NR   RX   R}   RW   R~   RZ   R   (   R"   R#   R   (   Rs   Rh   (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyRn   6  s    N(   RQ   RR   RS   R   Rx   R2   R   R!   RN   Rk   t   staticmethodRn   (    (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyR     s   		t   MediaInMemoryUploadc           B@  s/   e  Z d  Z e j d  d e e d   Z RS(   s   MediaUpload for a chunk of bytes.

  DEPRECATED: Use MediaIoBaseUpload with either io.TextIOBase or StringIO for
  the stream.
  i   s   application/octet-streamc         C@  s5   t  |  } t t |   j | | d | d | d S(   s  Create a new MediaInMemoryUpload.

  DEPRECATED: Use MediaIoBaseUpload with either io.TextIOBase or StringIO for
  the stream.

  Args:
    body: string, Bytes of body content.
    mimetype: string, Mime-type of the file or default of
      'application/octet-stream'.
    chunksize: int, File will be uploaded in chunks of this many bytes. Only
      used if resumable=True.
    resumable: bool, True if this is a resumable upload. False means upload
      in a single request.
    RW   RZ   N(   R   R{   R   RN   (   RM   t   bodyRX   RW   RZ   R   (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyRN   D  s    (   RQ   RR   RS   R   Rx   R   R!   RN   (    (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyR   =  s   t   MediaIoBaseDownloadc           B@  sD   e  Z d  Z e j d  e d   Z e j d  d d   Z RS(   s  "Download media resources.

  Note that the Python file object is compatible with io.Base and can be used
  with this class also.


  Example:
    request = farms.animals().get_media(id='cow')
    fh = io.FileIO('cow.png', mode='wb')
    downloader = MediaIoBaseDownload(fh, request, chunksize=1024*1024)

    done = False
    while done is False:
      status, done = downloader.next_chunk()
      if status:
        print "Download %d%%." % int(status.progress() * 100)
    print "Download Complete!"
  i   c         C@  s^   | |  _  | |  _ | j |  _ | |  _ d |  _ d |  _ t |  _	 t
 j |  _ t j |  _ d S(   s&  Constructor.

    Args:
      fd: io.Base or file object, The stream in which to write the downloaded
        bytes.
      request: googleapiclient.http.HttpRequest, the media request to perform in
        chunks.
      chunksize: int, File will be downloaded in chunks of this many bytes.
    i    N(   R|   t   _requestR?   t   _uriR~   t	   _progressR2   t   _total_sizeR!   t   _donet   timeR=   t   _sleept   randomt   _rand(   RM   R   R4   RW   (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyRN   n  s    						i   i    c      
   C@  s|  i d |  j  |  j  |  j f d 6} |  j j } t | | d |  j |  j |  j d d | \ } } | j d k r`d | k r | d |  j k r | d |  _ n  |  j  t	 |  7_  |  j
 j |  d	 | k r| d	 } | j d
 d  d } t |  |  _ n" d | k r&t | d  |  _ n  |  j  |  j k rDt |  _ n  t |  j  |  j  |  j f St | | d |  j  d S(   s_  Get the next chunk of the download.

    Args:
      num_retries: Integer, number of times to retry with randomized
            exponential backoff. If all retries fail, the raised HttpError
            represents the last request. If zero (default), we attempt the
            request only once.

    Returns:
      (status, done): (MediaDownloadStatus, boolean)
         The value of 'done' will be True when the media has been fully
         downloaded.

    Raises:
      googleapiclient.errors.HttpError if the response was not a 2xx.
      httplib2.HttpLib2Error if a transport error has occured.
    s   bytes=%d-%dR   s   media downloadt   GETt   headersi   i   s   content-locations   content-ranget   /i   s   content-lengthR?   N(   i   i   (   R   R~   R   R:   RI   R   R   R   R3   t   lenR|   t   writet   rsplitt   intR   R   R   RT   R   (   RM   R;   R   R:   RC   R+   t   content_rangeR   (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyt
   next_chunk  s,    
(   RQ   RR   RS   R   Rx   R   RN   R   (    (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyR   Z  s
   t   _StreamSlicec           B@  s#   e  Z d  Z d   Z d d  Z RS(   s  Truncated stream.

  Takes a stream and presents a stream that is a slice of the original stream.
  This is used when uploading media in chunks. In later versions of Python a
  stream can be passed to httplib in place of the string of data to send. The
  problem is that httplib just blindly reads to the end of the stream. This
  wrapper presents a virtual stream that only reads to the end of the chunk.
  c         C@  s/   | |  _  | |  _ | |  _ |  j  j |  d S(   s   Constructor.

    Args:
      stream: (io.Base, file object), the stream to wrap.
      begin: int, the seek position the chunk begins at.
      chunksize: int, the size of the chunk.
    N(   t   _streamt   _beginR~   R   (   RM   R_   R[   RW   (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyRN     s    			ic         C@  sX   |  j  j   } |  j |  j } | d k s; | | | k rH | | } n  |  j  j |  S(   s   Read n bytes.

    Args:
      n, int, the number of bytes to read.

    Returns:
      A string of length 'n', or less if EOF is reached.
    i(   R   R   R   R~   R   (   RM   t   nt   curR\   (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyR     s
    
(   RQ   RR   RS   RN   R   (    (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyR     s   	t   HttpRequestc           B@  s   e  Z d  Z e j d  d d d d d d   Z e j d  d d d   Z e j d  d    Z e j d  d d d	   Z	 d
   Z
 d   Z e d    Z RS(   s#   Encapsulates a single HTTP request.i   R   c	         C@  s   | |  _  | |  _ | |  _ | p$ i  |  _ | |  _ | |  _ | |  _ | |  _ g  |  _ t	 |  _
 t j |  j j d d   \ }	 }
 } t |  j p d  |  _ d |  _ d |  _ t j |  _ t j |  _ d S(   s  Constructor for an HttpRequest.

    Args:
      http: httplib2.Http, the transport object to use to make a request
      postproc: callable, called on the HTTP response and content to transform
                it into a data object before returning, or raising an exception
                on an error.
      uri: string, the absolute URI to send the request to
      method: string, the HTTP method to use
      body: string, the request body of the HTTP request,
      headers: dict, the HTTP request headers
      methodId: string, a unique identifier for the API method being called.
      resumable: MediaUpload, None if this is not a resumbale request.
    s   content-types   application/jsont    i    N(   R?   R@   R   R   t   methodIdR:   t   postprocRZ   t   response_callbacksR!   t   _in_error_stateR   t   parse_mime_typeR9   R   t	   body_sizeR2   t   resumable_uriRK   R   R   R   R=   R   (   RM   R:   R   R?   R@   R   R   R   RZ   t   majort   minort   params(    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyRN     s"    									!		i   i    c   	      C@  s  | d k r |  j } n  |  j r\ d } x. | d k rW |  j d | d |  \ } } q* W| Sd |  j k r t |  j  |  j d <n  t |  j  t	 k r2|  j
 d k r2d |  _
 d |  j d <d |  j d <t |  j  } t | j | j | j | j d d f  |  _ | j |  _ t t |  j   |  j d <n  t | | d	 |  j |  j t |  j  d
 t |  j
  d |  j d |  j \ } } x |  j D] } | |  qW| j d k rt | | d |  j  n  |  j | |  S(   s  Execute the request.

    Args:
      http: httplib2.Http, an http object to be used in place of the
            one the HttpRequest request object was constructed with.
      num_retries: Integer, number of times to retry with randomized
            exponential backoff. If all retries fail, the raised HttpError
            represents the last request. If zero (default), we attempt the
            request only once.

    Returns:
      A deserialized object model of the response body as determined
      by the postproc.

    Raises:
      googleapiclient.errors.HttpError if the response was not a 2xx.
      httplib2.HttpLib2Error if a transport error has occured.
    R:   R;   s   content-lengthR   t   POSTs   x-http-method-overrides!   application/x-www-form-urlencodeds   content-typeR4   R@   R   R   i,  R?   N(   R2   R:   RZ   R   R   t   strR   R   R?   t   MAX_URI_LENGTHR@   R   R   t   schemet   netloct   pathR   t   queryR   RI   R   R   R   R3   R   R   (	   RM   R:   R;   R   R   t   parsedRC   R+   t   callback(    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyt   execute  s6    	"$	$*i   c         C@  s   |  j  j |  d S(   s   add_response_headers_callback

    Args:
      cb: Callback to be called on receiving the response headers, of signature:

      def cb(resp):
        # Where resp is an instance of httplib2.Response
    N(   R   t   append(   RM   t   cb(    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyt   add_response_callbackK  s    
c         C@  s  | d k r |  j } n  |  j j   d k r6 d } n t |  j j    } |  j d k r*t j |  j  } |  j j   | d <| d k r | | d <n  t |  j	  | d <t
 | | d |  j |  j |  j d |  j d |  j d | \ } } | j d	 k rd
 | k r| d
 |  _ qt | |   nm |  j ri d | d 6d d 6} | j |  j d d | \ } } |  j | |  \ } }	 |	 r| |	 f Sn  |  j j   rH|  j j   }
 |  j j   d k r|
 j |  j  |  j j   |  j d } qt |
 |  j |  j j    }
 t |  j |  j j   d |  j j   d  } no |  j j |  j |  j j    }
 t |
  |  j j   k  rt |  j t |
   } n  |  j t |
  d } i d |  j | | f d 6t | |  j d  d 6} x t | d  D] } | d k rS|  j |  j   d |  t j  d | |  j |  j | j f  n  y. | j |  j d d d |
 d | \ } } Wn t! |  _   n Xt" | j |  sPqqW|  j | |  S(   s8  Execute the next step of a resumable upload.

    Can only be used if the method being executed supports media uploads and
    the MediaUpload object passed in was flagged as using resumable upload.

    Example:

      media = MediaFileUpload('cow.png', mimetype='image/png',
                              chunksize=1000, resumable=True)
      request = farm.animals().insert(
          id='cow',
          name='cow.png',
          media_body=media)

      response = None
      while response is None:
        status, response = request.next_chunk()
        if status:
          print "Upload %d%% complete." % int(status.progress() * 100)


    Args:
      http: httplib2.Http, an http object to be used in place of the
            one the HttpRequest request object was constructed with.
      num_retries: Integer, number of times to retry with randomized
            exponential backoff. If all retries fail, the raised HttpError
            represents the last request. If zero (default), we attempt the
            request only once.

    Returns:
      (status, body): (ResumableMediaStatus, object)
         The body will be None until the resumable media is fully uploaded.

    Raises:
      googleapiclient.errors.HttpError if the response was not a 2xx.
      httplib2.HttpLib2Error if a transport error has occured.
    t   *s   X-Upload-Content-Types   X-Upload-Content-Lengths   content-lengths   resumable URI requestR@   R   R   i   t   locations
   bytes */%ss   Content-Ranget   0t   PUTii   s   bytes %d-%d/%ss   Content-Lengthi    i   s7   Retry #%d for media upload: %s %s, following status: %dN(#   R2   R:   RZ   RY   R   R   Rc   R   RX   R   RI   R   R   R?   R@   R   R3   R   R   R4   t   _process_responseR^   R_   RW   R   RK   R   t   minR]   R   R   R(   R)   R   R-   (   RM   R:   R;   RY   t   start_headersRC   R+   R   R3   R   R,   t	   chunk_endRD   (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyR   W  sz    '	*	
	 	c         C@  s   | j  d
 k r. t |  _ d |  j | |  f S| j  d k r t |  _ y( t | d j d  d  d |  _ Wn t k
 r d |  _ n Xd | k r | d |  _	 q n! t
 |  _ t | | d	 |  j  t |  j |  j j    d f S(   s  Process the response from a single chunk upload.

    Args:
      resp: httplib2.Response, the response object.
      content: string, the content of the response.

    Returns:
      (status, body): (ResumableMediaStatus, object)
         The body will be None until the resumable media is fully uploaded.

    Raises:
      googleapiclient.errors.HttpError if the response was not a 2xx or a 308.
    i   i   i4  R   t   -i   i    R   R?   (   i   i   N(   R3   R!   R   R2   R   R   Rp   RK   R'   R   R   R   R?   RJ   RZ   RY   (   RM   RC   R+   (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyR     s    		(	c         C@  sa   t  j  |  j  } | d d k	 r8 |  j j   | d <n  | d =| d =| d =| d =t j |  S(   s1   Returns a JSON representation of the HttpRequest.RZ   R:   R   R   R   N(   Rc   Rd   R2   RZ   Rk   R"   Re   (   RM   Rh   (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyRk     s    c         C@  s   t  j |   } | d d k	 r9 t j | d  | d <n  t | | d | d d | d d | d d | d d | d d | d S(   s>   Returns an HttpRequest populated with info from a JSON object.RZ   R?   R@   R   R   R   N(   R"   R#   R2   RU   Rw   R   (   Rs   R:   R   Rh   (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyRn     s    




N(   RQ   RR   RS   R   Rx   R2   RN   R   R   R   R   Rk   R   Rn   (    (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyR     s   +8}	"	t   BatchHttpRequestc           B@  s   e  Z d  Z e j d  d d d   Z d   Z d   Z d   Z	 d   Z
 d   Z d   Z e j d	  d d d
   Z d   Z e j d  d d   Z RS(   sj  Batches multiple HttpRequest objects into a single HTTP request.

  Example:
    from googleapiclient.http import BatchHttpRequest

    def list_animals(request_id, response, exception):
      """Do something with the animals list response."""
      if exception is not None:
        # Do something with the exception.
        pass
      else:
        # Do something with the response.
        pass

    def list_farmers(request_id, response, exception):
      """Do something with the farmers list response."""
      if exception is not None:
        # Do something with the exception.
        pass
      else:
        # Do something with the response.
        pass

    service = build('farm', 'v2')

    batch = BatchHttpRequest()

    batch.add(service.animals().list(), list_animals)
    batch.add(service.farmers().list(), list_farmers)
    batch.execute(http=http)
  i   c         C@  sj   | d k r d } n  | |  _ | |  _ i  |  _ i  |  _ g  |  _ d |  _ d |  _ i  |  _ i  |  _	 d S(   s  Constructor for a BatchHttpRequest.

    Args:
      callback: callable, A callback to be called for each response, of the
        form callback(id, response, exception). The first parameter is the
        request id, and the second is the deserialized response object. The
        third is an googleapiclient.errors.HttpError exception object if an HTTP error
        occurred while processing the request, or None if no error occurred.
      batch_uri: string, URI to send batch requests to.
    s    https://www.googleapis.com/batchi    N(
   R2   t
   _batch_urit	   _callbackt	   _requestst
   _callbackst   _ordert   _last_auto_idt   _base_idt
   _responsest   _refreshed_credentials(   RM   R   t	   batch_uri(    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyRN   5  s    									c         C@  s   d } | j d k	 r< t | j j d  r< | j j j } n- | d k	 ri t | j d  ri | j j } n  | d k	 r t |  |  j k r | j |  d |  j t |  <q n  | j d k s t | j j d  r | j | j	  n  d S(   s   Refresh the credentials and apply to the request.

    Args:
      request: HttpRequest, the request.
      http: httplib2.Http, the global http object for the batch.
    t   credentialsi   N(
   R2   R:   t   hasattrR4   R   t   idR   t   refresht   applyR   (   RM   R4   R:   t   creds(    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyt   _refresh_and_apply_credentials]  s    
	
c         C@  s8   |  j  d k r! t j   |  _  n  d |  j  t |  f S(   s%  Convert an id to a Content-ID header value.

    Args:
      id_: string, identifier of 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.
    s   <%s+%s>N(   R   R2   t   uuidt   uuid4R   (   RM   t   id_(    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyt   _id_to_headerx  s    c         C@  s{   | d d k s  | d d k r3 t  d |   n  d | k rR t  d |   n  | d d !j d d  \ } } t |  S(   s>  Convert a Content-ID header value to an id.

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

    Args:
      header: string, Content-ID header value.

    Returns:
      The extracted id value.

    Raises:
      BatchError if the header is not in the expected format.
    i    t   <it   >s    Invalid value for Content-ID: %st   +i   (   R   R   R   (   RM   t   headert   baseR   (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyt   _header_to_id  s     c         C@  s  t  | j  } t d d | j | j | j d f  } | j d | d } | j j d d  j	 d  \ } } t
 | |  } | j j   } | j d k	 r t | j j d  r | j j j j |  n  d | k r | d =n  x' t j |  D] \ }	 }
 |
 | |	 <q W| j | d <| j d  | j d k	 r_| j | j  t t | j   | d	 <n  t   } t | d
 d } | j | d t | j   } | | S(   s   Convert an HttpRequest object into a string.

    Args:
      request: HttpRequest, the request to serialize.

    Returns:
      The request as a string in application/http format.
    R   t    s
    HTTP/1.1
s   content-types   application/jsonR   R   t   Hosts   content-lengtht   maxheaderleni    t   unixfromN(   R   R?   R   R   R   R   R@   R   R9   Rp   R   Rc   R:   R2   R   R4   R   R   R   t	   iteritemsR   t   set_unixfromR   t   set_payloadR   R   R   R	   t   flattenR!   t   getvalue(   RM   R4   R   t   request_linet   status_lineR   R   t   msgR   t   keyt   valuet   fpt   gR   (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyt   _serialize_request  s0    
$$	
	c   
      C@  s   | j  d d  \ } } | j  d d  \ } } } t   } | j |  | j   } | | d <t j |  } | | _ t | j  d d  d j d d   | _	 | j  d	 d  d }	 | |	 f S(
   s   Convert string into httplib2 response and content.

    Args:
      payload: string, headers and body as a string.

    Returns:
      A pair (resp, content), such as would be returned from httplib2.request.
    s   
i   R   i   R3   R   Rm   R   s   

(
   Rp   R   t   feedt   closet   httplib2t   ResponseR   R   t   replacet   version(
   RM   t   payloadR   t   protocolR3   R   t   parserR   RC   R+   (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyt   _deserialize_response  s    
	
	+c         C@  sJ   |  j  d 7_  x+ t |  j   |  j k r< |  j  d 7_  q Wt |  j   S(   s   Create a new id.

    Auto incrementing number that avoids conflicts with ids already used.

    Returns:
       string, a new unique id.
    i   (   R   R   R   (   RM   (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyt   _new_id  s    i   c         C@  s   | d k r |  j   } n  | j d k	 r9 t d   n  | |  j k r[ t d |   n  | |  j | <| |  j | <|  j j |  d S(   s  Add a new request.

    Every callback added will be paired with a unique id, the request_id. That
    unique id will be passed back to the callback when the response comes back
    from the server. The default behavior is to have the library generate it's
    own unique id. If the caller passes in a request_id then they must ensure
    uniqueness for each request_id, and if they are not an exception is
    raised. Callers should either supply all request_ids or nevery supply a
    request id, to avoid such an error.

    Args:
      request: HttpRequest, Request to add to the batch.
      callback: callable, A callback to be called for this response, of the
        form callback(id, response, exception). The first parameter is the
        request id, and the second is the deserialized response object. The
        third is an googleapiclient.errors.HttpError exception object if an HTTP error
        occurred while processing the request, or None if no errors occurred.
      request_id: string, A unique id for the request. The id will be passed to
        the callback with the response.

    Returns:
      None

    Raises:
      BatchError if a media request is added to a batch.
      KeyError is the request_id is not unique.
    s1   Media requests cannot be used in a batch request.s)   A request with this ID already exists: %sN(	   R2   R  RZ   R   R   R'   R   R   R   (   RM   R4   R   t
   request_id(    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyt   add  s    c         C@  s3  t  d  } t | d d    xm | D]e } | | } t d d  } d | d <|  j |  | d <|  j |  } | j |  | j |  q& Wt   }	 t |	 d	 t	 }
 |
 j
 | d
 t	 |	 j   } i  } d | j   | d <| j |  j d d d | d | \ } } | j d k r7t | | d |  j  n  d | d } t j r`| j d  } n  | | } t   } | j |  | j   } | j   st d d | d |  n  xy | j   D]k } |  j | d  } |  j | j    \ } } t | t j  r| j d  } n  | | f |  j | <qWd S(   s  Serialize batch request, send to server, process response.

    Args:
      http: httplib2.Http, an http object to be used to make the request with.
      order: list, list of request ids in the order they were added to the
        batch.
      request: list, list of request objects to send.

    Raises:
      httplib2.HttpLib2Error if a transport error has occured.
      googleapiclient.errors.BatchError if the response is the wrong format.
    t   mixedt   _write_headersc         S@  s   d  S(   N(   R2   (   RM   (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyt   <lambda>+  s    t   applicationR:   t   binarys   Content-Transfer-Encodings
   Content-IDt   mangle_from_R   s   multipart/mixed; boundary="%s"s   content-typeR@   R   R   R   i,  R?   s   content-type: %s

s   utf-8s'   Response not in multipart/mixed format.RC   R+   N(    R
   t   setattrR   R   R   R   t   attachR   R	   R!   R   R   t   get_boundaryR4   R   R3   R   R   t   PY3R$   R   R   R   t   is_multipartR   t   get_payloadR   R  t
   isinstancet	   text_typet   encodeR   (   RM   R:   t   ordert   requestst   messageR  R4   R   R   R   R   R   RC   R+   R   t
   for_parserR  t   mime_responset   partt   response(    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyt   _execute  sJ    

		
	c         C@  sv  t  |  j  d k r d
 S| d
 k rb x: |  j D], } |  j | } | d
 k	 r/ | j } Pq/ q/ Wn  | d
 k r} t d   n  t | j d d
  d
 k	 r | j j } t | d d
  s t	 j
 d  | j |  q n  |  j | |  j |  j  i  } g  } xk |  j D]` } |  j | \ } } | d d k r| j |  |  j | } |  j | |  | | | <qqW| r|  j | | |  n  x |  j D] } |  j | \ } } |  j | } |  j | }	 d
 }
 d
 } y@ | j d k rt | | d	 | j  n  | j | |  }
 Wn t k
 r)} | } n X|	 d
 k	 rI|	 | |
 |  n  |  j d
 k	 r|  j | |
 |  qqWd
 S(   s  Execute all the requests as a single batched HTTP request.

    Args:
      http: httplib2.Http, an http object to be used in place of the one the
        HttpRequest request object was constructed with. If one isn't supplied
        then use a http object from the requests in this batch.

    Returns:
      None

    Raises:
      httplib2.HttpLib2Error if a transport error has occured.
      googleapiclient.errors.BatchError if the response is the wrong format.
    i    s   Missing a valid http object.R   t   access_tokens1   Attempting refresh to obtain initial access_tokenR3   t   401i,  R?   N(   R   R   R2   R   R:   R&   Rq   R4   R   R(   t   infoR   R  R   R   R   R   R3   R   R?   R   R   (   RM   R:   R  R4   R   t   redo_requestst
   redo_orderRC   R+   R   R  RF   t   e(    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyR   b  sV    	
N(   RQ   RR   RS   R   Rx   R2   RN   R   R   R   R   R  R  R  R  R   (    (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyR     s   '				-		&	Ft   HttpRequestMockc           B@  s#   e  Z d  Z d   Z d d  Z RS(   sU   Mock of HttpRequest.

  Do not construct directly, instead use RequestMockBuilder.
  c         C@  ss   | |  _  | |  _ | |  _ | d k rJ t j i d d 6d d 6 |  _  n  d |  j  k ro |  j  d |  j  _ n  d S(   sA  Constructor for HttpRequestMock

    Args:
      resp: httplib2.Response, the response to emulate coming from the request
      content: string, the response body
      postproc: callable, the post processing function usually supplied by
                the model class. See model.JsonModel.response() as an example.
    i   R3   t   OKR   N(   RC   R+   R   R2   R   R   R   (   RM   RC   R+   R   (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyRN     s    				#c         C@  s   |  j  |  j |  j  S(   s   Execute the request.

    Same behavior as HttpRequest.execute(), but the response is
    mocked and not really from an HTTP request/response.
    (   R   RC   R+   (   RM   R:   (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyR     s    N(   RQ   RR   RS   RN   R2   R   (    (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyR%    s   	t   RequestMockBuilderc           B@  s2   e  Z d  Z e d  Z d d d d d d  Z RS(   s  A simple mock of HttpRequest

    Pass in a dictionary to the constructor that maps request methodIds to
    tuples of (httplib2.Response, content, opt_expected_body) that should be
    returned when that method is called. None may also be passed in for the
    httplib2.Response, in which case a 200 OK response will be generated.
    If an opt_expected_body (str or dict) is provided, it will be compared to
    the body and UnexpectedBodyError will be raised on inequality.

    Example:
      response = '{"data": {"id": "tag:google.c...'
      requestBuilder = RequestMockBuilder(
        {
          'plus.activities.get': (None, response),
        }
      )
      googleapiclient.discovery.build("plus", "v1", requestBuilder=requestBuilder)

    Methods that you do not supply a response for will return a
    200 OK with an empty string as the response content or raise an excpetion
    if check_unexpected is set to True. The methodId is taken from the rpcName
    in the discovery document.

    For more details see the project wiki.
  c         C@  s   | |  _  | |  _ d S(   s  Constructor for RequestMockBuilder

    The constructed object should be a callable object
    that can replace the class HttpResponse.

    responses - A dictionary that maps methodIds into tuples
                of (httplib2.Response, content). The methodId
                comes from the 'rpcName' field in the discovery
                document.
    check_unexpected - A boolean setting whether or not UnexpectedMethodError
                       should be raised on unsupplied method.
    N(   t	   responsest   check_unexpected(   RM   R(  R)  (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyRN     s    	R   c	         C@  s  | |  j  k r |  j  | }	 |	 d  \ }
 } t |	  d k r |	 d } t |  t |  k rr t | |   n  t | t  r t j |  } n  t j |  } | | k r t | |   q n  t |
 | |  S|  j	 r t
 d |   n t t  } t d d | j  Sd S(   s   Implements the callable interface that discovery.build() expects
    of requestBuilder, which is to build an object compatible with
    HttpRequest.execute(). See that method for the description of the
    parameters and the expected response.
    i   R   s   {}N(   R(  R   t   boolR   R  R   R"   R#   R%  R)  R   R   R!   R2   R  (   RM   R:   R   R?   R@   R   R   R   RZ   R  RC   R+   t   expected_bodyt   model(    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyt   __call__  s"    
	N(   RQ   RR   RS   R!   RN   R2   R-  (    (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyR'    s   t   HttpMockc           B@  s5   e  Z d  Z d d d  Z d d d d d d  Z RS(   s   Mock of httplib2.Httpc         C@  s   | d k r i d d 6} n  | rM t | d  } | j   |  _ | j   n	 d |  _ | |  _ d |  _ d |  _ d |  _ d |  _	 d |  _ d S(   s   
    Args:
      filename: string, absolute filename to read response from
      headers: dict, header to return with response
    t   200R3   R   N(
   R2   R   R   R,   R   t   response_headersR   R?   R@   R   (   RM   R   R   t   f(    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyRN      s    						R   i   c         C@  s=   | |  _  | |  _ | |  _ | |  _ t j |  j  |  j f S(   N(   R?   R@   R   R   R   R   R0  R,   (   RM   R?   R@   R   R   t   redirectionst   connection_type(    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyR4   6  s
    				N(   RQ   RR   RS   R2   RN   R4   (    (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyR.    s   t   HttpMockSequencec           B@  s/   e  Z d  Z d   Z d d d d d d  Z RS(   s  Mock of httplib2.Http

  Mocks a sequence of calls to request returning different responses for each
  call. Create an instance initialized with the desired response headers
  and content and then use as if an httplib2.Http instance.

    http = HttpMockSequence([
      ({'status': '401'}, ''),
      ({'status': '200'}, '{"access_token":"1/3w","expires_in":3600}'),
      ({'status': '200'}, 'echo_request_headers'),
      ])
    resp, content = http.request("http://examples.com")

  There are special values you can pass in for content to trigger
  behavours that are helpful in testing.

  'echo_request_headers' means return the request headers in the response body
  'echo_request_headers_as_json' means return the request headers in
     the response body
  'echo_request_body' means return the request body in the response body
  'echo_request_uri' means return the request uri in the response body
  c         C@  s   | |  _  t |  _ d S(   sP   
    Args:
      iterable: iterable, a sequence of pairs of (headers, body)
    N(   t	   _iterableR   t   follow_redirects(   RM   t   iterable(    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyRN   [  s    	R   i   c   	      C@  s   |  j  j d  \ } } | d k r- | } nf | d k rK t j |  } nH | d k r~ t | d  ru | j   } q | } n | d k r | } n  t | t j  r | j	 d  } n  t
 j |  | f S(   Ni    t   echo_request_headerst   echo_request_headers_as_jsont   echo_request_bodyR   t   echo_request_uris   utf-8(   R5  t   popR"   Re   R   R   R  R   R  R  R   R   (	   RM   R?   R@   R   R   R2  R3  RC   R+   (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyR4   c  s    			N(   RQ   RR   RS   RN   R2   R4   (    (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyR4  C  s   		c         @  s:   |  j    d d d t j d    f d  } | |  _  |  S(   s  Set the user-agent on every request.

  Args:
     http - An instance of httplib2.Http
         or something that acts like it.
     user_agent: string, the value for the user-agent header.

  Returns:
     A modified instance of http that was passed in.

  Example:

    h = httplib2.Http()
    h = set_user_agent(h, "my-app-name/6.0")

  Most of the time the user-agent will be set doing auth, this is for the rare
  cases where you are accessing an unauthenticated endpoint.
  R   c         @  so   | d k r i  } n  d | k r:  d | d | d <n
  | d <  |  | | | | |  \ } } | | f S(   s1   Modify the request headers to add the user-agent.s
   user-agentR   N(   R2   (   R?   R@   R   R   R2  R3  RC   R+   (   t   request_origt
   user_agent(    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyt   new_request  s    	
N(   R4   R2   R   t   DEFAULT_MAX_REDIRECTS(   R:   R>  R?  (    (   R=  R>  sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyt   set_user_agentz  s    			c         @  s7   |  j    d d d t j d   f d  } | |  _  |  S(   s  Tunnel PATCH requests over POST.
  Args:
     http - An instance of httplib2.Http
         or something that acts like it.

  Returns:
     A modified instance of http that was passed in.

  Example:

    h = httplib2.Http()
    h = tunnel_patch(h, "my-app-name/6.0")

  Useful if you are running on a platform that doesn't support PATCH.
  Apply this last if you are using OAuth 1.0, as changing the method
  will result in a different signature.
  R   c         @  s   | d k r i  } n  | d k r\ d | j d d  k rI t j d  n  d | d <d } n    |  | | | | |  \ } } | | f S(	   s1   Modify the request headers to add the user-agent.t   PATCHt   oauth_tokent   authorizationR   s;   OAuth 1.0 request made with Credentials after tunnel_patch.s   x-http-method-overrideR   N(   R2   R9   R(   R)   (   R?   R@   R   R   R2  R3  RC   R+   (   R=  (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyR?    s    	

	N(   R4   R2   R   R@  (   R:   R?  (    (   R=  sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyt   tunnel_patch  s    			c          C@  s7   t  j   d k	 r! t  j   }  n t }  t j d |   S(   s  Builds httplib2.Http object

  Returns:
  A httplib2.Http object, which is used to make http requests, and which has timeout set by default.
  To override default timeout call

    socket.setdefaulttimeout(timeout_in_sec)

  before interacting with this method.
  t   timeoutN(   R6   t   getdefaulttimeoutR2   t   DEFAULT_HTTP_TIMEOUT_SECR   t   Http(   t   http_timeout(    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyt
   build_http  s    (Q   RS   t
   __future__R    R   t	   six.movesR   R   t
   __author__R   R   t   six.moves.urllib.parseR   R   R   R   t   base64Rc   t   gzipR   R"   t   loggingR   R   R   R6   t   sysR   R   t   sslt   ImportErrort   objectR5   t   SSLErrort   email.generatorR	   t   email.mime.multipartR
   t   email.mime.nonmultipartR   t   email.parserR   t   oauth2clientR   R   t   googleapiclientR   t   googleapiclient.errorsR   R   R   R   R   R   t   googleapiclient.modelR   t	   getLoggerRQ   R(   R   R   R   RH  R-   RI   RJ   RT   RU   Rz   R   R   R   R   R   R   R%  R'  R.  R4  RA  RE  RK  (    (    (    sF   /tmp/pip-build-kpPAdC/google-api-python-client/googleapiclient/http.pyt   <module>   s   "	
	+	8}C\( 7  I&7	(	)