获取此错误:
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代码:
from google.cloud import secretmanager
# Create the Secret Manager client.
client = secretmanager.SecretManagerServiceClient().from_service_account_json("app/integrations/google/service_account.json")
在tasks_client = tasks_v2.CloudTasksClient.from_service_account_json(settings.GOOGLE_CLOUD_KEY_FILE_NAME)
等其他谷歌服务中使用此from_service_account_json()
时,服务帐户信誉正常工作和storage_client = storage.Client.from_service_account_json("app/keys/google-creds.json")
为什么它在这种情况下不起作用?
您需要将函数用作类而不是实例方法:
from google.cloud import secretmanager
client = secretmanager.SecretManagerServiceClient.from_service_account_file(
"/path/to/key.json",
)
或者您可以预先创建凭据:
from google.cloud import secretmanager
from google.oauth2 import service_account
credentials = service_account.Credentials.from_service_account_file(
"/path/to/key.json",
)
client = secretmanager.SecretManagerServiceClient(
credentials=credentials,
)
该方法是有效的,但通常情况下,您会更好地使用应用程序默认凭据来实现可移植性,并将配置排除在代码之外。