当前位置: 首页>>代码示例>>Python>>正文


Python GoogleCredentials.get_application_default方法代码示例

本文整理汇总了Python中oauth2client.client.GoogleCredentials.get_application_default方法的典型用法代码示例。如果您正苦于以下问题:Python GoogleCredentials.get_application_default方法的具体用法?Python GoogleCredentials.get_application_default怎么用?Python GoogleCredentials.get_application_default使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在oauth2client.client.GoogleCredentials的用法示例。


在下文中一共展示了GoogleCredentials.get_application_default方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: validate

# 需要导入模块: from oauth2client.client import GoogleCredentials [as 别名]
# 或者: from oauth2client.client.GoogleCredentials import get_application_default [as 别名]
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)) 
开发者ID:googlegenomics,项目名称:gcp-variant-transforms,代码行数:26,代码来源:variant_transform_options.py

示例2: __init__

# 需要导入模块: from oauth2client.client import GoogleCredentials [as 别名]
# 或者: from oauth2client.client.GoogleCredentials import get_application_default [as 别名]
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) 
开发者ID:mortcanty,项目名称:earthengine,代码行数:26,代码来源:client.py

示例3: gce_credentials_from_config

# 需要导入模块: from oauth2client.client import GoogleCredentials [as 别名]
# 或者: from oauth2client.client.GoogleCredentials import get_application_default [as 别名]
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 
开发者ID:ClusterHQ,项目名称:flocker,代码行数:26,代码来源:gce.py

示例4: __init__

# 需要导入模块: from oauth2client.client import GoogleCredentials [as 别名]
# 或者: from oauth2client.client.GoogleCredentials import get_application_default [as 别名]
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 
开发者ID:google,项目名称:identity-toolkit-python-client,代码行数:22,代码来源:rpchelper.py

示例5: from_json

# 需要导入模块: from oauth2client.client import GoogleCredentials [as 别名]
# 或者: from oauth2client.client.GoogleCredentials import get_application_default [as 别名]
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 
开发者ID:luci,项目名称:luci-py,代码行数:26,代码来源:client.py

示例6: get_credentials

# 需要导入模块: from oauth2client.client import GoogleCredentials [as 别名]
# 或者: from oauth2client.client.GoogleCredentials import get_application_default [as 别名]
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() 
开发者ID:aiven,项目名称:pghoard,代码行数:20,代码来源:google.py

示例7: launch_job

# 需要导入模块: from oauth2client.client import GoogleCredentials [as 别名]
# 或者: from oauth2client.client.GoogleCredentials import get_application_default [as 别名]
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() 
开发者ID:akzaidi,项目名称:fine-lm,代码行数:11,代码来源:cloud_mlengine.py

示例8: make_request_fn

# 需要导入模块: from oauth2client.client import GoogleCredentials [as 别名]
# 或者: from oauth2client.client.GoogleCredentials import get_application_default [as 别名]
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 
开发者ID:akzaidi,项目名称:fine-lm,代码行数:16,代码来源:query.py

示例9: update_bigquery_schema_on_append

# 需要导入模块: from oauth2client.client import GoogleCredentials [as 别名]
# 或者: from oauth2client.client.GoogleCredentials import get_application_default [as 别名]
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)) 
开发者ID:googlegenomics,项目名称:gcp-variant-transforms,代码行数:38,代码来源:bigquery_util.py

示例10: predict_cmle

# 需要导入模块: from oauth2client.client import GoogleCredentials [as 别名]
# 或者: from oauth2client.client.GoogleCredentials import get_application_default [as 别名]
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 
开发者ID:GoogleCloudPlatform,项目名称:cloudml-samples,代码行数:30,代码来源:inference.py

示例11: launch_job

# 需要导入模块: from oauth2client.client import GoogleCredentials [as 别名]
# 或者: from oauth2client.client.GoogleCredentials import get_application_default [as 别名]
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() 
开发者ID:tensorflow,项目名称:tensor2tensor,代码行数:11,代码来源:cloud_mlengine.py

示例12: get

# 需要导入模块: from oauth2client.client import GoogleCredentials [as 别名]
# 或者: from oauth2client.client.GoogleCredentials import get_application_default [as 别名]
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') 
开发者ID:amygdala,项目名称:gae-dataflow,代码行数:36,代码来源:main.py

示例13: start_gsuite_ingestion

# 需要导入模块: from oauth2client.client import GoogleCredentials [as 别名]
# 或者: from oauth2client.client.GoogleCredentials import get_application_default [as 别名]
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) 
开发者ID:lyft,项目名称:cartography,代码行数:35,代码来源:__init__.py

示例14: _get_services

# 需要导入模块: from oauth2client.client import GoogleCredentials [as 别名]
# 或者: from oauth2client.client.GoogleCredentials import get_application_default [as 别名]
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) 
开发者ID:singularityhub,项目名称:sregistry-cli,代码行数:13,代码来源:__init__.py

示例15: _get_services

# 需要导入模块: from oauth2client.client import GoogleCredentials [as 别名]
# 或者: from oauth2client.client.GoogleCredentials import get_application_default [as 别名]
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) 
开发者ID:singularityhub,项目名称:sregistry-cli,代码行数:13,代码来源:__init__.py


注:本文中的oauth2client.client.GoogleCredentials.get_application_default方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。