Google Cloud Document AI地域不匹配错误排查求助
解决Document AI调用时"Invalid location: 'eu' must match the server deployment 'us'"错误
问题描述
在Mac上使用Python 3.12调用GCP的Document AI PDF分割器时,即便确认处理器部署在eu区域,仍收到错误:Invalid location: 'eu' must match the server deployment 'us',本地VS Code和Colab运行均失败,尝试获取处理器列表时也触发相同错误。
问题根源
Document AI Python客户端默认连接**美国区域(us)**的服务端点,即便你在parent参数中指定了eu区域,客户端仍会向us区域的服务器发送请求,导致区域不匹配验证失败。
修复方案
方案1:初始化客户端时指定对应区域的API端点
修改客户端初始化代码,通过client_options参数明确指定eu区域的服务端点:
from google.oauth2 import service_account from google.cloud import documentai_v1 as documentai def list_document_ai_processors(project_id: str, location: str, service_account_file: str): credentials = service_account.Credentials.from_service_account_file(service_account_file) # 指定对应区域的API端点 client_options = {"api_endpoint": f"{location}-documentai.googleapis.com"} client = documentai.DocumentProcessorServiceClient( credentials=credentials, client_options=client_options ) parent = f"projects/{project_id}/locations/{location}" processors = client.list_processors(parent=parent) for processor in processors: print(f"Processor name: {processor.name}") print(f"Processor type: {processor.type_}") print(f"Display name: {processor.display_name}") print(f"State: {processor.state}\n") if __name__ == "__main__": project_id = "abmtest-429810" location = "eu" service_account_file = "/Users/XXXXXX/Desktop/DocAI/credentials.json" list_document_ai_processors(project_id, location, service_account_file)
方案2:设置环境变量指定默认区域
在运行代码前,通过环境变量告诉客户端使用eu区域:
- 终端临时设置:
export GOOGLE_CLOUD_LOCATION=eu - 或在代码开头添加:
import os os.environ["GOOGLE_CLOUD_LOCATION"] = "eu"
额外验证步骤
- 用gcloud命令确认处理器所在区域:
gcloud documentai processors list --location=eu --project=abmtest-429810 - 检查服务账号是否拥有
eu区域的Document AI权限,确保角色包含roles/documentai.admin或roles/documentai.user。
内容的提问来源于stack exchange,提问作者AlexCT
相关产品推荐
相关产品推荐

