隐藏页面特效

FastAPI系列:模型用法

模型基本用法

from pydantic import BaseModel class Item(BaseModel): # 通过继承BaseModel name: str price: float is_offer: Union[bool, None] = None

常用的模型属性和方法

dict() #将数据模型的字段和值封装成字典 json() #将数据模型的字段和值封装成json格式字符串 copy() #生成数据模型实例的副本 parse_obj() #将python字典数据解析为数据模型实例 parse_raw() #将字符串解析为数据模型实例 parse_file() #传入文件路径,并将路径所对应的文件解析为数据模型实例 from_orm() #将任何自定义类的实例转换成数据模型对象 schema() #将数据模型转换成json模式数据 schema_json() #将返回schema()生成的字符串 construct() #类方法,创建数据模型实例时不进行验证 __fields_set__ #创建数据模型实例的初始化字段列表 __fields__ # 罗列数据模型的全部字段的字典 __config__ # 显示数据模型的配置类

模型转换成字典

class Item(BaseModel): name: str price: float is_offer: Union[bool, None] = None @app.put("/items/{item_id}") def update_item(item_id: int, item: Item): """ dict()相关参数 include: Optional[Union['AbstractSetIntStr', 'MappingIntStrAny']] = None, # 要包含在返回的字典中的字段。你可以传递一个集合或映射对象,指定要包含的字段 exclude: Optional[Union['AbstractSetIntStr', 'MappingIntStrAny']] = None, # 要从返回的字典中排除的字段。你可以传递一个集合或映射对象,指定要排除的字段。 by_alias: bool = False, # 是否应用字段别名作为返回字典中的键。如果设置为 True,将使用字段别名作为键。 skip_defaults: Optional[bool] = None, # 是否应从返回的字典中排除等于其默认值(无论是否设置)的字段 exclude_unset: bool = False, # 创建模型时未显式设置的字段是否应从返回的字典中排除 exclude_defaults: bool = False, # 是否应从返回的字典中排除等于其默认值(无论是否设置)的字段 exclude_none: bool = False, #是否应从返回的字典中排除等于 None 的字段 """ item_dict = item.dict() # 将模型转换为字典 return {"item_id": item_id, **item_dict}

嵌套模型

from typing import List from pydantic import BaseModel class Blackboard(BaseModel): size = 4000 color: str class Table(BaseModel): position: str class ClassRoom(BaseModel): blackboard: Blackboard tables: List[Table] m = ClassRoom( blackboard={'color': 'green'}, tables=[{'position': '第一排左1'},{'position': '第一排左2'}] )

模型字段校验

1.默认值,为字段提供一个默认值,在创建数据模型实例的时候,字段会使用这个默认值,将默认值设置为(...)用来标记该字段是必填字段 2.别名alias 3.详细信息description 4.数值比较函数gt/ge/lt/le 5.正则表达式 from pydantic import BaseModel,Field class Blackboard(BaseModel): size: 4000 color: str=Field(...,alias='颜色',gt=1,description='黑板的颜色,可选green和black')

响应模型response_model

class Item(BaseModel): name: str description: str | None = None price: float tax: float | None = None tags: list[str] = [] @app.post("/items/", response_model=Item) async def create_item(item: Item) -> Any: return item @app.get("/items/", response_model=List[Item]) async def read_items() -> Any: return [ {"name": "Portal Gun", "price": 42.0}, {"name": "Plumbus", "price": 32.0}, ]

从orm模型实例创建Pydantic模型

class ItemResponse(BaseModel): name: str description: str | None = None # 配置类,开启orm模式 class Config: orm_mode = True @app.get("/items/{id}", response_model=ItemResponse) def query_items(id: int): # 查询数据库,返回的是一个对象 blog = db.query(Blog).filter(Blog.id == id).first() # 将模型映射成pydantic模型,并返回给前端 return blog

orm_mode的其他用法

class Person(BaseModel): pid: int name: str # 配置类,开启orm模式 class Config: orm_mode = True from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class PersonORM(Base): __tablename__ = 'person' pid = Column(Integer,primary_key=True) name = Column(String(24),unique=True) # from_orm()从orm模型对象构造模型实例 p_obj = PersonORM(pid=1,name='jack') Person.from_orm(p_obj) # dict()将basemodel的实例解析为orm类型的实例 person = Person(pid=2,name='nick') p_orm = PersonORM(**person.dict())

响应模型排除具有默认值的字段response_model_exclude_unset

class Item(BaseModel): name: str description: Union[str, None] = None price: float tax: float = 10.5 tags: List[str] = [] # 比作你数据库查询出来的数据 items = { "foo": {"name": "Foo", "price": 50.2}, "bar": {"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2}, "baz": {"name": "Baz", "description": None, "price": 50.2, "tax": 10.5, "tags": []}, } @app.get("/items/{item_id}", response_model=Item, response_model_exclude_unset=True) async def read_item(item_id: str): return items[item_id] #比如我返回的是第一条数据,映射到Item中,响应排除具有默认值的字段

其他参数

response_model_exclude_defaults=True,忽略与默认值相同的字段 response_model_exclude_none=True,忽略值为None的字段 response_model_include={},输出数据中仅包含指定的字段 response_model_exclude={},输出数据中仅排除指定的字段

__EOF__

本文作者404 Not Found
本文链接https://www.cnblogs.com/weiweivip666/p/18041245.html
关于博主:可能又在睡觉
版权声明:转载请注明出处
声援博主:如果看到我睡觉请喊我去学习
posted @   我在路上回头看  阅读(290)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2022-02-28 方法指针或非指针类型接收器
点击右上角即可分享
微信分享提示