fastAPIでAPIの構築を行なっています。
UploadFileとpydanticについて教えていただきたいことがあります。
以下のようにprogram_itemとfileを受け取ってprogram_itemを作りたいと考えているのですが、以下のコードで行うと422が返ってきます。
python
1@router.post("/", response_model=Result, operation_id="creatProgramItem", tags=['programItems'], status_code=HTTP_201_CREATED) 2def create_program_item( 3 program_item: ProgramItemCreateSchema, 4 file: UploadFile = Form(None), 5 db: Session = Depends(get_db)): 6 7 program_items.create_program_item(db=db, program_item=program_item, upload_file=file, settings=settings) 8 return Result(result=True) 9 10 11class ProgramItemCreateSchema(BaseSchema): 12 title: str 13 training_type: int 14 training_tool: Optional[int] 15 guidance_methods: List[GuidanceMethodSchema] 16 17 18class GuidanceMethodSchema(BaseModel): 19 description: str 20
調べた結果、FastAPIはUploadFileとJSON本体を一緒に処理できないということはわかりました。
github:[QUESTION] Use UploadFile in Pydantic model
github:Using UploadFile and Pydantic model in one request
この場合は、ProgramItemCreateSchemaを分解して
def create_program_item( title: str = Form(…), training_type: int = Form(…), training_tool: Optional[int] = Form(None), guidance_methods: List[GuidanceMethodSchema] = Form(…), file: UploadFile = Form(None), db: Session = Depends(get_db)):
とするしかないのでしょうか?
可能であればprogram_item
という1つの引数にまとめたいと思ったのですが、もしそのようにできる方法があれば教えていただけませんか?
よろしくお願いいたします。
環境は以下の通りです
fastapi 0.70.0 pydantic 1.8.2 SQLAlchemy 1.4.27 Python 3.9.7
あなたの回答
tips
プレビュー