如何在 FastAPI 中使用文件上传添加多个正文参数? [英] How to add multiple body params with fileupload in FastAPI?

查看:100
本文介绍了如何在 FastAPI 中使用文件上传添加多个正文参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 FastAPI 部署的机器学习模型,但问题是我需要该模型采用双体参数

I have a machine learning model deployed using FastAPI, but the issue is I need the model to take two-body parameters

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

当我尝试发送输入参数时,在 postman 中出现错误,请参见下图,

When I tried to send the input parameters I am getting an error in postman, please see the pic below,

推荐答案

来自 FastAPI 讨论 thread--(#657)

From the FastAPI discussion thread--(#657)

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

if you are receiving JSON data, with application/json, use normal Pydantic models.

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

This would be the most common way to communicate with an API.

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

If you are receiving a raw file, e.g. a picture or PDF file to store it in the server, then use UploadFile, it will be sent as form data (multipart/form-data).

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

If you need to receive some type of structured content that is not JSON but you want to validate in some way, for example, an Excel file, you would still have to upload it using UploadFile and do all the necessary validations in your code. You could use Pydantic in your own code for your validations, but there's no way for FastAPI to do it for you in that case.

所以,在你的情况下,路由器应该是,

So, in your case, the router should be as,

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}

这篇关于如何在 FastAPI 中使用文件上传添加多个正文参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆