[Python] Pydantic params validation with file upload [duplicate]

Discussão em 'Python' iniciado por Stack, Março 1, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying upload user data with file. I wanna do something like this, validate user data and attach file

    class User(BaseModel):
    user: str
    name: str

    @router.post("/upload")
    async def create_upload_file(data: User, file: UploadFile = File(...)):
    print(data)
    return {"filename": file.filename}


    but it doesn't work Error: Unprocessable Entity Response body:

    {
    "detail": [
    {
    "loc": [
    "body",
    "data"
    ],
    "msg": "value is not a valid dict",
    "type": "type_error.dict"
    }
    ]
    }


    But if i do separate ulr all work:

    class User(BaseModel):
    user: str
    name: str

    @router.post("/d")
    async def create(file: UploadFile = File(...)):
    return {"filename": file.filename}

    @router.post("/")
    def main(user: User):
    return user


    How to combine all together?

    Continue reading...

Compartilhe esta Página