【发布时间】:2018-01-12 01:18:46
【问题描述】:
我是一名编程初学者,我正在努力学习如何将谷歌 API 与 Python 一起使用。
我有:
- 在 Google Cloud 上创建了一个项目并启用了我想要使用的 API,
Natural Language API。 - 创建凭证并下载凭证JSON文件,保存为
apikey.JSON - 在终端中我运行了这个命令:export
GOOGLE_APPLICATION_CREDENTIALS=apikey.JSON,没有弹出错误。
但是,即使我为此运行了最简单的代码,我也会遇到错误,提示找不到凭据变量。
我不知道现在该做什么。请帮忙。
这是我的代码:
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)
我有错误:
> Traceback (most recent call last): File
> "/Users/YELI1/Downloads/googlecloud/sentimentanalysis/simple.py", line
> 21, in <module>
> sentiment_text(sampletxt)
>
> File
> "/Users/YELI1/Downloads/googlecloud/sentimentanalysis/simple.py", line
> 5, in sentiment_text
> client = language.LanguageServiceClient()
>
> File
> "/usr/local/lib/python3.6/site-packages/google/cloud/gapic/language/v1/language_service_client.py",
> line 147, in __init__
> ssl_credentials=ssl_credentials)
>
> File "/usr/local/lib/python3.6/site-packages/google/gax/grpc.py",
> line 106, in create_stub
>
> credentials = _grpc_google_auth.get_default_credentials(scopes) File
> "/usr/local/lib/python3.6/site-packages/google/gax/_grpc_google_auth.py",
> line 62, in get_default_credentials
> credentials, _ = google.auth.default(scopes=scopes)
>
> File
> "/usr/local/lib/python3.6/site-packages/google/auth/_default.py", line
> 282, 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.
值不在环境中
import os
print(os.environ['GOOGLE_APPLICATION_CREDENTIALS'])
File "/usr/local/Cellar/python3/3.6.2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/os.py", line 669, in getitem
raise KeyError(key) from None KeyError: 'GOOGLE_APPLICATION_CREDENTIALS'
【问题讨论】:
-
我可以看到
print(os.environ['GOOGLE_APPLICATION_CREDENTIALS'])。 -
代码运行'import os print(os.environ['GOOGLE_APPLICATION_CREDENTIALS'])' 输出回溯(最近一次调用最后):文件“/Users/YELI1/Downloads/googlecloud/sentimentanalysis/simple.py ”,第 2 行,在
中打印(os.environ['GOOGLE_APPLICATION_CREDENTIALS'])文件“/usr/local/Cellar/python3/3.6.2/Frameworks/Python.framework/Versions/3.6/lib/python3.6 /os.py",第 669 行,在 getitem 中引发 KeyError(key) from None KeyError: 'GOOGLE_APPLICATION_CREDENTIALS' -
我不知道如何正确格式化这个东西,看起来很乱,但看起来好像是说没有'GOOGLE_APPLICATION_CREDENTIALS'这样的键。 @stovfl
-
是的,KeyError 表示请求的环境变量未在 Python 脚本的环境中设置。 Edit您的问题并添加 OS 版本、Python 版本。您必须从执行
export ...的相同 终端启动Python 脚本。
标签: python google-api