如何使用 Python 请求将多个文件发送到 FastAPI 服务器?

How to send multiple files with Python requests to FastAPI server?

我的 FastAPI 服务器中有以下端点:

@app.post("/submit")
async def submit(file1: List[UploadFile] = File(...), file2: List[UploadFile] = File(...), file3: List[UploadFile] = File(...)):
    # do something
    return 'hello'

如果我使用 Swagger UI,它会按预期工作。但是,我不知道如何使用 Python requests 模块向此端点发送 POST 请求。这是我尝试过的:

import requests

headers = {
    'accept': 'application/json',
    'Content-Type': 'multipart/form-data',
}

files = [
    ('file1', open('file1.zip', 'rb')), 
    ('file2', open('file2.txt', 'rb')),
    ('file3', open('file3.rar', 'rb')),
]

response = requests.post('http://localhost:8000/submit', headers=headers, files=files)

print(response.text)

但是我得到一个错误:

{"detail":"There was an error parsing the body"}

您应该将每个 file 定义为端点中的单独参数,例如 file1: UploadFile = File(...)file2: UploadFile = File(...) 等(不使用 List),或者,最好定义一个List的文件使用files: List[UploadFile] = File(...),如下图(下面可以用来return所有上传文件的文件名)

@app.post("/submit")
async def submitUPP(files: List[UploadFile] = File(...)):
    # do something
    return {"Uploaded Files:": [file.filename for file in files]}

在客户端,您应该使用您在端点中为每个文件提供的相同 key(即上述情况下的 files)发送文件列表。

files = [
    ('files', open('file1.zip', 'rb')), 
    ('files', open('file2.txt', 'rb')),
    ('files', open('file3.rar', 'rb')),
]

您可能还想看看 this and this 答案。

重要

除上述之外,不应在 headers 中设置 Content-Type 使用文件时为 multipart/form-data,而是让 Python 请求设置 Content-Type,因为除了 multipart/form-dataContent-Type 必须 包括 boundary string used to separate each body part in the multipart payload). Please have a look at the answers here and here。以您的方式设置 Content-Type 是您遇到错误的原因,即 {'detail': 'There was an error parsing the body'}。因此,您应该避免在 headers.

中设置 Content-Type