Set GOOGLE_APPLICATION_CREDENTIALS in Python project to use Google API

I am a programming beginner and thing I'm trying to learn how to use google API with Python.

I have:

  1. created a project on Google Cloud and enabled the API that I want to use, Natural Language API.
  2. created a credential and downloaded the credential JSON file, saved it as apikey.JSON
  3. In the Terminal I have ran this command: export GOOGLE_APPLICATION_CREDENTIALS=apikey.JSON, no error popped.

However, even when I ran the simplest of codes for this, I have errors which says the credential variable is not found.

I am not sure what to do now. Please kindly help.

This is my code:

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)

And I have errors:

> 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.

The value is not in the environment

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'
173665 次浏览

如果你正在处理一个 jupyter 笔记本,并且想要用 Python 代码设置 GOOGLE _ application _ CREDENTIALS 环境变量:

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

另一种测试方法是进入终端并输入:

# Linux/Unix
set | grep GOOGLE_APPLICATION_CREDENTIALS

或者

# Windows:
set | Select-String -Pattern GOOGLE_APPLICATION_CREDENTIALS

这会告诉你环境变量和它所在的路径。如果没有返回任何值,那么您没有设置变量,或者您可能设置了错误的路径

我知道这篇文章得到了回复,但是下面是一个更简洁的指定 GOOGLE_APPLICATION_CREDENTIALS变量的方法。

client = language.LanguageServiceClient.from_service_account_json("/path/to/file.json")

还有一种更简单的方法可以让它工作,那就是明确地提到凭证,并将它们传递给客户机,如下所示。

import os
from google.oauth2 import service_account


credentials = service_account.Credentials.from_service_account_file("your-json-path-with-filename.json")
client = language.LanguageServiceClient(credentials=credentials)

如果您在内存中有凭证(例如,环境变量) ,并且您不希望特别为其创建文件:

from google.cloud import storage
from google.oauth2 import service_account


gcp_json_credentials_dict = json.loads(gcp_credentials_string)
credentials = service_account.Credentials.from_service_account_info(gcp_json_credentials_dict)
client = storage.Client(project=gcp_json_credentials_dict['project_id'], credentials=credentials)

使用 python3.7和 google-cloud-storage==1.35.0

当您的代码在本地开发环境中运行时,最好的选择是使用与您的 Google 帐户相关联的凭据。

  1. Install and initialize the gcloud CLI, if you haven't already.

  2. 创建证书文件:

    gcloud auth application-default login
    

将显示一个登录屏幕。登录后,您的凭据将存储在 ADC 使用的本地凭据文件中。然后应该允许您自动确定凭据。