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

FastAPI:(7)路劲操作配置与JSON编码兼容

FastAPI:(7)路劲操作配置与JSON编码兼容

由于CSDN无法展示「渐构」的「#d,#e,#t,#c,#v,#a」标签,推荐访问我个人网站进行阅读:Hkini
「渐构展示」如下:在这里插入图片描述
在这里插入图片描述

#c 概述 文章内容

路径装饰器
HTTP方法
元数据
文档生成
GET/POST/PUT/DELETE
summary/description/tags
OpenAPI/Swagger
JSON编码
jsonable_encoder
模型转dict
时间转str

1.路劲操作装饰器配置

#d 路劲装饰器配置

路径操作装饰器配置是FastAPI中定义API接口路径请求方法(如GET、POST等) 之间映射关系的机制。开发者通过在「路劲操作函数」前添加装饰器(如@app.get()@app.post())来绑定URL路径与处理逻辑。这一配置不仅决定了请求的访问方式,还能绑定请求参数、文档信息、标签和响应模型等元数据,使得API行为更清晰、易管理、自动文档化

重要特征:

  • 特征1:明确的请求方法绑定:每个装饰器绑定一个或多个HTTP请求方法(GET/POST/PUT/DELETE等),体现操作语义。
  • 特征2:路径与逻辑强关联:装饰器配置将路径(URL)和业务逻辑函数精确绑定,提升可读性与维护性。
  • 特征3:可绑定元数据:路径操作装饰器可配合参数如summarydescriptiontagsresponse_model,增强文档生成和可维护性。
  • 特征4:自动文档集成:基于装饰器配置,FastAPI可自动生成OpenAPI规范与Swagger UI界面,无需额外书写文档。

#e 电商查询接口的配置

现象
电商平台需要为用户提供一个商品查询接口,使用GET方法访问/items/{item_id},函数逻辑为从数据库中查询商品信息。此接口使用路径参数item_id绑定,并带有描述元数据和响应模型。

特征对比:

  • 特征1(请求方法明确):使用GET方法,体现查询操作,符合REST语义;
  • 特征2(路径-逻辑绑定):路径/items/{item_id}与商品查询函数一一对应;
  • 特征3(元数据):附带summary、description,支持自动文档;
  • 特征4(自动文档):FastAPI自动将此接口展示在Swagger UI中,结构清晰。
from fastapi import FastAPI, UploadFile, File
from pydantic import BaseModelapp = FastAPI()# 正例1:商品查询接口
class Item(BaseModel):id: intname: strprice: float@app.get("/items/{item_id}", summary="获取商品信息", description="根据商品ID查询商品详细信息", response_model=Item)
def read_item(item_id: int):return {"id": item_id, "name": "Example Product", "price": 99.99}

#e status_code 状态码

status_code 用于定义_路径操作_响应中的 HTTP 状态码。可以直接传递 int 代码, 比如 404。如果记不住数字码的涵义,也可以用 status 的快捷常量。

from typing import Set, Unionfrom fastapi import FastAPI, status
from pydantic import BaseModelapp = FastAPI()class Item(BaseModel):name: strdescription: Union[str, None] = Noneprice: floattax: Union[float, None] = Nonetags: Set[str] = set()@app.post("/items/", response_model=Item, status_code=status.HTTP_201_CREATED)
async def create_item(item: Item):return item

#e tags参数

tags 参数的值是由 str 组成的 list (一般只有一个 str ),tags 用于为_路径操作_添加标签:

from typing import Set, Unionfrom fastapi import FastAPI
from pydantic import BaseModelapp = FastAPI()class Item(BaseModel):name: strdescription: Union[str, None] = Noneprice: floattax: Union[float, None] = Nonetags: Set[str] = set()@app.post("/items/", response_model=Item, tags=["items"])
async def create_item(item: Item):return item@app.get("/items/", tags=["items"])
async def read_items():return [{"name": "Foo", "price": 42}]@app.get("/users/", tags=["users"])
async def read_users():return [{"username": "johndoe"}]

#e 摘要与描述参数

from typing import Set, Union
from fastapi import FastAPI
from pydantic import BaseModelapp = FastAPI()class Item(BaseModel):name: strdescription: Union[str, None] = Noneprice: floattax: Union[float, None] = Nonetags: Set[str] = set()@app.post("/items/",response_model=Item,summary="Create an item",description="Create an item with all the information, name, description, price, tax and a set of unique tags",
)
async def create_item(item: Item):return item

#e 文档字符串

描述内容比较长且占用多行时,可以在函数的 docstring 中声明_路径操作_的描述,FastAPI 支持从文档字符串中读取描述内容。

文档字符串支持 Markdown,能正确解析和显示 Markdown 的内容,但要注意文档字符串的缩进

from typing import Set, Unionfrom fastapi import FastAPI
from pydantic import BaseModelapp = FastAPI()class Item(BaseModel):name: strdescription: Union[str, None] = Noneprice: floattax: Union[float, None] = Nonetags: Set[str] = set()@app.post("/items/", response_model=Item, summary="Create an item")
async def create_item(item: Item):"""Create an item with all the information:- **name**: each item must have a name- **description**: a long description- **price**: required- **tax**: if the item doesn't have tax, you can omit this- **tags**: a set of unique tag strings for this item"""return item

下图为 Markdown 文本在 API 文档中的显示效果:

#e 响应描述

response_description 参数用于定义响应的描述说明。

注意,response_description 只用于描述响应,description 一般则用于描述_路径操作_。

OpenAPI 规定每个_路径操作_都要有响应描述。如果没有定义响应描述,FastAPI 则自动生成内容为 “Successful response” 的响应描述。

from typing import Set, Unionfrom fastapi import FastAPI
from pydantic import BaseModelapp = FastAPI()class Item(BaseModel):name: strdescription: Union[str, None] = Noneprice: floattax: Union[float, None] = Nonetags: Set[str] = set()@app.post("/items/",response_model=Item,summary="Create an item",response_description="The created item",
)
async def create_item(item: Item):"""Create an item with all the information:- **name**: each item must have a name- **description**: a long description- **price**: required- **tax**: if the item doesn't have tax, you can omit this- **tags**: a set of unique tag strings for this item"""return item

#e 弃用路劲操作

deprecated 参数可以把_路径操作_标记为弃用,无需直接删除:

from fastapi import FastAPIapp = FastAPI()@app.get("/items/", tags=["items"])
async def read_items():return [{"name": "Foo", "price": 42}]@app.get("/users/", tags=["users"])
async def read_users():return [{"username": "johndoe"}]@app.get("/elements/", tags=["items"], deprecated=True)
async def read_elements():return [{"item_id": "Foo"}]

2.JSON编码兼容

#c 场景 编码兼容

在某些情况下,可能需要将数据类型(如Pydantic模型)转换为与JSON兼容的数据类型(如dictlist等)。比如,如果需要将其存储在数据库中。对于这种要求, FastAPI提供了jsonable_encoder()函数。

#e jsonable_encoder

假设有一个数据库名为fake_db,它只能接收与JSON兼容的数据。例如,它不接收datetime这类的对象,因为这些对象与JSON不兼容。因此,datetime对象必须将转换为包含ISO格式化的str类型对象。

同样,这个数据库也不会接收Pydantic模型(带有属性的对象),而只接收dict。对此可以使用jsonable_encoder。它接收一个对象,比如Pydantic模型,并会返回一个JSON兼容的版本。

from datetime import datetimefrom fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModelfake_db = {}class Item(BaseModel):title: strtimestamp: datetimedescription: str | None = Noneapp = FastAPI()@app.put("/items/{id}")
def update_item(id: str, item: Item):json_compatible_item_data = jsonable_encoder(item)fake_db[id] = json_compatible_item_data

这个例子中,它将Pydantic模型转换为dict,并将datetime转换为str。调用它的结果后就可以使用Python标准编码中的json.dumps()

这个操作不会返回一个包含JSON格式(作为字符串)数据的庞大的str。它将返回一个Python标准数据结构(例如dict),其值和子值都与JSON兼容。

相关文章:

  • 基于yolov8的苹果病虫害识别与预警系统【附源码】
  • 视频编码怎么选?H.264、H.265、VP9、AV1全解析
  • [Python] 使用 Python 提取 PPT 中不同 Shape 类型文本的技巧与性能权衡
  • Java八股文——MySQL「事务篇」
  • Spring Boot集成Kafka全攻略:从基础配置到高级实践
  • FlinkCDC-Hudi数据实时入湖原理篇
  • Java Wed应用---商城会员管理
  • 算法 学习 双指针 2025年6月16日11:36:24
  • 【SQLite3】渐进式锁机制
  • Vite的核心概念
  • 汽车总线安全研究系列—CAN(FD)渗透测试指南
  • RGB解码:神经网络如何通过花瓣与叶片的数字基因解锁分类奥秘
  • spring如何解决循环依赖问题
  • 三星内置远程控制怎样用?三星手机如何远程控制其他品牌的手机?
  • Linux-split命令(文件分割)使用方法
  • origin曲线美化教程
  • FastAPI:(6)错误处理
  • 自然语言处理相关基本概念
  • 【Docker基础】Docker核心概念:命名空间(Namespace)之IPC详解
  • 【一手实测】字节豆包 1.6 + Trae + 火山 MCP + FaaS:AI云原生 Agent 开发部署全流程体验!
  • 做网站html和asp/百度推广有效果吗
  • 电子商务网站建设/seo收录查询工具
  • 网盟推广是什么/广丰网站seo
  • 做英德红茶的网站/企业网络组建方案
  • 公司网站制作费用多少/seo公司优化
  • 龙之向导外贸网址/seo快速建站