为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 FastAPI 中使用 fileupload 添加多个正文参数?

如何在 FastAPI 中使用 fileupload 添加多个正文参数?

侃侃尔雅 2023-10-11 16:17:16
我有一个使用 FastAPI 部署的机器学习模型,但问题是我需要该模型采用二体参数app = FastAPI()class Inputs(BaseModel):    industry: str = None    file: UploadFile = File(...)@app.post("/predict")async def predict(inputs: Inputs):    # params    industry = inputs.industry    file = inputs.file    ### some code ###    return predicted value当我尝试发送输入参数时,我在邮递员中收到错误,请参见下图,
查看完整描述

1 回答

?
慕侠2389804

TA贡献1719条经验 获得超6个赞


如果您正在接收 JSON 数据,application/json请使用普通的 Pydantic 模型。

这将是与 API 通信的最常见方式。

如果您收到原始文件(例如图片或 PDF 文件)并将其存储在服务器中,则使用UploadFile,它将作为表单数据 ( multipart/form-data) 发送。

如果您需要接收某种类型的非 JSON 结构化内容,但希望以某种方式进行验证(例如 Excel 文件),您仍然需要使用上传它并在代码中执行所有必要的验证UploadFile。您可以在自己的代码中使用 Pydantic 进行验证,但在这种情况下 FastAPI 无法为您执行此操作。

因此,就您而言,路由器应该是,

from fastapi import FastAPI, File, UploadFile, Form


app = FastAPI()



@app.post("/predict")

async def predict(

        industry: str = Form(...),

        file: UploadFile = File(...)

):

    # rest of your logic

    return {"industry": industry, "filename": file.filename}


查看完整回答
反对 回复 2023-10-11
  • 1 回答
  • 0 关注
  • 114 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信