当前位置: 首页 > news >正文

FastAPI入门:响应模型

响应模型

在任意的路径操作中使用 response_model 参数来声明用于响应的模型

FastAPI 将使用此 response_model 来:

  • 将输出数据限制在该模型定义内
  • 将输出数据转换为其声明的类型。
  • 校验数据。
  • 在 OpenAPI 的路径操作中为响应添加一个 JSON Schema。
  • 并在自动生成文档系统中使用。

返回与输入相同的模型

from typing import Anyfrom fastapi import FastAPI
from pydantic import BaseModelapp = FastAPI()class Item(BaseModel):name: strdescription: str | None = Noneprice: floattax: float | None = Nonetags: 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 [Item(name="Item 1", description="A sample item", price=10.0, tax=1.0, tags=["tag1", "tag2"]),Item(name="Item 2", description="Another sample item", price=20.0, tax=2.0, tags=["tag3"]),]

添加输出模型

from typing import Anyfrom fastapi import FastAPI
from pydantic import BaseModel, EmailStrapp = FastAPI()class UserInput(BaseModel):username: strpassword: stremail: EmailStr fullname: str | None = Noneclass UserOutput(BaseModel):username: stremail: EmailStrfullname: str | None = None@app.post("/user/", response_model=UserOutput)
async def create_user(user: UserInput) -> Any:return user

将 response_model 声明为了不包含密码的 UserOut 模型

response_model_exclude_unset

设置response_model_exclude_unset=True响应中将不会包含那些默认值,而是仅有实际设置的值。

from typing import List, Unionfrom fastapi import FastAPI
from pydantic import BaseModelapp = FastAPI()class Item(BaseModel):name: strdescription: Union[str, None] = Noneprice: floattax: float = 10.5tags: 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]

访问http://127.0.0.1:8000/items/foo,将只显示
在这里插入图片描述

response_model_include 和 response_model_exclude

使用路径操作装饰器的 response_model_include 和 response_model_exclude 参数。

它们接收一个由属性名称 str 组成的 set 来包含(忽略其他的)或者排除(包含其他的)这些属性。

from typing import List, Unionfrom fastapi import FastAPI
from pydantic import BaseModelapp = FastAPI()class Item(BaseModel):name: strdescription: Union[str, None] = Noneprice: floattax: float = 10.5tags: 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}/name",response_model=Item,response_model_include={"name", "description"},)
async def read_item(item_id: str):return items[item_id]@app.get("/items/{item_id}/public", response_model=Item,response_model_exclude={"tax"})
async def read_item(item_id: str):return items[item_id]

访问:http://127.0.0.1:8000/items/foo/public
在这里插入图片描述
访问http://127.0.0.1:8000/items/foo/name:
在这里插入图片描述

http://www.dtcms.com/a/311958.html

相关文章:

  • 如何分析Linux内存性能问题
  • Windows字体simsum.ttf的安装与Python路径设置指南
  • junit中@InjectMocks作用详解
  • wgd v1.1.2 安装与使用-生信工具056
  • Java 字符串常量池 +反射,枚举和lambda表达式
  • 【数据结构】栈的顺序存储(整型栈、字符栈)
  • Postman四种请求教程
  • unsloth - LLM超级轻量级微调框架
  • ollama 多实例部署
  • 语音识别数据集
  • 【ROS2】ROS2节点Node机制与常用命令行
  • Autosar Nm-网管报文PNC停发后无法休眠问题排查
  • 决策树算法:三大核心流程解析
  • Agents-SDK智能体开发[4]之集成MCP入门
  • Qt 槽函数被执行多次,并且使用Qt::UniqueConnection无效【已解决】
  • Python编程基础与实践:Python文件处理入门
  • 智能手表:MPU6050和水平仪,动态表情包
  • 第14届蓝桥杯Python青少组中/高级组选拔赛(STEMA)2023年1月15日真题
  • Qemu-NUC980(二):时钟clock代码添加
  • 驾驶场景玩手机识别:陌讯行为特征融合算法误检率↓76% 实战解析
  • 如何修复非json数据
  • 兰空图床部署教程
  • 从C++0基础到C++入门(第十五节:switch语句)
  • 工具包:位图格式一键生成可无限放大的矢量图SVG/EPS及CAD文件DXF
  • 我的世界模组开发教程——物品item(1)
  • 建筑施工场景安全帽识别误报率↓79%:陌讯动态融合算法实战解析
  • 深入 Vue v-model
  • SpringBoot启动项目详解
  • MC0351区间询问和
  • MybatisPlus-自动生成代码