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

通过Memsource API导入TMX文件遇400错误,求解决方法

如何解决Memsource API上传TMX文件返回400错误的问题

我尝试用API请求把TMX(XML格式)文件上传到Memsource服务器,但代码一直返回400错误(Bad Request),求解决办法。

补充信息:

  • 使用Python 3.11
  • 参考Memsource API文档的Translation Memory\Import TMX章节

原代码:

import codecs
import requests

f_name = r'D:\my_folder\myTranslationMemory.tmx'
token = 'ApiToken ABCDEFG123'
transMemoryUid = 'myTransMemoryUid'
url = 'https://cloud.memsource.com/web/api2/v1/transMemories/' + str(transMemoryUid) + '/import'

headers = {'Authorization': token,
           'Content-Disposition': f'attachment; filename="{f_name}"',
           "Content-Type": 'application/octet-stream; charset=utf-8'
           }

with codecs.open(f_name, "rb", encoding='utf-8') as tmx_fileobject:
    file_dict = {f_name: tmx_fileobject}
    response = requests.post(url, headers=headers, files=file_dict)
    print(response)

错误信息:

return (<Response [400]>
)

问题排查与修正

1. 文件参数键名错误

Memsource的Import TMX接口要求上传文件的参数键必须是file,而非你使用的本地文件路径f_name——服务器无法识别自定义的字段名,这是导致400错误的核心原因。

2. 文件打开方式错误

用codecs.open以二进制模式(rb)打开时指定encoding='utf-8'是矛盾的,二进制模式不需要编码参数。直接用内置open函数以rb模式打开即可。

3. 冗余请求头设置

  • Content-Disposition无需手动设置,requests库在使用files参数时会自动生成正确的头部信息。
  • Content-Type也不需要手动指定为application/octet-stream,可以在files参数中指定TMX文件对应的MIME类型application/xml,让请求更规范。

修正后的代码

import requests

f_name = r'D:\my_folder\myTranslationMemory.tmx'
token = 'ApiToken ABCDEFG123'
transMemoryUid = 'myTransMemoryUid'
# 用f-string简化URL拼接
url = f'https://cloud.memsource.com/web/api2/v1/transMemories/{transMemoryUid}/import'

headers = {'Authorization': token}

# 以二进制模式打开文件,无需编码参数
with open(f_name, 'rb') as tmx_fileobject:
    # 固定参数键为'file',指定正确的MIME类型
    files = {'file': (f_name, tmx_fileobject, 'application/xml')}
    response = requests.post(url, headers=headers, files=files)
    print(response.status_code)
    # 打印响应内容,便于排查权限、文件格式等其他问题
    print(response.text)

额外建议

  • 打印response.text查看服务器返回的具体错误描述,能帮你定位权限不足、TMX文件格式无效等更多细节问题。
  • 确认API令牌拥有操作目标翻译记忆库的权限,且transMemoryUid完全正确。

内容的提问来源于stack exchange,提问作者Владислав

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 07:06:13