在Python项目中设置GOOGLE_应用程序_凭据以使用GOOGLE API

在Python项目中设置GOOGLE_应用程序_凭据以使用GOOGLE API,python,google-api,Python,Google Api,我是一名编程初学者,我正在努力学习如何将GoogleAPI与Python结合使用 我有: 在谷歌云上创建了一个项目,并启用了我想要使用的API,自然语言API 创建凭证并下载凭证JSON文件,将其保存为apikey.JSON 在终端中,我运行了以下命令:exportGOOGLE\u APPLICATION\u CREDENTIALS=apikey.JSON,没有弹出错误 但是,即使我为此运行了最简单的代码,也会出现错误,表明找不到凭证变量 我不知道现在该怎么办。请帮忙 这是我的代码: from

我是一名编程初学者,我正在努力学习如何将GoogleAPI与
Python
结合使用

我有:

  • 在谷歌云上创建了一个项目,并启用了我想要使用的API,
    自然语言API
  • 创建凭证并下载凭证JSON文件,将其保存为
    apikey.JSON
  • 在终端中,我运行了以下命令:export
    GOOGLE\u APPLICATION\u 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.
    
    我有错误:

    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.
    

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

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

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

    # Linux/Unix
    set | grep 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和
    谷歌云存储==1.35.0

    我可以看到
    打印(os.environ['google\u应用程序凭据])
    。代码运行“导入操作系统打印(os.environ['google\u应用程序凭据])”输出回溯(最后一次调用):文件“/Users/YELI1/Downloads/googlecloud/thousanalysis/simple.py”,第2行,在打印(os.environ['GOOGLE_应用程序_凭证'])文件/usr/local/cillar/python3/3.6.2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/os.py中,第669行,在从None-keyrerror获得的getitem raise-KeyError(key)中:“GOOGLE_应用程序_凭证”我不知道如何正确格式化这个东西,看起来一团糟,但它似乎在说,没有“谷歌应用程序凭据”这样的密钥@stovflYes,keyrerror表示请求的环境变量未在Python脚本的环境中设置。您的问题和添加操作系统版本,Python版本。您必须从执行
    导出…
    的同一终端启动Python脚本。您可以通过选择此链接上的项目来生成凭据和Json文件:@marius谢谢您,即使谷歌文档也不清晰谢谢!现在也工作了。@Mim我认为“不清楚”是一个欠维度的陈述!你们将如何在生产中满足这一需求?是的,没错!这应该也在Google Translate API快速启动中,而不是一些环境变量,谢谢@sdikby!