首页 > 其他分享 >FastAPI系列:模型用法

FastAPI系列:模型用法

时间:2024-02-28 18:00:04浏览次数:157  
标签:None name FastAPI 模型 用法 item str BaseModel 数据模型

模型基本用法

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={},输出数据中仅排除指定的字段

标签:None,name,FastAPI,模型,用法,item,str,BaseModel,数据模型
From: https://www.cnblogs.com/weiweivip666/p/18041245

相关文章

  • FastAPI系列:上传文件File和UploadFile
    上传文件#file仅适用于小文件@app.post("/files/")asyncdefcreate_file(file:bytes|None=File(default=None)):ifnotfile:return{"message":"Nofilesent"}else:return{"file_size":len(file)}......
  • FastAPI系列:路径参数额外校验Path
    路径参数额外校验PathfromfastapiimportPathapp=FastAPI()@app.get('/items/{item_id}')asyncdefread_items(item_id:str=Path(default=None,max_length=3,min_length=1,title='theidofitemtoget')):"""def......
  • FastAPI系列:查询字符串参数
    单个查询字符串@app.get('/index/{username}')defindex(username:str,id:int):#id为查询字符串?id=5return{"message":"success","username":username,"id":id}可选的查询字符串参数@app.get('/items/{item_id}......
  • 随笔记录篇——原来高手都在numpy手写机器学习/深度学习模型
    一个无名小辈最近要开始在博客园留下自己学习的印迹了。最近在从0开始了解一些机器学习模型。原来,在数学建模的时候,调用一些库,用过一些机器学习的算法,自以为会了点机器学习的内容知识,实则是,实质什么也不懂,只会用封装好的库来实现。高手都是从0开始现推机器学习算法,numpy实现。......
  • FastAPI系列:APIRouter实例的路由注册
    APIRouter实例的路由注册API端点路由注册大致分为3种:1.基于app实例对象提供的装饰器或函数进行注册2.基于FastAPI提供的APIRouter类的实例对象提供的装饰器或函数进行注册3.通过直接实例化APIRoute对象且添加的方式进行注册路由注册方式基于APIRouter的实例对象实现路由注册......
  • FastAPI系列:mount应用挂载
    mount应用挂载1.创建主app应用对象实例,注册所属的路由信息fromfastapiimportFastAPIfromfastapi.responseimportJSONResponseapp=FastAPI(title='主应用',description='主应用描述',version='v1.0.0')@app.get('/index',summary='首页')......
  • FastAPI系列:全局routes参数的使用
    全局routes参数的使用fromfastapiimportFastAPI,Requestfromfastapi.responseimportJSONResponsefromfastapi.routingimportAPIRouteasyncdeffastapi_index():returnJSONResponse({'index':'fastapi_index'})asyncdeffastapi_about()......
  • FastAPI系列:路由之节点元数据参数说明
    节点元数据参数说明#拿app.get()方法的参数来说明,其他的差不多类似defget(self,path:str,*,response_model:Optional[Type[Any]]=None,status_code:Optional[int]=None,tags:Optional[List[Union[str,Enum]]]......
  • FastAPI系列:路由之APIRouter参数介绍
    APIRouter参数介绍classAPIRouter(routing.Router):def__init__(self,*,prefix:str="",#表示当前路由分组的url前缀tags:Optional[List[Union[str,Enum]]]=None,#表示当前路由分组在可交互文档中所属的分组标签列表。一......
  • FastAPI系列 :安装启动及简单示例
    安装pip3installfastapipip3installuvicorn[standard]#是一个ASGI异步服务器网关接口服务器框架pip3installpython-multipart#处理表单参数的#完整安装pipinstallfastapi[all]启动程序#命令行启动uvicornmain:app--reload--host0.0.0.0--port8888......