Python oauth2client.client.GoogleCredentials.get_application_default() Examples

The following are 30 code examples for showing how to use oauth2client.client.GoogleCredentials.get_application_default(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module oauth2client.client.GoogleCredentials , or try the search function .

Example 1
Project: gcp-variant-transforms   Author: googlegenomics   File: variant_transform_options.py    License: Apache License 2.0 6 votes vote down vote up
def validate(self, parsed_args, client=None):
    if not client:
      credentials = GoogleCredentials.get_application_default().create_scoped(
          ['https://www.googleapis.com/auth/bigquery'])
      client = bigquery.BigqueryV2(credentials=credentials)

    project_id, dataset_id, table_id = bigquery_util.parse_table_reference(
        parsed_args.input_table)
    if not bigquery_util.table_exist(client, project_id, dataset_id, table_id):
      raise ValueError('Table {}:{}.{} does not exist.'.format(
          project_id, dataset_id, table_id))
    if table_id.count(TABLE_SUFFIX_SEPARATOR) != 1:
      raise ValueError(
          'Input table {} is malformed - exactly one suffix separator "{}" is '
          'required'.format(parsed_args.input_table,
                            TABLE_SUFFIX_SEPARATOR))
    base_table_id = table_id[:table_id.find(TABLE_SUFFIX_SEPARATOR)]
    sample_table_id = bigquery_util.compose_table_name(base_table_id,
                                                       SAMPLE_INFO_TABLE_SUFFIX)

    if not bigquery_util.table_exist(client, project_id, dataset_id,
                                     sample_table_id):
      raise ValueError('Sample table {}:{}.{} does not exist.'.format(
          project_id, dataset_id, sample_table_id)) 
Example 2
Project: earthengine   Author: mortcanty   File: client.py    License: MIT License 6 votes vote down vote up
def __init__(self, access_token, client_id, client_secret, refresh_token,
               token_expiry, token_uri, user_agent,
               revoke_uri=GOOGLE_REVOKE_URI):
    """Create an instance of GoogleCredentials.

    This constructor is not usually called by the user, instead
    GoogleCredentials objects are instantiated by
    GoogleCredentials.from_stream() or
    GoogleCredentials.get_application_default().

    Args:
      access_token: string, access token.
      client_id: string, client identifier.
      client_secret: string, client secret.
      refresh_token: string, refresh token.
      token_expiry: datetime, when the access_token expires.
      token_uri: string, URI of token endpoint.
      user_agent: string, The HTTP User-Agent to provide for this application.
      revoke_uri: string, URI for revoke endpoint.
        Defaults to GOOGLE_REVOKE_URI; a token can't be revoked if this is None.
    """
    super(GoogleCredentials, self).__init__(
        access_token, client_id, client_secret, refresh_token, token_expiry,
        token_uri, user_agent, revoke_uri=revoke_uri) 
Example 3
Project: flocker   Author: ClusterHQ   File: gce.py    License: Apache License 2.0 6 votes vote down vote up
def gce_credentials_from_config(gce_credentials_config=None):
    """
    This function creates a proper GCE credentials object either from a passed
    in configuration blob or, if this code is being run on a GCE instance, from
    the default service account credentials associated with the VM.

    :param dict gce_credentials_config: A credentials dict used to authenticate
        against GCE. This should have the same content as the JSON blob you
        download when you create a new key for a service account. If this is
        ``None``, then the instances implicit credentials will be used.

    :returns: A GCE credentials object for use with the GCE API.
    """
    if gce_credentials_config is not None:
        credentials = ServiceAccountCredentials.from_p12_keyfile_buffer(
            service_account_email=gce_credentials_config['client_email'],
            file_buffer=BytesIO(gce_credentials_config['private_key']),
            scopes=[
                u"https://www.googleapis.com/auth/compute",
            ]
        )
    else:
        credentials = GoogleCredentials.get_application_default()
    return credentials 
Example 4
Project: identity-toolkit-python-client   Author: google   File: rpchelper.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, service_account_email, service_account_key,
               google_api_url, http):
    self.credentials = None
    if service_account_email and service_account_key:
      self.service_account_email = service_account_email
      self.service_account_key = service_account_key
    else:
      self.service_account_email = ''
      self.service_account_key = ''
      try:
        self.credentials = GoogleCredentials.get_application_default() \
            .create_scoped(RpcHelper.GITKIT_SCOPE)
      except Exception as e:
        print('WARNING: unable to retrieve service account credentials.')
    self.google_api_url = google_api_url + 'identitytoolkit/v3/relyingparty/'

    if http is None:
      self.http = httplib2.Http(client.MemoryCache())
    else:
      self.http = http 
Example 5
Project: luci-py   Author: luci   File: client.py    License: Apache License 2.0 6 votes vote down vote up
def from_json(cls, json_data):
        # TODO(issue 388): eliminate the circularity that is the reason for
        #                  this non-top-level import.
        from oauth2client.service_account import ServiceAccountCredentials
        data = json.loads(_from_bytes(json_data))

        # We handle service_account.ServiceAccountCredentials since it is a
        # possible return type of GoogleCredentials.get_application_default()
        if (data['_module'] == 'oauth2client.service_account' and
            data['_class'] == 'ServiceAccountCredentials'):
            return ServiceAccountCredentials.from_json(data)

        token_expiry = _parse_expiry(data.get('token_expiry'))
        google_credentials = cls(
            data['access_token'],
            data['client_id'],
            data['client_secret'],
            data['refresh_token'],
            token_expiry,
            data['token_uri'],
            data['user_agent'],
            revoke_uri=data.get('revoke_uri', None))
        google_credentials.invalid = data['invalid']
        return google_credentials 
Example 6
Project: luci-py   Author: luci   File: client.py    License: Apache License 2.0 6 votes vote down vote up
def from_json(cls, json_data):
        # TODO(issue 388): eliminate the circularity that is the reason for
        #                  this non-top-level import.
        from oauth2client.service_account import ServiceAccountCredentials
        data = json.loads(_from_bytes(json_data))

        # We handle service_account.ServiceAccountCredentials since it is a
        # possible return type of GoogleCredentials.get_application_default()
        if (data['_module'] == 'oauth2client.service_account' and
            data['_class'] == 'ServiceAccountCredentials'):
            return ServiceAccountCredentials.from_json(data)

        token_expiry = _parse_expiry(data.get('token_expiry'))
        google_credentials = cls(
            data['access_token'],
            data['client_id'],
            data['client_secret'],
            data['refresh_token'],
            token_expiry,
            data['token_uri'],
            data['user_agent'],
            revoke_uri=data.get('revoke_uri', None))
        google_credentials.invalid = data['invalid']
        return google_credentials 
Example 7
Project: luci-py   Author: luci   File: client.py    License: Apache License 2.0 6 votes vote down vote up
def from_json(cls, json_data):
        # TODO(issue 388): eliminate the circularity that is the reason for
        #                  this non-top-level import.
        from oauth2client.service_account import ServiceAccountCredentials
        data = json.loads(_from_bytes(json_data))

        # We handle service_account.ServiceAccountCredentials since it is a
        # possible return type of GoogleCredentials.get_application_default()
        if (data['_module'] == 'oauth2client.service_account' and
            data['_class'] == 'ServiceAccountCredentials'):
            return ServiceAccountCredentials.from_json(data)

        token_expiry = _parse_expiry(data.get('token_expiry'))
        google_credentials = cls(
            data['access_token'],
            data['client_id'],
            data['client_secret'],
            data['refresh_token'],
            token_expiry,
            data['token_uri'],
            data['user_agent'],
            revoke_uri=data.get('revoke_uri', None))
        google_credentials.invalid = data['invalid']
        return google_credentials 
Example 8
Project: luci-py   Author: luci   File: client.py    License: Apache License 2.0 6 votes vote down vote up
def from_json(cls, json_data):
        # TODO(issue 388): eliminate the circularity that is the reason for
        #                  this non-top-level import.
        from oauth2client.service_account import ServiceAccountCredentials
        data = json.loads(_from_bytes(json_data))

        # We handle service_account.ServiceAccountCredentials since it is a
        # possible return type of GoogleCredentials.get_application_default()
        if (data['_module'] == 'oauth2client.service_account' and
            data['_class'] == 'ServiceAccountCredentials'):
            return ServiceAccountCredentials.from_json(data)

        token_expiry = _parse_expiry(data.get('token_expiry'))
        google_credentials = cls(
            data['access_token'],
            data['client_id'],
            data['client_secret'],
            data['refresh_token'],
            token_expiry,
            data['token_uri'],
            data['user_agent'],
            revoke_uri=data.get('revoke_uri', None))
        google_credentials.invalid = data['invalid']
        return google_credentials 
Example 9
Project: luci-py   Author: luci   File: client.py    License: Apache License 2.0 6 votes vote down vote up
def from_json(cls, json_data):
        # TODO(issue 388): eliminate the circularity that is the reason for
        #                  this non-top-level import.
        from oauth2client.service_account import ServiceAccountCredentials
        data = json.loads(_from_bytes(json_data))

        # We handle service_account.ServiceAccountCredentials since it is a
        # possible return type of GoogleCredentials.get_application_default()
        if (data['_module'] == 'oauth2client.service_account' and
            data['_class'] == 'ServiceAccountCredentials'):
            return ServiceAccountCredentials.from_json(data)

        token_expiry = _parse_expiry(data.get('token_expiry'))
        google_credentials = cls(
            data['access_token'],
            data['client_id'],
            data['client_secret'],
            data['refresh_token'],
            token_expiry,
            data['token_uri'],
            data['user_agent'],
            revoke_uri=data.get('revoke_uri', None))
        google_credentials.invalid = data['invalid']
        return google_credentials 
Example 10
Project: pghoard   Author: aiven   File: google.py    License: Apache License 2.0 6 votes vote down vote up
def get_credentials(credential_file=None, credentials=None):
    if credential_file:
        return GoogleCredentials.from_stream(credential_file)

    if credentials and credentials["type"] == "service_account":
        return ServiceAccountCredentials_from_dict(credentials)

    if credentials and credentials["type"] == "authorized_user":
        return GoogleCredentials(
            access_token=None,
            client_id=credentials["client_id"],
            client_secret=credentials["client_secret"],
            refresh_token=credentials["refresh_token"],
            token_expiry=None,
            token_uri=GOOGLE_TOKEN_URI,
            user_agent="pghoard")

    return GoogleCredentials.get_application_default() 
Example 11
Project: fine-lm   Author: akzaidi   File: cloud_mlengine.py    License: MIT License 5 votes vote down vote up
def launch_job(job_spec):
  """Launch job on ML Engine."""
  project_id = "projects/{}".format(
      text_encoder.native_to_unicode(cloud.default_project()))
  credentials = GoogleCredentials.get_application_default()
  cloudml = discovery.build("ml", "v1", credentials=credentials,
                            cache_discovery=False)
  request = cloudml.projects().jobs().create(body=job_spec, parent=project_id)
  request.execute() 
Example 12
Project: fine-lm   Author: akzaidi   File: query.py    License: MIT License 5 votes vote down vote up
def make_request_fn():
  """Returns a request function."""
  if FLAGS.cloud_mlengine_model_name:
    request_fn = serving_utils.make_cloud_mlengine_request_fn(
        credentials=GoogleCredentials.get_application_default(),
        model_name=FLAGS.cloud_mlengine_model_name,
        version=FLAGS.cloud_mlengine_model_version)
  else:

    request_fn = serving_utils.make_grpc_request_fn(
        servable_name=FLAGS.servable_name,
        server=FLAGS.server,
        timeout_secs=FLAGS.timeout_secs)
  return request_fn 
Example 13
Project: gcp-variant-transforms   Author: googlegenomics   File: variant_transform_options.py    License: Apache License 2.0 5 votes vote down vote up
def validate(self, parsed_args, client=None):
    # type: (argparse.Namespace, bigquery.BigqueryV2) -> None
    if parsed_args.update_schema_on_append and not parsed_args.append:
      raise ValueError('--update_schema_on_append requires --append to be '
                       'true.')
    if (not parsed_args.sharding_config_path or
        not parsed_args.sharding_config_path.strip()):
      raise ValueError(
          '--sharding_config_path must point to a valid config file.')

    if not client:
      credentials = GoogleCredentials.get_application_default().create_scoped(
          ['https://www.googleapis.com/auth/bigquery'])
      client = bigquery.BigqueryV2(credentials=credentials)
    if not parsed_args.output_table:
      raise ValueError('--output_table must have a value.')
    self._validate_output_tables(
        client, parsed_args.output_table,
        parsed_args.sharding_config_path, parsed_args.append, True)

    if parsed_args.sample_lookup_optimized_output_table:
      if (parsed_args.output_table ==
          parsed_args.sample_lookup_optimized_output_table):
        raise ValueError('sample_lookup_optimized_output_table cannot be the '
                         'same as output_table.')
      self._validate_output_tables(
          client, parsed_args.sample_lookup_optimized_output_table,
          parsed_args.sharding_config_path, parsed_args.append, False) 
Example 14
Project: gcp-variant-transforms   Author: googlegenomics   File: bigquery_util.py    License: Apache License 2.0 5 votes vote down vote up
def update_bigquery_schema_on_append(schema_fields, output_table):
  # type: (List[beam_bigquery.TableFieldSchema], str) -> None
  """Update BQ schema by combining existing one with a new one, if possible.

  If table does not exist, do not need to update the schema.
  TODO (yifangchen): Move the logic into validate().
  """
  output_table_re_match = re.match(
      r'^((?P<project>.+):)(?P<dataset>\w+)\.(?P<table>[\w\$]+)$',
      output_table)
  credentials = GoogleCredentials.get_application_default().create_scoped(
      ['https://www.googleapis.com/auth/bigquery'])
  client = beam_bigquery.BigqueryV2(credentials=credentials)
  try:
    project_id = output_table_re_match.group('project')
    dataset_id = output_table_re_match.group('dataset')
    table_id = output_table_re_match.group('table')
    existing_table = client.tables.Get(beam_bigquery.BigqueryTablesGetRequest(
        projectId=project_id,
        datasetId=dataset_id,
        tableId=table_id))
  except exceptions.HttpError:
    return

  new_schema = beam_bigquery.TableSchema()
  new_schema.fields = _get_merged_field_schemas(existing_table.schema.fields,
                                                schema_fields)
  existing_table.schema = new_schema
  try:
    client.tables.Update(beam_bigquery.BigqueryTablesUpdateRequest(
        projectId=project_id,
        datasetId=dataset_id,
        table=existing_table,
        tableId=table_id))
  except exceptions.HttpError as e:
    raise RuntimeError('BigQuery schema update failed: %s' % str(e)) 
Example 15
Project: cloudml-samples   Author: GoogleCloudPlatform   File: inference.py    License: Apache License 2.0 5 votes vote down vote up
def predict_cmle(instances):
    """ Use a deployed model to AI Platform to perform prediction

    Args:
        instances: list of json, csv, or tf.example objects, based on the serving function called
    Returns:
        response - dictionary. If no error, response will include an item with 'predictions' key
    """

    credentials = GoogleCredentials.get_application_default()

    service = discovery.build('ml', 'v1', credentials=credentials)
    model_url = 'projects/{}/models/{}'.format(GCP_PROJECT, CMLE_MODEL_NAME)

    if CMLE_MODEL_VERSION is not None:
        model_url += '/versions/{}'.format(CMLE_MODEL_VERSION)

    request_data = {
        'instances': instances
    }

    response = service.projects().predict(
        body=request_data,
        name=model_url
    ).execute()

    output = response
    return output 
Example 16
Project: tensor2tensor   Author: tensorflow   File: cloud_mlengine.py    License: Apache License 2.0 5 votes vote down vote up
def launch_job(job_spec):
  """Launch job on ML Engine."""
  project_id = "projects/{}".format(
      text_encoder.native_to_unicode(default_project()))
  credentials = GoogleCredentials.get_application_default()
  cloudml = discovery.build("ml", "v1", credentials=credentials,
                            cache_discovery=False)
  request = cloudml.projects().jobs().create(body=job_spec, parent=project_id)
  request.execute() 
Example 17
Project: tensor2tensor   Author: tensorflow   File: query.py    License: Apache License 2.0 5 votes vote down vote up
def make_request_fn():
  """Returns a request function."""
  if FLAGS.cloud_mlengine_model_name:
    request_fn = serving_utils.make_cloud_mlengine_request_fn(
        credentials=GoogleCredentials.get_application_default(),
        model_name=FLAGS.cloud_mlengine_model_name,
        version=FLAGS.cloud_mlengine_model_version)
  else:

    request_fn = serving_utils.make_grpc_request_fn(
        servable_name=FLAGS.servable_name,
        server=FLAGS.server,
        timeout_secs=FLAGS.timeout_secs)
  return request_fn 
Example 18
Project: gae-dataflow   Author: amygdala   File: main.py    License: Apache License 2.0 5 votes vote down vote up
def get(self):
    is_cron = self.request.headers.get('X-Appengine-Cron', False)
    # logging.info("is_cron is %s", is_cron)
    # Comment out the following check to allow non-cron-initiated requests.
    if not is_cron:
      return 'Blocked.'
    # These env vars are set in app.yaml.
    PROJECT = os.environ['PROJECT']
    BUCKET = os.environ['BUCKET']
    TEMPLATE = os.environ['TEMPLATE_NAME']

    # Because we're using the same job name each time, if you try to launch one
    # job while another is still running, the second will fail.
    JOBNAME = PROJECT + '-twproc-template'

    credentials = GoogleCredentials.get_application_default()
    service = build('dataflow', 'v1b3', credentials=credentials)

    BODY = {
            "jobName": "{jobname}".format(jobname=JOBNAME),
            "gcsPath": "gs://{bucket}/templates/{template}".format(
                bucket=BUCKET, template=TEMPLATE),
            "parameters": {"timestamp": str(datetime.datetime.utcnow())},
             "environment": {
                "tempLocation": "gs://{bucket}/temp".format(bucket=BUCKET),
                "zone": "us-central1-f"
             }
        }

    dfrequest = service.projects().templates().create(
        projectId=PROJECT, body=BODY)
    dfresponse = dfrequest.execute()
    logging.info(dfresponse)
    self.response.write('Done') 
Example 19
Project: cartography   Author: lyft   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def start_gsuite_ingestion(session, config):
    """
    Starts the GSuite ingestion process by initializing

    :param session: The Neo4j session
    :param config: A `cartography.config` object
    :return: Nothing
    """
    common_job_parameters = {
        "UPDATE_TAG": config.update_tag,
    }

    try:
        credentials = GoogleCredentials.from_stream(GSUITE_CREDS)
        credentials = credentials.create_scoped(OAUTH_SCOPE)
        credentials = credentials.create_delegated(GSUITE_DELEGATED_ADMIN)

    except ApplicationDefaultCredentialsError as e:
        logger.debug('Error occurred calling GoogleCredentials.get_application_default().', exc_info=True)
        logger.error(
            (
                "Unable to initialize GSuite creds. If you don't have GSuite data or don't want to load "
                'Gsuite data then you can ignore this message. Otherwise, the error code is: %s '
                'Make sure your GSuite credentials are configured correctly, your credentials file (if any) is valid. '
                'For more details see README'
            ),
            e,
        )
        return

    resources = _initialize_resources(credentials)
    api.sync_gsuite_users(session, resources.admin, config.update_tag, common_job_parameters)
    api.sync_gsuite_groups(session, resources.admin, config.update_tag, common_job_parameters) 
Example 20
Project: BERT   Author: yyht   File: cloud_mlengine.py    License: Apache License 2.0 5 votes vote down vote up
def launch_job(job_spec):
  """Launch job on ML Engine."""
  project_id = "projects/{}".format(
      text_encoder.native_to_unicode(default_project()))
  credentials = GoogleCredentials.get_application_default()
  cloudml = discovery.build("ml", "v1", credentials=credentials,
                            cache_discovery=False)
  request = cloudml.projects().jobs().create(body=job_spec, parent=project_id)
  request.execute() 
Example 21
Project: BERT   Author: yyht   File: query.py    License: Apache License 2.0 5 votes vote down vote up
def make_request_fn():
  """Returns a request function."""
  if FLAGS.cloud_mlengine_model_name:
    request_fn = serving_utils.make_cloud_mlengine_request_fn(
        credentials=GoogleCredentials.get_application_default(),
        model_name=FLAGS.cloud_mlengine_model_name,
        version=FLAGS.cloud_mlengine_model_version)
  else:

    request_fn = serving_utils.make_grpc_request_fn(
        servable_name=FLAGS.servable_name,
        server=FLAGS.server,
        timeout_secs=FLAGS.timeout_secs)
  return request_fn 
Example 22
Project: sregistry-cli   Author: singularityhub   File: __init__.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def _get_services(self, version="v1"):
        """get version 1 of the google compute and storage service

        Parameters
        ==========
        version: version to use (default is v1)
        """
        self._bucket_service = storage.Client()
        creds = GoogleCredentials.get_application_default()
        self._storage_service = discovery_build("storage", version, credentials=creds)
        self._compute_service = discovery_build("compute", version, credentials=creds) 
Example 23
Project: sregistry-cli   Author: singularityhub   File: __init__.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def _get_services(self, version="v1"):
        """get version 1 of the google compute and storage service

            Parameters
            ==========
            version: version to use (default is v1)
        """
        self._bucket_service = storage.Client()
        creds = GoogleCredentials.get_application_default()
        self._storage_service = discovery_build("storage", version, credentials=creds)
        self._build_service = discovery_build("cloudbuild", version, credentials=creds) 
Example 24
Project: serverless-cloud-vision   Author: ramhiser   File: __init__.py    License: MIT License 5 votes vote down vote up
def get_vision_service():
    credentials = GoogleCredentials.get_application_default()
    return discovery.build('vision', 'v1',
                           credentials=credentials,
                           discoveryServiceUrl=API_URL) 
Example 25
Project: tokenquery   Author: ramtinms   File: google_nlp_api.py    License: GNU General Public License v3.0 5 votes vote down vote up
def call_google_nlp(text):
    """Use the NL API to analyze the given text string, and returns the
    response from the API.  Requests an encodingType that matches
    the encoding used natively by Python.  Raises an
    errors.HTTPError if there is a connection problem.
    """

    # TODO check cred exists ....

    # check GOOGLE_APPLICATION_CREDENTIALS
    credentials = GoogleCredentials.get_application_default()
    scoped_credentials = credentials.create_scoped(
        ['https://www.googleapis.com/auth/cloud-platform'])
    http = httplib2.Http()
    scoped_credentials.authorize(http)
    service = discovery.build(
        'language', 'v1beta1', http=http)
    body = {
        'document': {
            'type': 'PLAIN_TEXT',
            'content': text
        },
        'features': {
            # 'extract_syntax': True,
            'extractEntities': True
        },
        'encodingType': get_native_encoding_type(),
    }
    request = service.documents().annotateText(body=body)
    return request.execute() 
Example 26
Project: cloudbridge   Author: CloudVE   File: provider.py    License: MIT License 5 votes vote down vote up
def _credentials(self):
        if not self.credentials_obj:
            if self.credentials_dict:
                self.credentials_obj = (
                        ServiceAccountCredentials.from_json_keyfile_dict(
                                self.credentials_dict))
            else:
                self.credentials_obj = (
                        GoogleCredentials.get_application_default())
        return self.credentials_obj 
Example 27
Project: keyrotator   Author: GoogleCloudPlatform   File: iam_service.py    License: Apache License 2.0 5 votes vote down vote up
def _get_iam_service():
  """Get the IAM service.

  Returns:
    An apiclient service object.
  """
  credentials = GoogleCredentials.get_application_default()
  return discovery.build(
      serviceName="iam", version="v1", credentials=credentials) 
Example 28
Project: gcp-census   Author: ocadotechnology   File: model_creator.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, model_provider):
        self.model_provider = model_provider
        self.http = self._create_http()
        self.service = googleapiclient.discovery.build(
            'bigquery',
            'v2',
            credentials=GoogleCredentials.get_application_default(),
            http=self.http
        ) 
Example 29
Project: G-Scout   Author: nccgroup   File: utility.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_gcloud_creds():
	base_script_directory = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), ".."))
	keyfile_path = os.path.join(base_script_directory, 'keyfile.json')
	if os.path.isfile(keyfile_path):
		os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = keyfile_path
	creds = GoogleCredentials.get_application_default()
	return creds 
Example 30
Project: training_results_v0.5   Author: mlperf   File: cloud_mlengine.py    License: Apache License 2.0 5 votes vote down vote up
def launch_job(job_spec):
  """Launch job on ML Engine."""
  project_id = "projects/{}".format(
      text_encoder.native_to_unicode(default_project()))
  credentials = GoogleCredentials.get_application_default()
  cloudml = discovery.build("ml", "v1", credentials=credentials,
                            cache_discovery=False)
  request = cloudml.projects().jobs().create(body=job_spec, parent=project_id)
  request.execute()