【问题标题】:How to add multiple body params with fileupload in FastAPI?如何在 FastAPI 中通过文件上传添加多个正文参数?
【发布时间】:2021-01-21 18:03:59
【问题描述】:

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

当我尝试发送输入参数时,我在邮递员中收到错误,请参见下图,

【问题讨论】:

    标签: python python-3.x postman fastapi uvicorn


    【解决方案1】:

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

    如果您通过application/json 接收 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}
    

    【讨论】:

    • 现在,当我通过邮递员传递输入时,我收到行业错误,它返回否,请检查屏幕截图,在预测函数中我写了一个 if 条件,如果行业是 None 返回没有
    • @user_12 更新了答案
    • ... 代表什么
    • 它是Ellipsis。在 FastAPI 中,我们可以使用 ... 值 @user_12 将参数/参数设置为 required
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-19
    • 1970-01-01
    • 1970-01-01
    • 2018-11-01
    • 1970-01-01
    • 2018-08-28
    • 2021-08-16
    相关资源
    最近更新 更多