gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:35:30 26 4
gpt4 key购买 nike

我是一名编程初学者,我正在尝试学习如何将 google API 与 Python 一起使用。

我有:

  1. 在 Google Cloud 上创建了一个项目并启用了我想要使用的 API,Natural Language API
  2. 创建凭据并下载凭据 JSON 文件,将其保存为 apikey.JSON
  3. 在终端中我运行了这个命令: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/py‌​thon3.6/os.py", line 669, in getitem
raise KeyError(key) from None KeyError: 'GOOGLE_APPLICATION_CREDENTIALS'

最佳答案

如果您正在使用 jupyter 笔记本并希望在 Python 代码中设置 GOOGLE_APPLICATION_CREDENTIALS 环境变量:

import os
os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="/path/to/file.json"

关于python - 在 Python 项目中设置 GOOGLE_APPLICATION_CREDENTIALS 以使用 Google API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45501082/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com