相当于 cURL 返回错误的请求

requests equivalent to cURL returning error

我正在尝试使用 DeepL API。在文档中,他们谈到了这样的 cURL 命令:

curl https://api.deepl.com/v2/document \
    -F "file=@mydoc.docx" \
    -F "auth_key=<your-api-key>" \
    -F "target_lang=DE"

我像这样转换为 requests

import requests

files = {
    'file': ('mydoc.docx', open('mydoc.docx', 'rb')),
    'auth_key': (None, '<your-api-key>'),
    'target_lang': (None, 'DE'),
}

response = requests.post('https://api.deepl.com/v2/document', files=files)

奇怪的是,cURL 命令确实可以从命令行运行,但我无法使 Python 代码运行。服务器不断返回以下数据:

{'message': 'Invalid file data.'}

文档明确指出

Because the request includes a file upload, it must be an HTTP POST request containing multipart/form-data.

但据我所知,以上是正确的做法。我做错了什么?

DeepL 支持团队回复了我,解决方案是为文件指定数据类型(在我的例子中 text/plain)。所以请求应该是这样的:

import requests

files = {
    'file': ('mydoc.docx', open('mydoc.docx', 'rb'), 'text/plain'),
    'auth_key': (None, '<your-api-key>'),
    'target_lang': (None, 'DE')
}

response = requests.post('https://api.deepl.com/v2/document', files=files)