混合请求表单和文件:传输文件时在 post 请求中传递附加参数

Mixing Request Forms and Files: pass additional parameters in a post request when file is transmitted

在 FAST API 文档中,列出了以下示例作为参考,如何在传输文件时在 post 请求中传递附加参数。

https://fastapi.tiangolo.com/tutorial/request-forms-and-files/

from fastapi import FastAPI, File, Form, UploadFile

app = FastAPI()


@app.post("/files/")
async def create_file(
    file: bytes = File(...), token: str = Form(...)
):

当我发出如下 post 请求时,我得到:

requests.post(URL, files={'file': hdf5_file, 'token': 'teststring'})

422 Unprocessable Entity
{'detail': [{'loc': ['body', 'model_str'],
   'msg': 'str type expected',
   'type': 'type_error.str'}]}

为什么token不被识别为字符串?从文档中不清楚混合表单和文件的 post 请求应该是什么样子。

对于requests use参数files上传文件,data用于发送额外的表单数据。在这种情况下,所有内容都将作为内容类型 multipart/form-data:

的不同部分发送
requests.post(URL, files={'file': hdf5_file}, data={'token': 'teststring'})