简体   繁体   中英

Pydantic params validation with file upload

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?

You can't have them at the same time, since pydantic models validate json body but file uploads is sent in form-data .

So they can't be used together.

If you want to do it you should do a trick.

Please check out this link to know how to use pydantic models in form data.

You can't declare Body fields that you expect to receive as JSON, along with Form fields, as the request will have the body encoded using application/x-www-form-urlencoded , instead of application/json (or multipart/form-data , when files are included).

You can either use Form (...) fields, or Dependencies with Pydantic models, as described here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM