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

网站自动识别移动终端今日热点新闻头条

网站自动识别移动终端,今日热点新闻头条,西安制作app的公司,网站建设服务项目包括哪些FastAPI:(7)路劲操作配置与JSON编码兼容 由于CSDN无法展示「渐构」的「#d,#e,#t,#c,#v,#a」标签,推荐访问我个人网站进行阅读:Hkini 「渐构展示」如下: #c 概述 文章内…

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兼容。

http://www.dtcms.com/wzjs/221731.html

相关文章:

  • 外贸推广网站邮箱收费有没有专门做营销的公司
  • 发现了一个做字素的网站app优化推广
  • 网站改版模版博客优化网站seo怎么写
  • 定制网站开发食道里感觉有东西堵咸阳seo
  • 太原自助建站营销推广技巧
  • 自己做网站系统首选平台海口seo计费
  • 上饶市建设厅网站浙江网站建设平台
  • wordpress 套件seo关键词怎么填
  • 潍坊网站设计公司百度搜索软件
  • 服装商城的网站策划书网站收录提交入口大全
  • 公司网站开发人员的的工资多少钱百度资讯指数
  • 工信部网站备案信息怎么查询系统360优化大师官网
  • 购物网站的开发直通车官网
  • 深圳做网站最好的公司官网设计公司
  • 兼职做猎头的网站win7优化大师官方免费下载
  • 美丽说网站模板怎么创建网站快捷方式到桌面
  • 资讯网站 怎么做google chrome download
  • 三网合一 做网站现场直播的视频
  • 物流网站查询西宁网站seo
  • 网站推广优化建设武汉竞价托管公司
  • 淄博做网站推广哪家好下载优化大师
  • 交友网站初期怎么做怎么自己做一个网站平台
  • 爱奇艺会员做任务送十天网站品牌网站建设方案
  • 温州免费网站建站模板怎么推广自己的产品
  • 正邦品牌设计公司官网优化方案
  • 店面效果图制作软件快速排名seo软件
  • 哪些公司网站做的好百度24小时人工客服
  • 购物网站建设报价表体验营销案例
  • 重庆可作为推广的网站太原网站推广排名
  • 做旅游网站的目的发帖子最好的几个网站