示例#1
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
    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)
  logging.info('URL being requested: %s' % requested_url)
  resp, content = http.request(requested_url)
  if resp.status > 400:
    raise HttpError(resp, content, requested_url)
  try:
    service = simplejson.loads(content)
  except ValueError, e:
    logging.error('Failed to parse as JSON: ' + content)
    raise InvalidJsonError()
示例#2
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
    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)
    logging.info('URL being requested: %s' % requested_url)
    resp, content = http.request(requested_url)
    if resp.status > 400:
        raise HttpError(resp, content, requested_url)
    try:
        service = simplejson.loads(content)
    except ValueError, e:
        logging.error('Failed to parse as JSON: ' + content)
        raise InvalidJsonError()
示例#3
0
        def method(self, **kwargs):
            for name in kwargs.iterkeys():
                if name not in argmap:
                    raise TypeError('Got an unexpected keyword argument "%s"' %
                                    name)

            for name in required_params:
                if name not in kwargs:
                    raise TypeError('Missing required parameter "%s"' % name)

            for name, regex in pattern_params.iteritems():
                if name in kwargs:
                    if re.match(regex, kwargs[name]) is None:
                        raise TypeError(
                            'Parameter "%s" value "%s" does not match the pattern "%s"'
                            % (name, kwargs[name], regex))

            for name, enums in enum_params.iteritems():
                if name in kwargs:
                    if kwargs[name] not in enums:
                        raise TypeError(
                            'Parameter "%s" value "%s" is not an allowed value in "%s"'
                            % (name, kwargs[name], str(enums)))

            actual_query_params = {}
            actual_path_params = {}
            for key, value in kwargs.iteritems():
                to_type = param_type.get(key, 'string')
                # For repeated parameters we cast each member of the list.
                if key in repeated_params and type(value) == type([]):
                    cast_value = [_cast(x, to_type) for x in value]
                else:
                    cast_value = _cast(value, to_type)
                if key in query_params:
                    actual_query_params[argmap[key]] = cast_value
                if key in path_params:
                    actual_path_params[argmap[key]] = cast_value
            body_value = kwargs.get('body', None)
            media_filename = kwargs.get('media_body', None)

            if self._developerKey:
                actual_query_params['key'] = self._developerKey

            headers = {}
            headers, params, query, body = self._model.request(
                headers, actual_path_params, actual_query_params, body_value)

            expanded_url = uritemplate.expand(pathUrl, params)
            url = urlparse.urljoin(self._baseUrl, expanded_url + query)

            if media_filename:
                (media_mime_type,
                 encoding) = mimetypes.guess_type(media_filename)
                if media_mime_type is None:
                    raise UnknownFileType(media_filename)
                if not mimeparse.best_match([media_mime_type],
                                            ','.join(accept)):
                    raise UnacceptableMimeTypeError(media_mime_type)

                # Check the maxSize
                if maxSize > 0 and os.path.getsize(media_filename) > maxSize:
                    raise MediaUploadSizeError(media_filename)

                # Use the media path uri for media uploads
                expanded_url = uritemplate.expand(mediaPathUrl, params)
                url = urlparse.urljoin(self._baseUrl, expanded_url + query)

                if body is None:
                    headers['content-type'] = media_mime_type
                    # make the body the contents of the file
                    f = file(media_filename, 'rb')
                    body = f.read()
                    f.close()
                else:
                    msgRoot = MIMEMultipart('related')
                    # msgRoot should not write out it's own headers
                    setattr(msgRoot, '_write_headers', lambda self: None)

                    # attach the body as one part
                    msg = MIMENonMultipart(*headers['content-type'].split('/'))
                    msg.set_payload(body)
                    msgRoot.attach(msg)

                    # attach the media as the second part
                    msg = MIMENonMultipart(*media_mime_type.split('/'))
                    msg['Content-Transfer-Encoding'] = 'binary'

                    f = file(media_filename, 'rb')
                    msg.set_payload(f.read())
                    f.close()
                    msgRoot.attach(msg)

                    body = msgRoot.as_string()

                    # must appear after the call to as_string() to get the right boundary
                    headers['content-type'] = (
                        'multipart/related; '
                        'boundary="%s"') % msgRoot.get_boundary()

            logging.info('URL being requested: %s' % url)
            return self._requestBuilder(self._http,
                                        self._model.response,
                                        url,
                                        method=httpMethod,
                                        body=body,
                                        headers=headers,
                                        methodId=methodId)
示例#4
0
    def method(self, **kwargs):
      for name in kwargs.iterkeys():
        if name not in argmap:
          raise TypeError('Got an unexpected keyword argument "%s"' % name)

      for name in required_params:
        if name not in kwargs:
          raise TypeError('Missing required parameter "%s"' % name)

      for name, regex in pattern_params.iteritems():
        if name in kwargs:
          if re.match(regex, kwargs[name]) is None:
            raise TypeError(
                'Parameter "%s" value "%s" does not match the pattern "%s"' %
                (name, kwargs[name], regex))

      for name, enums in enum_params.iteritems():
        if name in kwargs:
          if kwargs[name] not in enums:
            raise TypeError(
                'Parameter "%s" value "%s" is not an allowed value in "%s"' %
                (name, kwargs[name], str(enums)))

      actual_query_params = {}
      actual_path_params = {}
      for key, value in kwargs.iteritems():
        to_type = param_type.get(key, 'string')
        # For repeated parameters we cast each member of the list.
        if key in repeated_params and type(value) == type([]):
          cast_value = [_cast(x, to_type) for x in value]
        else:
          cast_value = _cast(value, to_type)
        if key in query_params:
          actual_query_params[argmap[key]] = cast_value
        if key in path_params:
          actual_path_params[argmap[key]] = cast_value
      body_value = kwargs.get('body', None)
      media_filename = kwargs.get('media_body', None)

      if self._developerKey:
        actual_query_params['key'] = self._developerKey

      headers = {}
      headers, params, query, body = self._model.request(headers,
          actual_path_params, actual_query_params, body_value)

      expanded_url = uritemplate.expand(pathUrl, params)
      url = urlparse.urljoin(self._baseUrl, expanded_url + query)

      if media_filename:
        (media_mime_type, encoding) = mimetypes.guess_type(media_filename)
        if media_mime_type is None:
          raise UnknownFileType(media_filename)
        if not mimeparse.best_match([media_mime_type], ','.join(accept)):
          raise UnacceptableMimeTypeError(media_mime_type)

        # Check the maxSize
        if maxSize > 0 and os.path.getsize(media_filename) > maxSize:
          raise MediaUploadSizeError(media_filename)

        # Use the media path uri for media uploads
        expanded_url = uritemplate.expand(mediaPathUrl, params)
        url = urlparse.urljoin(self._baseUrl, expanded_url + query)

        if body is None:
          headers['content-type'] = media_mime_type
          # make the body the contents of the file
          f = file(media_filename, 'rb')
          body = f.read()
          f.close()
        else:
          msgRoot = MIMEMultipart('related')
          # msgRoot should not write out it's own headers
          setattr(msgRoot, '_write_headers', lambda self: None)

          # attach the body as one part
          msg = MIMENonMultipart(*headers['content-type'].split('/'))
          msg.set_payload(body)
          msgRoot.attach(msg)

          # attach the media as the second part
          msg = MIMENonMultipart(*media_mime_type.split('/'))
          msg['Content-Transfer-Encoding'] = 'binary'

          f = file(media_filename, 'rb')
          msg.set_payload(f.read())
          f.close()
          msgRoot.attach(msg)

          body = msgRoot.as_string()

          # must appear after the call to as_string() to get the right boundary
          headers['content-type'] = ('multipart/related; '
                                     'boundary="%s"') % msgRoot.get_boundary()

      logging.info('URL being requested: %s' % url)
      return self._requestBuilder(self._http,
                                  self._model.response,
                                  url,
                                  method=httpMethod,
                                  body=body,
                                  headers=headers,
                                  methodId=methodId)