【问题标题】:Could not establish an API connection in Google Cloud Platform无法在 Google Cloud Platform 中建立 API 连接
【发布时间】:2021-01-06 09:28:49
【问题描述】:

为了从我的项目中检索监控指标,我使用了以下 Python 代码:

from google.cloud import monitoring_v3
from google.oauth2 import service_account
from googleapiclient import discovery

credentials = service_account.Credentials.from_service_account_file(
   r'D:\GCP\credentials\blahblah-04e8fd0245b8.json')

service = discovery.build('compute', 'v1', credentials=credentials)

client = monitoring_v3.MetricServiceClient()

project_name = f"projects/{blahblah-300807}"

resource_descriptors = client.list_monitored_resource_descriptors(
    name=project_name)

for descriptor in resource_descriptors:
    print(descriptor.type)

我做得很好。我正确地提供了凭据信息的文件路径,但收到了以下错误消息:

raise exceptions.DefaultCredentialsError(_HELP_MESSAGE)
google.auth.exceptions.DefaultCredentialsError: \
Could not automatically determine credentials. \
Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create \
credentials and re-run the application. \
For more information, please see \
https://cloud.google.com/docs/authentication/getting-started

我什至检查了该链接并尝试了替代方法,但仍然没有用。我该如何纠正这个问题?我是不是搞错了?

【问题讨论】:

    标签: python google-app-engine google-cloud-platform credentials


    【解决方案1】:

    创建客户端时不使用凭据

    client = monitoring_v3.MetricServiceClient()
    

    你可以这样改

    client = monitoring_v3.MetricServiceClient(credentials=credentials)
    

    就个人而言,我更喜欢不在代码中显式提供凭据,我更喜欢为此使用环境变量GOOGLE_APPLICATION_CREDENTIALS

    在您的操作系统中创建一个名为 GOOGLE_APPLICATION_CREDENTIALS 的环境变量,其值指向服务帐户密钥文件 D:\GCP\credentials\blahblah-04e8fd0245b8.json

    但是,如果它在您自己的计算机上,您甚至可以不使用服务帐户密钥文件(这并不安全,我在this article 中解释了原因),您可以使用自己的凭据。为此,只需创建一个应用程序默认凭据 (ADC),如 gcloud auth application-default login

    【讨论】:

    • 谢谢。正如您所说,它通过将凭据作为参数传递来工作。我通过将 json 文件作为值传递来创建环境变量,但这不起作用
    • 因为你是windows操作系统,又是windows操作系统,你设置好环境变量后重启电脑了吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-27
    • 1970-01-01
    • 1970-01-01
    • 2019-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多