You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Python SDK以编程方式设置Google翻译API项目?

解决Google翻译API编程指定项目的问题

核心问题原因

你遇到的报错是因为服务账号默认关联其所在项目,而你需要将API调用的配额和权限指向另一个已启用翻译API的项目。仅通过client_options设置quota_project_id不足以覆盖服务账号的默认项目关联,必须在凭据层面显式指定配额项目。

针对不同版本客户端的解决方案

1. 旧版v2客户端(translate_v2)

直接创建带配额项目的凭据对象,传入客户端构造函数:

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

def translate_text(target: str, text: str):
    # 加载服务账号密钥并指定配额项目
    credentials = service_account.Credentials.from_service_account_file(
        "path/to/your/service-account-key.json",
        quota_project_id="my-proj-id"
    )
    # 初始化客户端时传入配置好的凭据
    translate_client = translate.Client(credentials=credentials)
    
    # 执行翻译逻辑
    result = translate_client.translate(text, target_language=target)
    print(f"原文: {result['input']}")
    print(f"译文: {result['translatedText']}")
    return result

如果是在GCP托管环境(如Cloud Run、GKE)中使用默认凭据,无需加载密钥文件:

from google.auth import default
from google.cloud import translate_v2 as translate

def translate_text(target: str, text: str):
    credentials, _ = default()
    # 为默认凭据附加配额项目
    credentials = credentials.with_quota_project("my-proj-id")
    translate_client = translate.Client(credentials=credentials)
    
    # 后续翻译逻辑...

2. 新版v3客户端(TranslationServiceClient)

同样需要在凭据层面指定配额项目,同时确保请求中的parent参数指向目标项目:

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

def translate_text(text: str = "hello", project_id: str = "my-proj"):
    # 创建带配额项目的凭据
    credentials = service_account.Credentials.from_service_account_file(
        "path/to/your/service-account-key.json",
        quota_project_id=project_id
    )
    # 初始化客户端,同时传入凭据和client_options
    client = translate.TranslationServiceClient(
        credentials=credentials,
        client_options={"quota_project_id": project_id}
    )
    
    location = "global"
    parent = f"projects/{project_id}/locations/{location}"
    request = {
        "parent": parent,
        "contents": [text],
        "mime_type": "text/plain",
        "source_language_code": "en-US",
        "target_language_code": "fr",
    }
    
    response = client.translate_text(**request)
    for translation in response.translations:
        print(f"翻译文本: {translation.translated_text}")
    return response

关键注意事项

  • 确保目标项目(my-proj-id)已启用Cloud Translation API
  • 确保你的服务账号在目标项目中拥有至少Cloud Translation API User权限
  • 不要依赖服务账号的默认项目关联,必须显式指定配额项目

内容的提问来源于stack exchange,提问作者red888

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 18:35:25