python-3.x - 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)
解决方案
您的问题似乎与您在应用程序上使用的身份验证方法有关,请按照使用 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 支持创建公共问题跟踪器
推荐阅读
- jquery - 为什么我想在 django 项目的 js 中加载 html 文件时出现错误?
- python - ctypes 范围内的字符串缓冲区
- python - 通过二维数组递归
- python - 将具有相同文件名的多个文件从服务器复制到本地并使用 python paramiko
- python-3.x - “in”运算符如何影响时间复杂度?
- javascript - Vue:创建可以渲染子组件的父组件
- java - 比较通过套接字 UTF8 传递的字符串
- php - 如何在控制器 laravel 中提供 CSRF
- html - 如何在 Bootstrap 4 列中使图像的高度响应,以便相邻列中的嵌入视频不受影响?
- google-apps-script - Google Sheet 使用 Importxml 错误无法获取 url