使用请求发布文件时 422

422 when posting file with requests

所以我整天都在努力解决这个问题,但一直没有取得任何进展。我有这个 curl 命令,它有效:

curl -X POST -H "x-hermes-key: <KEY>" -H "Accept: application/json"  --form file='@example_files/ex1.pdf' <URL> -kv 

当我尝试 运行 它在 python 中的等效请求时,我收到 422 错误:

header = {
            "Accept": "application/json",
            "X-Hermes-Key": <KEY>
        }

f = {'file': open("example_files/ex1.pdf", "rb")}
r_create = requests.post(url=<URL>, headers=header, files=f)

谁能帮我看看我哪里出错了?

以下应该匹配 curl 命令和 POST 与 content-type=multipart/form-data.

您可以在 'file' 值的元组中显式设置文件名、content_type 和 headers。

headers = {
            "Accept": "application/json",
            "X-Hermes-Key": <KEY>
        }

url = <URL>

files = [('file', ('ex1.pdf', open('example_files/ex1.pdf', 'rb'),
                     'application/octet-stream'))]
r = requests.post(url=url, headers=headers, files=files)
print(r.status_code)