后端开发
FastAPI
Pydantic
数据验证
当客户通过API提交一个订单时,你只需将输入数据传递给这个 Order
模型。如果数据无效,Pydantic 将自动抛出一个详细的错误,指出哪个字段无效以及为什么。
order_data = {
"product_id": 1,
"quantity": 50,
"payment_method": "credit_card"
}
try:
order = Order(**order_data)
except ValidationError as e:
print(e.json())
title: "如何用Pydantic简化Python数据验证?"
image: "https://picx.zhimg.com/v2-a69634fe9f79aa6d6e10e4e92bf13562_720w.jpg?source=172ae18b"
description: "背景介绍Pydantic 是一个Python库,用于数据验证和设置管理。它最初是为了弥补Python标准库在数据验证方面的不足而设计的。与其他数据验证库(如 Marshmallow、Cerberus)相比,Pydantic 强调类型提示和类型安全,…"
url: "https://zhuanlan.zhihu.com/p/652791602"
ORM mode
默认是lazy loading模式
That means, for example, that they don't fetch the data for relationships from the database unless you try to access the attribute that would contain that data.
For example, accessing the attribute items
:
current_user.items
would make SQLAlchemy go to the items
table and get the items for this user, but not before.
Without orm_mode
, if you returned a SQLAlchemy model from your path operation, it wouldn't include the relationship data.
Even if you declared those relationships in your Pydantic models.
在 Python 3.9 以前,标准的类型注解方式是使用来自
typing
模块的List
、Dict
、Set
等来定义复杂的类型,例如List[str]
或Dict[str, int]
。从 Python 3.9 开始,你可以直接使用内置的 list、dict、set 等作为泛型类型,如list[str]
和dict[str, int]
。