解决Adobe PDF Extract API的ValueError: client_id must not be blank报错
解决Adobe PDF Extract API的
client_id must not be blank报错(环境变量读取失败问题) 问题背景
- 已完成Adobe PDF Extract API(Python)入门配置,虚拟环境
venv_smed所需依赖安装完成,源码无语法错误 - 执行
python extract.py时触发报错:ValueError: client_id must not be blank - 调整凭证获取代码格式后问题仍存在,排查确认无法正确读取环境变量
PDF_SERVICES_CLIENT_ID和PDF_SERVICES_CLIENT_SECRET pdfservices-api-credentials.json配置内容无误
有效解决代码
优先采用直接从本地配置文件加载凭证的方式,绕过环境变量读取问题,完整代码示例:
from adobe.pdfservices.operation.auth.service_principal_credentials import ServicePrincipalCredentials from adobe.pdfservices.operation.pdfops.extract_pdf_operation import ExtractPDFOperation from adobe.pdfservices.operation.io.file_ref import FileRef from adobe.pdfservices.operation.exception.exceptions import ServiceApiException, ServiceUsageException, SdkException # 直接从本地json配置文件加载凭证 credentials = ServicePrincipalCredentials.from_file("./pdfservices-api-credentials.json") # 初始化ExtractPDF操作 extract_pdf_operation = ExtractPDFOperation.create_new() # 设置输入PDF文件 input_file = FileRef.create_from_local_file("./input/sample.pdf") extract_pdf_operation.set_input(input_file) # 执行操作并保存结果 try: result = extract_pdf_operation.execute(credentials) result.save_as("./output/extract_result.json") print("PDF内容提取成功,结果已保存至output/extract_result.json") except (ServiceApiException, ServiceUsageException, SdkException) as e: print(f"操作执行失败: {e}")
若仍需使用环境变量,需确保环境变量已正确设置(终端临时设置或写入系统环境变量),并使用可靠的读取方式:
import os from adobe.pdfservices.operation.auth.service_principal_credentials import ServicePrincipalCredentials # 读取环境变量(终端设置示例:export PDF_SERVICES_CLIENT_ID="你的ID" && export PDF_SERVICES_CLIENT_SECRET="你的密钥") client_id = os.environ.get("PDF_SERVICES_CLIENT_ID") client_secret = os.environ.get("PDF_SERVICES_CLIENT_SECRET") if not client_id or not client_secret: raise ValueError("PDF_SERVICES_CLIENT_ID或PDF_SERVICES_CLIENT_SECRET环境变量未正确设置") credentials = ServicePrincipalCredentials(client_id, client_secret)
执行成功结果
执行命令:
python extract.py
输出示例:
2024-XX-XX XX:XX:XX,XXX INFO [adobe.pdfservices.operation.internal.util.logging_service] - Starting ExtractPDF operation 2024-XX-XX XX:XX:XX,XXX INFO [adobe.pdfservices.operation.internal.util.logging_service] - ExtractPDF operation completed successfully PDF内容提取成功,结果已保存至output/extract_result.json
内容的提问来源于stack exchange,提问作者Ramiro
相关产品推荐
相关产品推荐

