from fastapi import File, Form, UploadFile
from pydantic import BaseModel


class TestFormDataCommand(BaseModel):
    name: str
    image: UploadFile
    nullable_image: UploadFile | None
    images: list[UploadFile]

    @classmethod
    def as_form(
        cls,
        name: str = Form(),
        image: UploadFile = File(),
        nullable_image: UploadFile | None = None,
        images: list[UploadFile] = [],  # File(default=[])
    ):
    	# Do Validation!
        return cls(
            name=name,
            image=image,
            nullable_image=nullable_image,
            images=images,
        )


@router.post("/test")
async def test(command: TestFormDataCommand = Depends(TestFormDataCommand.as_form)):
    print(f"name: {command.name}")
    print(f"image: {command.image}")
    print(f"nullable_image: {command.nullable_image}")
    if command.nullable_image:
        print(f"desc: {command.nullable_image.__dict__}")
    print(f"images: {command.images}")
    for i in command.images:
        print(f"list i: {i.__dict__}")

 

이미지 파일에 대한 속성입니다.

# from FastAPI import UploadFile

"file": {
    "filename": "test.jpg",
    "file": {
        "_file": {},
        "_max_size": 1048576,
        "_rolled": false,
        "_TemporaryFileArgs": {
            "mode": "w+b",
            "buffering": -1,
            "suffix": null,
            "prefix": null,
            "encoding": null,
            "newline": null,
            "dir": null,
            "errors": null
        }
    },
    "size": 7487,
    "headers": {
        "content-disposition": "form-data; name=\"file\"; filename=\"test.jpg\"",
        "content-type": "image/jpeg"
    }
}

 

+ Recent posts