Python包

问题描述 投票:1回答:1

我尝试运行使用Google云的代码。

import signal
import sys

from google.cloud import language, exceptions

# create a Google Cloud Natural Languague API Python client
client = language.LanguageServiceClient()

但它给出以下错误消息:

  Traceback (most recent call last):
  File "analyse-comments.py", line 7, in <module>
    client = language.LanguageServiceClient()
  File "C:\Python27\lib\site-packages\google\cloud\language_v1\gapic\language_service_client.py", line 92, in __init__
    scopes=self._DEFAULT_SCOPES)
  File "C:\Python27\lib\site-packages\google\api_core\grpc_helpers.py", line 132, in create_channel
    credentials, _ = google.auth.default(scopes=scopes)
  File "C:\Python27\lib\site-packages\google\auth\_default.py", line 283, in default
    raise exceptions.DefaultCredentialsError(_HELP_MESSAGE)
google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or
explicitly create credential and re-run the application. For more
information, please see
https://developers.google.com/accounts/docs/application-default-credentials.

第7行是代码的一部分

 client = language.LanguageServiceClient()

我已经pip安装谷歌和云。我有谷歌寻求解决方案,但没有一个解决方案符合我的情况需要解决的问题。

python google-cloud-platform service-accounts google-natural-language
1个回答
1
投票

您共享的错误明确指出凭据存在问题:

google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or
explicitly create credential and re-run the application.

它邀请您访问Setting Up Authentication的文档页面有关此主题的更多信息:

For more information, please see https://developers.google.com/accounts/docs/application-default-credentials.

这里的具体问题是您正在使用的客户端库(google.cloud.language)正在尝试直接在环境变量GOOGLE_APPLICATION_CREDENTIALS中找到要使用您的GCP帐户进行身份验证的凭据,但它无法找到它们。为了解决这个问题,您应该首先从Service Accounts page in the Console下载服务帐户的JSON密钥(单击右边的三个点并创建一个新的JSON密钥),将其存储在本地,然后使用GOOGLE_APPLICATION_CREDENTIALS指向它,作为explained in the documentation,取决于您的操作系统分布。

使用JSON键的正确目录路径填充此环境变量后,您正在使用的客户端库将能够正确进行身份验证,并且错误应该消失。

此外,如果该过程对您不起作用(我没有看到任何原因),您可以将凭证文件显式传递给您正在实例化的LanguageServiceClient(),如下所示,详见API reference for the Natural Language API

from google.cloud import language
from google.oauth2 import service_account

creds = service_account.Credentials.from_service_account_file('path/key.json')
client = language.LanguageServiceClient(
    credentials=creds,
)
© www.soinside.com 2019 - 2024. All rights reserved.