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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45501082/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:05:07  来源:igfitidea点击:

Set GOOGLE_APPLICATION_CREDENTIALS in Python project to use Google API

pythongoogle-api

提问by Liam

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

我是一名编程初学者,我正在尝试学习如何将 google API 与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.
  1. 创建了谷歌云项目,并启用了,我想使用的API, Natural Language API
  2. 创建凭据并下载凭据 JSON 文件,将其保存为 apikey.JSON
  3. 在终端中,我运行了这个命令: export GOOGLE_APPLICATION_CREDENTIALS=apikey.JSON,没有弹出错误。

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'

回答by Marius

If you're working on a jupyter notebook and want to set GOOGLE_APPLICATION_CREDENTIALS environment variable in Python code :

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

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

回答by sdikby

I know that this post was answered but the following is a cleaner way to specify the GOOGLE_APPLICATION_CREDENTIALSvariable.

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

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

回答by rishi jain

There is 1 more simpler way of making it working by explicity mentioning Credentials and passing them to client as shown below.

通过明确提及凭据并将它们传递给客户端,有一种更简单的方法可以使其工作,如下所示。

    import os
    from google.oauth2 import service_account

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

回答by seanbrhn3

Another way to test this is to go into the terminal and type:

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

# Linux/Unix
set | grep GOOGLE_APPLICATION_CREDENTIALS 

or

或者

# Windows:
set | Select-String -Pattern GOOGLE_APPLICATION_CREDENTIALS 

This will show you the environment variable and the path where it is located. If this returns nothing then you have not set the variable or you may have the wrong path set

这将向您显示环境变量及其所在的路径。如果这没有返回任何内容,那么您没有设置变量,或者您可能设置了错误的路径