Python googleapiclient.discovery() Examples

The following are code examples for showing how to use googleapiclient.discovery(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: cloud-profiler-python   Author: GoogleCloudPlatform   File: client.py    Apache License 2.0 7 votes vote down vote up
def _filter_log(self):
    """Disables logging in the discovery API to avoid excessive logging."""

    class _ChildLogFilter(logging.Filter):
      """Filter to eliminate info-level logging when called from this module."""

      def __init__(self, filter_levels=None):
        super(_ChildLogFilter, self).__init__()
        self._filter_levels = filter_levels or set(logging.INFO)
        # Get name without extension to avoid .py vs .pyc issues
        self._my_filename = os.path.splitext(
            inspect.getmodule(_ChildLogFilter).__file__)[0]

      def filter(self, record):
        if record.levelno not in self._filter_levels:
          return True
        callerframes = inspect.getouterframes(inspect.currentframe())
        for f in callerframes:
          if os.path.splitext(f[1])[0] == self._my_filename:
            return False
        return True

    googleapiclient.discovery.logger.addFilter(_ChildLogFilter({logging.INFO})) 
Example 2
Project: cloud-profiler-python   Author: GoogleCloudPlatform   File: client.py    Apache License 2.0 5 votes vote down vote up
def _build_service(self):
    """Builds a discovery client for talking to the Profiler."""
    http = httplib2.Http(timeout=_PROFILER_SERVICE_TIMEOUT_SEC)
    http = google_auth_httplib2.AuthorizedHttp(self._credentials, http)
    profiler_api = googleapiclient.discovery.build(
        'cloudprofiler',
        'v2',
        http=http,
        cache_discovery=False,
        requestBuilder=ProfilerHttpRequest,
        discoveryServiceUrl=self._discovery_service_url)
    return profiler_api.projects().profiles() 
Example 3
Project: AvereSDK   Author: Azure   File: gce.py    MIT License 5 votes vote down vote up
def connection(self, connection_type='compute', version='v1', retries=CONNECTION_TIMEOUT, scopes=None): #pylint: disable=arguments-differ
        '''Connection factory, returns a new connection or thread local copy

            Arguments:
                connection_type (str, optional): connection type (compute, storage)
                version (str, optional): currently unused
                retries (int, optional): number of retries, default to vFXT.service.CONNECTION_TIMEOUT
                scopes ([str], optional): list of scopes to request, defaults to DEFAULT_SCOPES
        '''
        try:
            if self.local.instance_data['token_expires'] < int(time.time()):
                log.debug("Access token expired, forcing refresh")
                self.local.connections = {}
        except Exception:
            pass

        if not hasattr(self.local, 'connections'):
            self.local.connections = {}

        connection_sig = '{}_{}'.format(connection_type, version)
        if not self.local.connections.get(connection_sig, False):
            if self.access_token:
                self.local.instance_data = self.get_instance_data(source_address=self.source_address)
                self.local.access_token = self.local.instance_data['access_token']

            log.debug("Creating new {} connection object".format(connection_type))
            connection_attempts = 0
            while True:
                try:
                    self.local.connections[connection_sig] = googleapiclient.discovery.build(connection_type, version, http=self._auth_http(scopes=scopes))
                    break
                except Exception as e:
                    if connection_attempts == retries:
                        raise vFXTServiceConnectionFailure("Failed to establish connection to service: {}".format(e))
                    log.debug("Retrying failed connection attempt: {}".format(e))
                    connection_attempts += 1
                    time.sleep(backoff(connection_attempts))

        return self.local.connections[connection_sig] 
Example 4
Project: shoogle   Author: tokland   File: execute.py    GNU General Public License v3.0 5 votes vote down vote up
def run(options):
    """Run command execute."""
    service_id, resource_name, method_name = lib.pad_list(options.api_path.split(".", 2), 3)
    request_fd = (sys.stdin if options.json_request == "-" else open(options.json_request))
    method_options = lib.load_json(request_fd.read())
    try:
        response = do_request(service_id, resource_name, method_name, method_options, options)
        lib.output(lib.pretty_json(response))
    except TypeError as error:
        frm = inspect.trace()[-1]
        mod = inspect.getmodule(frm[0])
        if mod.__name__ == 'googleapiclient.discovery':
            config.logger.error("googleapiclient.discovery: {}".format(error))
        else:
            raise 
Example 5
Project: shoogle   Author: tokland   File: execute.py    GNU General Public License v3.0 5 votes vote down vote up
def build_service(service_id, credentials):
    """Return service object from ID and credentials."""
    base_http = httplib2.Http()
    http = (credentials.authorize(base_http) if credentials else base_http)
    service_name, version = service_id.split(":", 1)
    return googleapiclient.discovery.build(service_name, version, http=http) 
Example 6
Project: recsys2019   Author: logicai-io   File: create_instance_and_run_model.py    Apache License 2.0 5 votes vote down vote up
def main(config_file, validation):
    compute = googleapiclient.discovery.build("compute", "v1")
    project = "logicai-recsys2019"
    timestamp = get_timestamp()
    zone = "europe-west1-b"
    snapshot_name = "recsys1-models"
    instance_name = f"recsys-tmp-{timestamp}"
    validation_str = "val" if validation else "sub"
    disk_name = f"recsys-tmp-disk-{timestamp}"
    with open(config_file) as inp:
        model_config = inp.read()
    config_hash = str(str_to_hash(model_config) % 1_000_000)
    storage_path = f"predictions/runs/{config_hash}_{timestamp}_{validation_str}/"
    # make sure it is a proper json
    assert json.loads(model_config)
    validation = 1 if validation else 0
    print("Clone disk from snapshot")
    operation = clone_disk_from_snapshot(
        compute=compute, project=project, zone=zone, snapshot_name=snapshot_name, disk_name=disk_name
    )
    print(operation)
    print("Waiting for creation")
    wait_for_operation(compute, project, zone, operation["name"])
    print("Create instance")
    operation = create_instance(
        compute=compute,
        project=project,
        zone=zone,
        name=instance_name,
        model_config=model_config,
        validation=validation,
        storage_path=storage_path,
        disk_name=disk_name,
    )
    print(operation)
    wait_for_operation(compute, project, zone, operation["name"])
    print("Waiting some time for the network")
    time.sleep(60)
    os.system(f"gcloud compute scp startup-script.sh [email protected]{instance_name}:/tmp/")
    os.system(f"gcloud compute ssh {instance_name} --command='chmod +x /tmp/startup-script.sh'")
    os.system(f"gcloud compute ssh {instance_name} --command='nohup /tmp/startup-script.sh &'") 
Example 7
Project: hyou   Author: google   File: api.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, http, discovery):
        if discovery:
            self.sheets = googleapiclient.discovery.build(
                'sheets', 'v4', http=http,
                discoveryServiceUrl=SHEETS_API_DISCOVERY_URL)
            self.drive = googleapiclient.discovery.build(
                'drive', 'v2', http=http)
        else:
            self.sheets = googleapiclient.discovery.build_from_document(
                schema.SHEETS_V4, http=http)
            self.drive = googleapiclient.discovery.build_from_document(
                schema.DRIVE_V2, http=http)