使用GCP api密钥时,python env出现问题

时间:2018-09-05 04:49:13

标签: python google-translate

我想使用google translation api,但是遇到一些问题。

我的环境是Linux ubuntu 18和Atom空闲的python

我曾被gcloud用来设置配置并获得了auth登录名,auth登录令牌。

export GOOGLE_APPLICATION_CREDENTIALS=//api_key.json
gcloud init
gcloud auth application-default login
gcloud auth application-default print-access-token

所以我可以使用curl并获得一些测试数据

curl -X POST      -H "Authorization: Bearer "$(gcloud auth application-default print-access-token)      -H "Content-Type: application/json; charset=utf-8"      --data 
"{
  'q': 'Hello world',
  'q': 'My name is Jeff',
  'target': 'de'
}" "https://translation.googleapis.com/language/translate/v2"
{
  "data": {
    "translations": [
      {
        "translatedText": "Hallo Welt",
        "detectedSourceLanguage": "en"
      },
      {
        "translatedText": "Mein Name ist Jeff",
        "detectedSourceLanguage": "en"
      }
    ]
  }
}

当我在Atom空闲状态下运行测试代码时,我的项目号错误。 这是我过去的项目。 即使我在bash python中运行测试代码,情况也是一样

我不知道出什么问题了,我只是在python env中猜出了一些问题。

引发错误

raise exceptions.from_http_response(response)
google.api_core.exceptions.Forbidden: 403 POST 
https://translation.googleapis.com/language/translate/v2: Cloud Translation    
API has not been used in project [wrong number] before or it is disabled.   
Enable it by visiting
https://console.developers.google.com/apis/api/translate.googleapis.com
/overview?project=[wrong number] then retry. If you enabled this API 
recently, wait a few minutes for the action to propagate to our systems and 
retry.

1 个答案:

答案 0 :(得分:0)

通常由于多种原因(例如文件丢失,凭据路径无效,环境变量分配不正确)而未正确地对应用程序进行认证时,会引发此错误消息。由于客户端库需要从环境变量或客户端对象中提取凭证数据,因此需要确保您指向正确的身份验证文件。请记住,使用CURL命令时可能不会发生此问题,因为您是直接传递access-token的。

基于此,我建议您确认您正在使用当前项目的JSON文件凭据,并遵循Obtaining and providing service account credentials manually指南以明确指定服务帐户文件直接进入您的代码;这样,您将能够永久设置它,并验证您是否正确传递了服务凭据。此外,您可以查看Using Client Libraries指南,其中包含将Translation API与Python结合使用所需的分步过程。

在代码示例中将路径传递到服务帐户密钥:

def explicit():
from google.cloud import storage

# Explicitly use service account credentials by specifying the private key
# file.
storage_client = storage.Client.from_service_account_json('service_account.json')

# Make an authenticated API request
buckets = list(storage_client.list_buckets())
print(buckets)