加入自訂驗證器
Mode360 Solutions 是這個留言審核系統背後的組織,你被指派要為所有員工建立一個驗證服務。系統必須能驗證輸入的詳細資料(username、email 和 age),以便只有使用公司正式電子郵件地址的員工才能註冊。
你需要定義一個 Pydantic 的 User 模型,並在 email 上使用 @field_validator 裝飾器,檢查輸入的電子郵件是否以 @mode360.com 結尾。
這些驗證器能提升安全性並促進系統整合。
本練習屬於課程
使用 FastAPI 將 AI 佈署到生產環境
練習說明
- 加上 Pydantic 裝飾器,為
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