Fastapi 简明教程

FastAPI - Pydantic

Pydantic 是一个用于数据解析和验证的 Python 库。它使用更新版本 Python(3.6 及更高版本)的类型提示机制,并在运行时验证类型。Pydantic 定义 BaseModel 类。其充当创建用户定义模型的基类。

以下代码将 Student 类定义为基于 BaseModel 的模型。

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

Student 类的属性使用类型提示声明。请注意 subjects 属性是 typing 模块定义的 List 类型和内置 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] = []

按如下所示填充数据。此处的名称超出了 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