我是一名編程初學者,並且正在學習如何使用Google API和Python。在Python項目中設置GOOGLE_APPLICATION_CREDENTIALS以使用Google API
我:
- 創建了谷歌雲項目,並啓用了,我想使用的API,自然語言的API。
- 創建憑證和下載證書JSON文件,它保存爲apikey.JSON
- 在終端我已經跑這個命令:出口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 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'])
Output Traceback (most recent call last):
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/python3.6/os.py", line 669, in getitem raise KeyError(key) from None KeyError: 'GOOGLE_APPLICATION_CREDENTIALS'
我可以看到'print(os.environ ['GOOGLE_APPLICATION_CREDENTIALS'])''。 – stovfl
代碼運行 '輸入OS 打印(os.environ [' GOOGLE_APPLICATION_CREDENTIALS '])' 輸出 回溯(最近通話最後一個): 文件 「/Users/YELI1/Downloads/googlecloud/sentimentanalysis/simple.py」第2行,在 print(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)無 KeyError:'GOOGLE_APPLICATION_CREDENTIALS' –
Liam
我不知道如何格式化這件事情,看起來很亂,但看起來像是說沒有這樣的關鍵'GOOGLE_APPLICATION_CREDENTIALS'。 @stovfl – Liam