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

How to add multiple body params with fileupload in FastAPI?

我有一个使用 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

当我尝试发送输入参数时,邮递员出现错误,请看下图,

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

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

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

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

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.

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

from fastapi import FastAPI, File, UploadFile, <b>Form</b>

app = FastAPI()


@app.post("/predict")
async def predict(
        <b>industry: str = Form(...),
        file: UploadFile = File(...)</b>
):
    # rest of your logic
    return {"industry": industry, "filename": file.filename}