不良请求错误400 Google API用于翻译Python



调用API并获得错误需要从英语转换为法国,但是获得此错误,因此我使用了此代码,但是它无法正常工作

代码:

from __future__ import print_function
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
from googleapiclient.discovery import build

def main():
  service = build('translate', 'v2',
            developerKey='AIzaSyDRRpR3GS1F1_jKNNM9HCNd2wJQyPG3oN0')
  print(service.translations().list(
      source='en',
      target='fr',
     q="flower"
    ).execute())
if __name__ == '__main__':
  main()

错误

Traceback (most recent call last):
  File "trail.py", line 19, in <module>
    main()
  File "trail.py", line 15, in main
    q="flower"
  File "build/bdist.linux-i686/egg/oauth2client/_helpers.py", line 133, in positional_wrapper
  File "build/bdist.linux-i686/egg/googleapiclient/http.py", line 840, in execute
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://www.googleapis.com/language/translate/v2?q=flower&source=en&alt=json&target=fr&key=AIzaSyDRRpR3GS1F1_jKNNM9HCNd2wJQyPG3oN0 returned "Bad Request">

使用新的Google Cloud客户端库,并使用服务帐户凭据JSON授权您的API并调用export GOOGLE_APPLICATION_CREDENTIALS=your_service.json而不是使用API密钥。您也可以通过调用gcloud auth application-default login使用默认的应用程序凭据。

在Google Cloud翻译Python样品中,这也应该帮助您更快地开始。

请注意,翻译API需要计费,如翻译QuickStart指令中所述,因此准备为您的项目设置该设置。

最新更新