如何解决Google Cloud API的“如果未提供http,则凭据必须存在”的问题?

问题描述

我是编程的新手,并且一直在尝试使用Google Translate API。我遇到了这个问题,并试图找到无济于事的解决方案。我已经创建了一个Google服务帐户和密钥。我在Jupyter Notebook内的Mac上。

错误

~/opt/anaconda3/lib/python3.7/site-packages/google/cloud/client.py in __init__(self,credentials,_http,client_options)
    141             raise ValueError(_GOOGLE_AUTH_CREDENTIALS_HELP)
    142 
--> 143         scopes = client_options.scopes or self.ScopE
    144 
    145         # if no http is provided,credentials must exist

AttributeError: 'ClientOptions' object has no attribute 'scopes'

我的代码

import os
from google.cloud import translate_v2

os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="cloud_key.json"
translate_client = translate.Client()

解决方法

我尝试了使用最新更新的库的示例,它对我有用。

但是,如果未正确处理推断出的凭据,则可以pass explicit credentials to the client

from google.cloud import translate_v2 as translate
from google.oauth2 import service_account

credentials = service_account.Credentials.from_service_account_file('/path/to/key.json')
scoped_credentials = credentials.with_scopes(['https://www.googleapis.com/auth/cloud-platform'])

translate_client = translate.Client(credentials=scoped_credentials)

有关在here中创建显式凭据的更多详细信息(此答案几乎是该文档上的说明的副本)。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...