การเพิ่ม validator แบบกำหนดเอง
Mode360 Solutions คือองค์กรที่อยู่เบื้องหลังระบบกลั่นกรองความคิดเห็น และคุณได้รับมอบหมายให้สร้างบริการตรวจสอบข้อมูลสำหรับพนักงานทุกคน ระบบต้องสามารถตรวจสอบข้อมูลนำเข้า (username, email และ age) โดยอนุญาตให้เฉพาะพนักงานที่ใช้อีเมลทางการเท่านั้นสามารถลงทะเบียนได้
ต้องกำหนดโมเดล User ของ Pydantic โดยใช้ decorator @field_validator บนฟิลด์ email เพื่อตรวจสอบว่าอีเมลที่ป้อนลงท้ายด้วย @mode360.com หรือไม่
validator เหล่านี้ช่วยเสริมความปลอดภัยและการผสานรวมระบบ
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การ Deploy AI สู่ Production ด้วย FastAPI
คำแนะนำการฝึกหัด
- เพิ่ม decorator ของ Pydantic เพื่อสร้าง validator แบบกำหนดเองบนฟิลด์
email - ใช้เมธอด
endswithของสตริงเพื่อตรวจสอบว่าอีเมลลงท้ายด้วยโดเมน@mode360.comหรือไม่
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
from pydantic import BaseModel, field_validator, Field
class User(BaseModel):
username: str = Field(..., min_length=5, max_length=20)
email: str
age: int
# Add the Pydantic decorator to validate
____('email')
def email_must_be_example_domain(cls, user_email):
# Use the endswith method to validate the email ends with @mode360.com
if not user_email.endswith("____"):
raise ValueError('Email must be from the mode360.com domain')
return user_email