Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

MrChoke
MrChoke

Posted on

     

การใช้ Pydantic Model กับ Form Data ใน FastAPI

ปกติถ้าหากจำนวน Fields ใน Form มีไม่มากก็ไม่มีปัญหาเราสามารถเขียนแบบปกติได้ เช่น

@app.post("/abc",response_model=bool)defabc(id:int=Form(...),name:str=Form(default=None),status:str=Form(default="single")):returnTrue
Enter fullscreen modeExit fullscreen mode

แต่ถ้า Fields มีเยอะ ๆ สัก 10 Fields ขึ้นไป Code ก็จะเริ่มดูยากยาวมาก การใช้ Pydantic model เข้ามาช่วยก็จะจัดการง่ายขึ้น ปกติเราใช้ Pydantic model ใน Body แบบ JSON กันอยู่แล้วแต่สำหรับ Form Data จะมีลูกเล่นนิดหนึ่ง ค้นหาใน internet ไปเจอวิธีที่คิดว่าง่ายที่สุดละเลยบันทึกไว้สักหน่อย

ต้นฉบับที่ผมนำมาใช้

stackoverflow

ตัวอย่าง model.py

fromtypingimportOptionalfromfastapiimportFormfrompydanticimportBaseModeldefform_body(cls):cls.__signature__=cls.__signature__.replace(parameters=[arg.replace(default=Form(default=arg.default)ifarg.defaultisnotinspect._emptyelseForm(...))forargincls.__signature__.parameters.values()])returncls@form_bodyclassProfile(BaseModel):passport_no:Optional[str]hn:Optional[str]patient_guid:Optional[str]prefix:str="นาย"first_name:strlast_name:strprefix_eng:str="Mr"first_name_eng:Optional[str]middle_name_eng:Optional[str]last_name_eng:Optional[str]gender:int=1birth_date:Optional[str]mobile_phone:Optional[str]installed_line_connect:Optional[str]address:Optional[str]moo:Optional[str]road:Optional[str]chw_code:Optional[str]amp_code:Optional[str]tmb_code:Optional[str]address_full_thai:Optional[str]address_full_english:Optional[str]nationality:Optional[str]
Enter fullscreen modeExit fullscreen mode

ในส่วนของ Form มันจะมีหลัก ๆ อยู่สามแบบคือ

  • บังคับ
  • มีค่า Default
  • มีก็ได้ไม่มีก็ได้

ผมเลยปรับในตัว Decorators เพิ่มเติมให้มันปรับตาม Model ที่เรากำหนดไว้

arg.replace(default=Form(default=arg.default)ifarg.defaultisnotinspect._emptyelseForm(...))
Enter fullscreen modeExit fullscreen mode

ตัวอย่าง Router

frommodelimportProfilefromfastapiimportDepends,FastAPI,File,UploadFileapp=FastAPI()@app.post("/abc",response_model=bool)defabc(profile:Profile=Depends(Profile),photo:UploadFile=File(...)):returnTrue
Enter fullscreen modeExit fullscreen mode

ตอน Render ก็จะได้ประมาณนี้

Swagger

Swagger input with default

ลองเอาไปประยุกต์ใช้กันดูครับ

Top comments(4)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
veer66 profile image
Vee Satayamas
I'm a Thai-Lao-English-speaking software engineer who has worked on data pipelines, web/app back-end, and multilingual text processing.
  • Location
    SE Asia
  • Work
    software engineer
  • Joined

คือเอาไว้ทำอะไรนะครับ ?

CollapseExpand
 
mrchoke profile image
MrChoke
Just For Fun!!
  • Location
    Thailand
  • Work
    Dev at Thailand
  • Joined

แค่เอาไว้ลดการเขียน arguments ใน router function ให้สั้นลงครับ ถ้าไม่ใช้ model ก็ต้องยัดทั้งหมดลงใน arguments และอีกอย่างก็สามารถเอา model ไป reused ได้ด้วยครับ

CollapseExpand
 
veer66 profile image
Vee Satayamas
I'm a Thai-Lao-English-speaking software engineer who has worked on data pipelines, web/app back-end, and multilingual text processing.
  • Location
    SE Asia
  • Work
    software engineer
  • Joined

Python นี่รับ request เข้ามาตัวแปรเดียวไม่ได้ใช่เปล่าครับ เลยต้องทำแบบนี้ ?

Thread Thread
 
mrchoke profile image
MrChoke
Just For Fun!!
  • Location
    Thailand
  • Work
    Dev at Thailand
  • Joined

ถ้าเป็น json ส่งมาเป็น object แล้วใช้ model รับแบบนี้ได้เเลย แต่ form data มันมาแบบ field หรืออาจจะมีแล้วหว่ายังไม่ได้อ่าน doc ใหม่ 😂 ครับ

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Just For Fun!!
  • Location
    Thailand
  • Work
    Dev at Thailand
  • Joined

More fromMrChoke

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp