【问题标题】:Mixing Request Forms and Files: pass additional parameters in a post request when file is transmitted混合请求表单和文件:传输文件时在发布请求中传递附加参数
【发布时间】:2021-06-23 16:11:36
【问题描述】:

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

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(...)
):

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

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 识别为字符串?从文档中并不清楚将表单与文件混合的发布请求应该是什么样子。

【问题讨论】:

    标签: python python-requests fastapi


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2013-03-15
      • 1970-01-01
      • 2013-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多