apiclient.http
index
/home/jcgregorio/projects/apiclient-release/apiclient/http.py

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.

 
Modules
       
StringIO
base64
copy
gzip
httplib2
apiclient.mimeparse
mimetypes
os
json
urllib
urlparse
uuid

 
Classes
       
__builtin__.object
BatchHttpRequest
HttpMock
HttpMockSequence
HttpRequest
HttpRequestMock
MediaUpload
MediaFileUpload
MediaInMemoryUpload
MediaUploadProgress
RequestMockBuilder

 
class BatchHttpRequest(__builtin__.object)
    Batches multiple HttpRequest objects into a single HTTP request.
 
  Methods defined here:
__init__(self, callback=None, batch_uri=None)
Constructor for a BatchHttpRequest.
 
Args:
  callback: callable, A callback to be called for each response, of the
    form callback(id, response). The first parameter is the request id, and
    the second is the deserialized response object.
  batch_uri: string, URI to send batch requests to.
add(self, request, callback=None, request_id=None)
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). The first parameter is the request id, and
    the second is the deserialized response object.
  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 resumable request is added to a batch.
  KeyError is the request_id is not unique.
execute(self, http=None)
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.Error if a transport error has occured.
  apiclient.errors.BatchError if the response is the wrong format.

Data descriptors defined here:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)

 
class HttpMock(__builtin__.object)
    Mock of httplib2.Http
 
  Methods defined here:
__init__(self, filename, headers=None)
Args:
  filename: string, absolute filename to read response from
  headers: dict, header to return with response
request(self, uri, method='GET', body=None, headers=None, redirections=1, connection_type=None)

Data descriptors defined here:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)

 
class HttpMockSequence(__builtin__.object)
    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
 
  Methods defined here:
__init__(self, iterable)
Args:
  iterable: iterable, a sequence of pairs of (headers, body)
request(self, uri, method='GET', body=None, headers=None, redirections=1, connection_type=None)

Data descriptors defined here:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)

 
class HttpRequest(__builtin__.object)
    Encapsulates a single HTTP request.
 
  Methods defined here:
__init__(self, http, postproc, uri, method='GET', body=None, headers=None, methodId=None, resumable=None)
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.
execute(self, http=None)
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.
 
Returns:
  A deserialized object model of the response body as determined
  by the postproc.
 
Raises:
  apiclient.errors.HttpError if the response was not a 2xx.
  httplib2.Error if a transport error has occured.
next_chunk(self, http=None)
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('smiley.png', mimetype='image/png',
                          chunksize=1000, resumable=True)
  request = service.objects().insert(
      bucket=buckets['items'][0]['id'],
      name='smiley.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)
 
 
Returns:
  (status, body): (ResumableMediaStatus, object)
     The body will be None until the resumable media is fully uploaded.
to_json(self)
Returns a JSON representation of the HttpRequest.

Static methods defined here:
from_json(s, http, postproc)
Returns an HttpRequest populated with info from a JSON object.

Data descriptors defined here:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)

 
class HttpRequestMock(__builtin__.object)
    Mock of HttpRequest.
 
Do not construct directly, instead use RequestMockBuilder.
 
  Methods defined here:
__init__(self, resp, content, postproc)
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.
execute(self, http=None)
Execute the request.
 
Same behavior as HttpRequest.execute(), but the response is
mocked and not really from an HTTP request/response.

Data descriptors defined here:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)

 
class MediaFileUpload(MediaUpload)
    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('smiley.png', mimetype='image/png', chunksize=1000,
                  resumable=True)
  service.objects().insert(
      bucket=buckets['items'][0]['id'],
      name='smiley.png',
      media_body=media).execute()
 
 
Method resolution order:
MediaFileUpload
MediaUpload
__builtin__.object

Methods defined here:
__init__(self, filename, mimetype=None, chunksize=262144, resumable=False)
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.
  resumable: bool, True if this is a resumable upload. False means upload
    in a single request.
chunksize(self)
getbytes(self, begin, length)
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.
mimetype(self)
resumable(self)
size(self)
to_json(self)
Creating a JSON representation of an instance of Credentials.
 
Returns:
   string, a JSON representation of this instance, suitable to pass to
   from_json().

Static methods defined here:
from_json(s)

Class methods inherited from MediaUpload:
new_from_json(cls, s) from __builtin__.type
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().

Data descriptors inherited from MediaUpload:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)

 
class MediaInMemoryUpload(MediaUpload)
    MediaUpload for a chunk of bytes.
 
Construct a MediaFileUpload and pass as the media_body parameter of the
method. For example, if we had a service that allowed plain text:
 
 
Method resolution order:
MediaInMemoryUpload
MediaUpload
__builtin__.object

Methods defined here:
__init__(self, body, mimetype='application/octet-stream', chunksize=262144, resumable=False)
Create a new MediaBytesUpload.
 
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.
chunksize(self)
Chunk size for resumable uploads.
 
Returns:
  Chunk size in bytes.
getbytes(self, begin, length)
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.
mimetype(self)
Mime type of the body.
 
Returns:
  Mime type.
resumable(self)
Whether this upload is resumable.
 
Returns:
  True if resumable upload or False.
size(self)
Size of upload.
 
Returns:
  Size of the body.
to_json(self)
Create a JSON representation of a MediaInMemoryUpload.
 
Returns:
   string, a JSON representation of this instance, suitable to pass to
   from_json().

Static methods defined here:
from_json(s)

Class methods inherited from MediaUpload:
new_from_json(cls, s) from __builtin__.type
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().

Data descriptors inherited from MediaUpload:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)

 
class MediaUpload(__builtin__.object)
    Describes a media object to upload.
 
Base class that defines the interface of MediaUpload subclasses.
 
  Methods defined here:
chunksize(self)
getbytes(self, begin, end)
mimetype(self)
resumable(self)
size(self)
to_json(self)
Create a JSON representation of an instance of MediaUpload.
 
Returns:
   string, a JSON representation of this instance, suitable to pass to
   from_json().

Class methods defined here:
new_from_json(cls, s) from __builtin__.type
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().

Data descriptors defined here:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)

 
class MediaUploadProgress(__builtin__.object)
    Status of a resumable upload.
 
  Methods defined here:
__init__(self, resumable_progress, total_size)
Constructor.
 
Args:
  resumable_progress: int, bytes sent so far.
  total_size: int, total bytes in complete upload.
progress(self)
Percent of upload completed, as a float.

Data descriptors defined here:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)

 
class RequestMockBuilder(__builtin__.object)
    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),
    }
  )
  apiclient.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.
 
  Methods defined here:
__call__(self, http, postproc, uri, method='GET', body=None, headers=None, methodId=None, resumable=None)
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.
__init__(self, responses, check_unexpected=False)
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.

Data descriptors defined here:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)

 
Functions
       
set_user_agent(http, user_agent)
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.
tunnel_patch(http)
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.

 
Data
        __author__ = 'jcgregorio@google.com (Joe Gregorio)'

 
Author
        jcgregorio@google.com (Joe Gregorio)