FastAPI - Pydantic



Pydantic 是一個用於資料解析和驗證的 Python 庫。它使用 Python 新版本(3.6 及以上版本)的型別提示機制,並在執行時驗證型別。Pydantic 定義了BaseModel 類,作為建立使用者自定義模型的基類。

以下程式碼定義了一個基於 BaseModel 的 Student 類模型。

from typing import List
from pydantic import BaseModel
class Student(BaseModel):
   id: int
   name :str
   subjects: List[str] = []

Student 類的屬性用型別提示宣告。請注意,subjects 屬性是 typing 模組中定義的 List 型別,以及內建的列表型別。

我們可以使用具有匹配結構的字典來填充 Student 類的物件,如下所示:

>>> data = {
   'id': 1,
   'name': 'Ravikumar',
   'subjects': ["Eng", "Maths", "Sci"],
}
>>> s1=Student(**data)
>>> print (s1)
id=1 name='Ravikumar' subjects=['Eng', 'Maths', 'Sci']
>>> s1
Student(id=1, name='Ravikumar', subjects=['Eng', 'Maths', 'Sci'])
>>> s1.dict()
{'id': 1, 'name': 'Ravikumar', 'subjects': ['Eng', 'Maths', 'Sci']}

Pydantic 會盡可能自動進行資料型別轉換。例如,即使字典中的 id 鍵被賦予數字的字串表示(例如 '123'),它也會將其強制轉換為整數。但如果無法轉換,則會引發異常。

>>> data = {
   'id': [1,2],
   'name': 'Ravikumar',
   'subjects': ["Eng", "Maths", "Sci"],
}
>>> s1=Student(**data)
Traceback (most recent call last):
   File "<pyshell#13>", line 1, in <module>
      s1=Student(**data)
   File "pydantic\main.py", line 406, in
pydantic.main.BaseModel.__init__
pydantic.error_wrappers.ValidationError: 1 validation error
for Student
id
   value is not a valid integer (type=type_error.integer)

Pydantic 還包含一個 Field 類,用於宣告模型屬性的元資料和驗證規則。首先修改 Student 類,在 "name" 屬性上應用 Field 型別,如下所示:

from typing import List
from pydantic import BaseModel, Field
class Student(BaseModel):
   id: int
   name :str = Field(None, title="The description of the item", max_length=10)
   subjects: List[str] = []

按如下所示填充資料。這裡的 name 超過了規定的max_length。Pydantic 按預期丟擲ValidationError

>>> data = {
   'id': 1,
   'name': 'Ravikumar Sharma',
   'subjects': ["Eng", "Maths", "Sci"],
}
>>> s1=Student(**data)
Traceback (most recent call last):
   File "<pyshell#28>", line 1, in <module>
      s1=Student(**data)
   File "pydantic\main.py", line 406, in
pydantic.main.BaseModel.__init__
pydantic.error_wrappers.ValidationError: 1 validation error for Student
name
   ensure this value has at most 10 characters
   (type=value_error.any_str.max_length; limit_value=10)

Pydantic 模型可以與 ORM 模型(如SQLAlchemyPeewee)對映。

廣告
© . All rights reserved.