相关疑难解决方法(0)

在Python项目中设置GOOGLE_APPLICATION_CREDENTIALS以使用Google API

我是一名编程初学者,并且学习如何在Python中使用google API.

我有:

  1. 在Google Cloud上创建了一个项目,并启用了我想要使用的API,即Natural Language API.
  2. 创建了一个凭证并下载了凭证JSON文件,将其保存为apikey.JSON
  3. 在终端我运行了这个命令:export GOOGLE_APPLICATION_CREDENTIALS = apikey.JSON,没有弹出错误.

但是,即使我为此运行了最简单的代码,我也有错误,表示找不到凭证varialbe.

我不知道现在该怎么办.请帮忙.

这是我的代码:

from google.cloud import language

def sentiment_text(text):

    client = language.LanguageServiceClient()

    sentiment = client.analyze_sentiment(text).document_sentiment

    print('Score: {}'.format(sentiment.score))
    print('Magnitude: {}'.format(sentiment.magnitude))

sampletxt='Python is great'

sentiment_text(sampletxt)
Run Code Online (Sandbox Code Playgroud)

我有错误:

回溯(最近一次调用最后一次):文件"/Users/YELI1/Downloads/googlecloud/sentimentanalysis/simple.py",第21行,sentiment_text(sampletxt)

文件"/Users/YELI1/Downloads/googlecloud/sentimentanalysis/simple.py",第5行,在sentiment_text client = language.LanguageServiceClient()中

init ssl_credentials = ssl_credentials中输入文件"/usr/local/lib/python3.6/site-packages/google/cloud/gapic/language/v1/language_service_client.py",第147行

在create_stub中的文件"/usr/local/lib/python3.6/site-packages/google/gax/grpc.py",第106行

credentials = _grpc_google_auth.get_default_credentials(scopes)   File
Run Code Online (Sandbox Code Playgroud)

"/usr/local/lib/python3.6/site-packages/google/gax/_grpc_google_auth.py",第62行,在get_default_credentials凭据中,_ = google.auth.default(scopes = scopes)

文件"/usr/local/lib/python3.6/site-packages/google/auth/_default.py",第282行,默认情况下

raise exceptions.DefaultCredentialsError(_HELP_MESSAGE) google.auth.exceptions.DefaultCredentialsError: Could not
Run Code Online (Sandbox Code Playgroud)

自动确定凭据.请设置GOOGLE_APPLICATION_CREDENTIALS或明确创建凭据并重新运行该应用程序.有关详细信息,请参阅 https://developers.google.com/accounts/docs/application-default-credentials.

import os 
print(os.environ['GOOGLE_APPLICATION_CREDENTIALS']) 
Run Code Online (Sandbox Code Playgroud)

输出回溯(最近一次调用最后一次):

  File "/Users/YELI1/Downloads/googlecloud/sentimentanalysis/simple??.py", line 2, in <module>  
print(os.environ['GOOGLE_APPLICATION_CREDENTIALS']) 
   File "/usr/local/Cellar/python3/3.6.2/Frameworks/Python.framework??/Versions/3.6/lib/py??thon3.6/os.py", line 669, …
Run Code Online (Sandbox Code Playgroud)

python google-api

27
推荐指数
5
解决办法
4万
查看次数

标签 统计

google-api ×1

python ×1