Azure Document Translator返回202但未翻译,Python请求报错求助
Azure批量翻译服务问题排查
问题背景
Blob存储层级:
- storage account
- container1
- translation-input
- sampleTranslation.docx
- translation-output
- translation-input
- container1
需求:将sampleTranslation.docx翻译后存入translation-output目录。
错误现象
- Postman调用API返回202状态码,但无响应体,翻译未执行。
- Python调用时抛出错误:
The JSON value could not be converted to Microsoft.MT.Batch.Contracts.Api.V1.StartTranslationDetails. Path: $ | LineNumber: 0 | BytePositionInLine: 590.
问题原因及修复方案
1. 请求URL格式错误
代码中构造的URL存在多余的双斜杠,会导致API路由解析异常:
constructed_url = endpoint + "/translator//text//batch//v1.0//batches"
修复为单斜杠路径:
constructed_url = endpoint + "/translator/text/batch/v1.0/batches"
2. JSON序列化重复问题
requests.post的json参数接受Python字典对象,无需提前用json.dumps序列化。代码中先将字典转为字符串再传入json参数,会导致双重序列化,生成格式错误的JSON,触发转换失败错误。
修复方式二选一:
- 直接传入Python字典,去掉
json.dumps:
body = { "inputs": [ { "source": { "sourceUrl": sourceUrl, }, "targets": [ { "targetUrl": targetUrl, "language": "fr" } ] } ] } request = requests.post( constructed_url, headers=headers, json=body, verify=False )
- 保留
json.dumps,改用data参数传递序列化后的字符串:
request = requests.post( constructed_url, headers=headers, data=body, verify=False )
3. Blob访问权限问题(Postman无执行的核心原因)
Postman返回202仅表示API接收请求成功,但翻译未执行,大概率是sourceUrl和targetUrl未生成有效的SAS签名URL。Azure翻译服务需要读写Blob的权限,必须为输入输出Blob生成带读写权限的SAS令牌,确保服务能访问存储资源。
修复后的完整Python代码示例
import requests import json import uuid from your_module import CONSTANTS # 替换为实际导入路径 subscription_key = CONSTANTS["TRANSLATOR_TEXT_SUBSCRIPTION_KEY"] region = CONSTANTS["TRANSLATOR_TEXT_REGION"] endpoint = CONSTANTS["TRANSLATOR_DOC_ENDPOINT"] # 修正URL路径 constructed_url = endpoint + "/translator/text/batch/v1.0/batches" headers = { "Ocp-Apim-Subscription-Key": subscription_key, "Ocp-Apim-Subscription-Region": region, "Content-type": "application/json", "X-ClientTraceId": str(uuid.uuid4()), } # 直接使用字典,无需提前序列化 body = { "inputs": [ { "source": { "sourceUrl": sourceUrl, # 确保是带SAS的Blob URL }, "targets": [ { "targetUrl": targetUrl, # 确保是带SAS的Blob URL "language": "fr" } ] } ] } request = requests.post( constructed_url, headers=headers, json=body, verify=False ) # 处理响应:202状态码无响应体,无需调用json() if request.status_code == 202: print("请求已接受,翻译任务已提交") # 可通过API查询任务状态 else: try: response = request.json() print("Request URL:\t", constructed_url) print("Response:\t") print( json.dumps( response, sort_keys=True, indent=4, ensure_ascii=False, separators=(",", ": "), ) ) except: print(f"请求失败,状态码:{request.status_code},响应内容:{request.text}")
内容的提问来源于stack exchange,提问作者Roy
相关产品推荐
相关产品推荐

