博兴专业做网站,建设网站有哪些术语,黑马程序员培训在哪里,网站建设教程 mysql参考#xff1a;模式的额外信息 - 例子 - FastAPI
在FastAPI中#xff0c;Body和Field是两个常用的注解#xff0c;它们用于定义请求体中的数据或路径参数、查询参数等的处理方式。这两个注解都来自于Pydantic库#xff0c;用于数据验证和解析#xff0c;但它们的应用场景…参考模式的额外信息 - 例子 - FastAPI
在FastAPI中Body和Field是两个常用的注解它们用于定义请求体中的数据或路径参数、查询参数等的处理方式。这两个注解都来自于Pydantic库用于数据验证和解析但它们的应用场景有所不同。
Body
Body是一个注解用来指示FastAPI从HTTP请求的主体即请求体中读取数据并根据提供的模型或类型进行解析和验证。当期望客户端通过POST、PUT等方法发送JSON对象或其他格式的数据时就会用到Body。它常与Pydantic的模型类一起使用来定义请求体的结构。
Field
Field是Pydantic模型类中用于定义模型字段属性的一个方法。它允许你为模型的字段添加额外的元数据比如默认值、标题、描述等。Field通常不直接用于FastAPI的路由定义中而是用于定义Pydantic模型的结构这些模型随后可能作为Body、查询参数、路径参数等使用。
举例
from typing import List, Set, Union, Optional
import uvicorn
from fastapi import FastAPI, Body
from pydantic import BaseModel, HttpUrl, Field
from typing_extensions import Annotated# 初始化FastAPI应用程序
app FastAPI()# 定义Item模型表示商品项的属性
class Item(BaseModel):name: strdescription: Union[str, None] Noneprice: floattax: Union[float, None] None# 定义Item_1模型与Item类似但提供了更详细的字段示例
class Item_1(BaseModel):name: str Field(examples[Foo])description: Union[str, None] Field(defaultNone, examples[A very nice Item])price: float Field(examples[35.4])tax: Union[float, None] Field(defaultNone, examples[3.2])# 更新物品信息的API端点
# 接收一个item_id参数和一个Item实例作为请求体
app.put(/items/{item_id})
async def update_item(item_id: int, item: Item):results {item_id: item_id, item: item}return results# 另一个更新物品信息的API端点使用了更详细的Annotated注解来指定请求体的期望格式
app.put(/items_1/{item_id})
async def update_item(item_id: int,item: Annotated[Item_1,Body(examples[{name: Foo,description: A very nice Item,price: 35.4,tax: 3.2,}],),],
):results {item_id: item_id, item: item}return results# 主函数用于启动FastAPI应用程序
# 注释中提供了两种运行模式线上模式和调试模式
# 主函数用于启动FastAPI应用程序
if __name__ __main__:## 线上模式# uvicorn.run(abr_server:app, host0.0.0.0, port 1218)## debug 模式uvicorn.run(test4:app, host0.0.0.0, port1218, reloadTrue, )