首页 > 解决方案 > 400 调用者的项目与父项目不匹配

问题描述

我有这段代码,它基本上使用云翻译 API 将文本从一种语言翻译成另一种语言。问题是这段代码总是抛出错误:“调用者的项目与父项目不匹配”。可能是什么问题呢?

translation_separator = "translated_text: "
language_separator = "detected_language_code: "
translate_client = translate.TranslationServiceClient()
# parent = translate_client.location_path(
        #     self.translate_project_id, self.translate_location
        # )
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = (
                os.getcwd()
                + "/translator_credentials.json"
        )

        # Text can also be a sequence of strings, in which case this method
        # will return a sequence of results for each text.
try:
            result = str(
                translate_client.translate_text(
                    request={
                        "contents": [text],
                        "target_language_code": self.target_language_code,
                        "parent": f'projects/{self.translate_project_id}/'
                                  f'locations/{self.translate_location}',
                        "model": self.translate_model
                    }
                )
            )
            print(result)
except Exception as e:
            print("error here>>>>>", e)

标签: python-3.xgoogle-cloud-platformgoogle-cloud-translate

解决方案


您的问题似乎与您在应用程序上使用的身份验证方法有关,请按照使用 translate API 的身份验证方法指南进行操作。如果您尝试使用代码传递凭据,则可以使用以下代码显式指向您的服务帐户文件

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')
        

此外,还有一个使用 Python 开始使用翻译 API 的代码实验室,这是使用 Python 运行翻译 API 的逐步入门指南。

如果问题仍然存在,您可以尝试为 Google 支持创建公共问题跟踪器


推荐阅读