FastAPI 基础学习(三) Pydantic 做类型强制检查

作者:麦克煎蛋   出处:https://www.cnblogs.com/mazhiyong/ 转载请保留这段声明,谢谢!

 

FastAPI 基于 PydanticPydantic 主要用来做类型强制检查。参数赋值,不符合类型要求就会抛出异常。

对于 API 服务,支持类型检查非常有用,会让服务更加健壮,也会加快开发速度,因为开发者再也不用自己写一行一行的做类型检查。

我们用纯粹的,经典的Python来定义数据,用Pydantic来校验数据。

 

官方文档地址:https://pydantic-docs.helpmanual.io/

 

一、安装

pip install pydantic

二、使用

from pydantic import ValidationError

from datetime import datetime
from typing import List
from pydantic import BaseModel

class User(BaseModel):
    id: int
    name = 'jack guo'
    signup_timestamp: datetime = None
    friends: List[int] = []

观察到:

  • id 要求必须为 int
  • name 要求必须为 str, 且有默认值
  • signup_timestamp 要求为 datetime, 默认值为 None
  • friends 要求为 List,元素类型要求 int, 默认值为 []

使用 User 类:

try:
    User(signup_timestamp='not datetime', friends=[1, 2, 3, 'not number'])
except ValidationError as e:
    print(e.json())

id 没有默认值,按照预期会报缺失的异常

signup_timestamp 被赋为非 datetime 类型值,按照预期会报异常

friends 索引为 3 的元素被赋值为 str,按照预期也会报异常

执行代码,验证是否符合预期。

[
  {
    "loc": [
      "id"
    ],
    "msg": "field required",
    "type": "value_error.missing"
  },
  {
    "loc": [
      "signup_timestamp"
    ],
    "msg": "invalid datetime format",
    "type": "value_error.datetime"
  },
  {
    "loc": [
      "friends",
      3
    ],
    "msg": "value is not a valid integer",
    "type": "type_error.integer"
  }
]

 

参考文章:https://cloud.tencent.com/developer/article/1593589

更复杂的使用和例子可以参考官方文档。

 

posted on 2020-04-30 15:00  麦克煎蛋  阅读(6184)  评论(2编辑  收藏  举报