Esempio n. 1
0
 def __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.
   """
   if methodId in self.responses:
     response = self.responses[methodId]
     resp, content = response[:2]
     if len(response) > 2:
       # Test the body against the supplied expected_body.
       expected_body = response[2]
       if bool(expected_body) != bool(body):
         # Not expecting a body and provided one
         # or expecting a body and not provided one.
         raise UnexpectedBodyError(expected_body, body)
       if isinstance(expected_body, str):
         expected_body = simplejson.loads(expected_body)
       body = simplejson.loads(body)
       if body != expected_body:
         raise UnexpectedBodyError(expected_body, body)
     return HttpRequestMock(resp, content, postproc)
   elif self.check_unexpected:
     raise UnexpectedMethodError(methodId)
   else:
     model = JsonModel(False)
     return HttpRequestMock(None, '{}', model.response)
Esempio n. 2
0
 def _get_reason(self):
   """Calculate the reason for the error from the response content."""
   if self.resp.get('content-type', '').startswith('application/json'):
     try:
       data = simplejson.loads(self.content)
       reason = data['error']['message']
     except (ValueError, KeyError):
       reason = self.content
   else:
     reason = self.resp.reason
   return reason
Esempio n. 3
0
 def from_json(s, http, postproc):
   """Returns an HttpRequest populated with info from a JSON object."""
   d = simplejson.loads(s)
   if d['resumable'] is not None:
     d['resumable'] = MediaUpload.new_from_json(d['resumable'])
   return HttpRequest(
       http,
       postproc,
       uri=d['uri'],
       method=d['method'],
       body=d['body'],
       headers=d['headers'],
       methodId=d['methodId'],
       resumable=d['resumable'])
Esempio n. 4
0
  def new_from_json(cls, 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().
    """
    data = simplejson.loads(s)
    # Find and call the right classmethod from_json() to restore the object.
    module = data['_module']
    m = __import__(module, fromlist=module.split('.')[:-1])
    kls = getattr(m, data['_class'])
    from_json = getattr(kls, 'from_json')
    return from_json(s)
Esempio n. 5
0
def build_from_document(
    service,
    base,
    future=None,
    http=None,
    developerKey=None,
    model=None,
    requestBuilder=HttpRequest):
  """Create a Resource for interacting with an API.

  Same as `build()`, but constructs the Resource object from a discovery
  document that is it given, as opposed to retrieving one over HTTP.

  Args:
    service: string, discovery document.
    base: string, base URI for all HTTP requests, usually the discovery URI.
    future: string, discovery document with future capabilities (deprecated).
    http: httplib2.Http, An instance of httplib2.Http or something that acts
      like it that HTTP requests will be made through.
    developerKey: string, Key for controlling API usage, generated
      from the API Console.
    model: Model class instance that serializes and de-serializes requests and
      responses.
    requestBuilder: Takes an http request and packages it up to be executed.

  Returns:
    A Resource object with methods for interacting with the service.
  """

  # future is no longer used.
  future = {}

  service = simplejson.loads(service)
  base = urlparse.urljoin(base, service['basePath'])
  schema = Schemas(service)

  if model is None:
    features = service.get('features', [])
    model = JsonModel('dataWrapper' in features)
  resource = _createResource(http, base, model, requestBuilder, developerKey,
                       service, service, schema)

  return resource
Esempio n. 6
0
 def from_json(s):
   d = simplejson.loads(s)
   return MediaInMemoryUpload(base64.b64decode(d['_b64body']),
                              d['_mimetype'], d['_chunksize'],
                              d['_resumable'])
Esempio n. 7
0
 def from_json(s):
   d = simplejson.loads(s)
   return MediaFileUpload(
       d['_filename'], d['_mimetype'], d['_chunksize'], d['_resumable'])
Esempio n. 8
0
def build(serviceName,
          version,
          http=None,
          discoveryServiceUrl=DISCOVERY_URI,
          developerKey=None,
          model=None,
          requestBuilder=HttpRequest):
  """Construct a Resource for interacting with an API.

  Construct a Resource object for interacting with an API. The serviceName and
  version are the names from the Discovery service.

  Args:
    serviceName: string, name of the service.
    version: string, the version of the service.
    http: httplib2.Http, An instance of httplib2.Http or something that acts
      like it that HTTP requests will be made through.
    discoveryServiceUrl: string, a URI Template that points to the location of
      the discovery service. It should have two parameters {api} and
      {apiVersion} that when filled in produce an absolute URI to the discovery
      document for that service.
    developerKey: string, key obtained from
      https://code.google.com/apis/console.
    model: apiclient.Model, converts to and from the wire format.
    requestBuilder: apiclient.http.HttpRequest, encapsulator for an HTTP
      request.

  Returns:
    A Resource object with methods for interacting with the service.
  """
  params = {
      'api': serviceName,
      'apiVersion': version
      }

  if http is None:
    http = httplib2.Http()

  requested_url = uritemplate.expand(discoveryServiceUrl, params)

  # REMOTE_ADDR is defined by the CGI spec [RFC3875] as the environment
  # variable that contains the network address of the client sending the
  # request. If it exists then add that to the request for the discovery
  # document to avoid exceeding the quota on discovery requests.
  if 'REMOTE_ADDR' in os.environ:
    requested_url = _add_query_parameter(requested_url, 'userIp',
                                         os.environ['REMOTE_ADDR'])
  logger.info('URL being requested: %s' % requested_url)

  resp, content = http.request(requested_url)

  if resp.status == 404:
    raise UnknownApiNameOrVersion("name: %s  version: %s" % (serviceName,
                                                            version))
  if resp.status >= 400:
    raise HttpError(resp, content, requested_url)

  try:
    service = simplejson.loads(content)
  except ValueError, e:
    logger.error('Failed to parse as JSON: ' + content)
    raise InvalidJsonError()
Esempio n. 9
0
 def deserialize(self, content):
   body = simplejson.loads(content)
   if isinstance(body, dict) and 'data' in body:
     body = body['data']
   return body