FastAPI快速入门2 Pydantic错误处理

news/2024/10/6 1:36:41

2.1 Pydantic简介

Pydantic使用python类型注解进行数据验证和配置管理。这是一款能让您更精确地处理数据结构的工具。例如,到目前为止,我们一直依赖字典来定义项目中的典型配方。有了Pydantic,我们可以这样定义配方:

from pydantic import BaseModelclass Recipe(BaseModel):id: intlabel: strsource: strraw_recipe = {'id': 1, 'label': 'Lasagna', 'source': 'Grandma Wisdom'}
structured_recipe = Recipe(**raw_recipe)
print(structured_recipe.id)
#> 1

Recipe 类继承自Pydantic BaseModel,我们可以使用标准Python类型提示来定义每个预期字段及其类型。

除了使用类型模块的标准类型外,您还可以像这样递归地使用Pydantic模型:

from pydantic import BaseModelclass Car(BaseModel):brand: strcolor: strgears: intclass ParkingLot(BaseModel):cars: List[Car]  # recursively use `Car`spaces: int

结合这些功能,您可以定义非常复杂的对象。这只是Pydantic功能的皮毛,以下是对其优势的快速总结:

  • 无需学习新的微语言(这意味着它能很好地与集成开发环境/精简器配合使用)
  • 既可用于 "验证该请求/响应数据",也可用于加载配置
  • 验证复杂的数据结构--Pydantic 提供极为精细的验证器
  • 可扩展--您可以创建自定义数据类型
  • 可与Python数据类一起使用
  • 速度非常快

2.2 Pydantic与FastAPI结合使用

ch02/main.py

from fastapi import FastAPI, APIRouter, Queryfrom typing import Optionalfrom schemas import RecipeSearchResults, Recipe, RecipeCreate
from recipe_data import RECIPESapp = FastAPI(title="Recipe API", openapi_url="/openapi.json")api_router = APIRouter()@api_router.get("/", status_code=200)
def root() -> dict:"""Root GET"""return {"msg": "Hello, World!"}# Updated using to use a response_model
# https://fastapi.tiangolo.com/tutorial/response-model/
@api_router.get("/recipe/{recipe_id}", status_code=200, response_model=Recipe)
def fetch_recipe(*, recipe_id: int) -> dict:"""Fetch a single recipe by ID"""result = [recipe for recipe in RECIPES if recipe["id"] == recipe_id]if result:return result[0]# Updated using the FastAPI parameter validation `Query` class
# # https://fastapi.tiangolo.com/tutorial/query-params-str-validations/
@api_router.get("/search/", status_code=200, response_model=RecipeSearchResults)
def search_recipes(*,keyword: Optional[str] = Query(None,min_length=3,openapi_examples={"chickenExample": {"summary": "A chicken search example","value": "chicken",}},),max_results: Optional[int] = 10
) -> dict:"""Search for recipes based on label keyword"""if not keyword:# we use Python list slicing to limit results# based on the max_results query parameterreturn {"results": RECIPES[:max_results]}results = filter(lambda recipe: keyword.lower() in recipe["label"].lower(), RECIPES)return {"results": list(results)[:max_results]}# New addition, using Pydantic model `RecipeCreate` to define
# the POST request body
@api_router.post("/recipe/", status_code=201, response_model=Recipe)
def create_recipe(*, recipe_in: RecipeCreate) -> dict:"""Create a new recipe (in memory only)"""new_entry_id = len(RECIPES) + 1recipe_entry = Recipe(id=new_entry_id,label=recipe_in.label,source=recipe_in.source,url=recipe_in.url,)RECIPES.append(recipe_entry.dict())return recipe_entryapp.include_router(api_router)if __name__ == "__main__":# Use this for debugging purposes onlyimport uvicornuvicorn.run(app, host="0.0.0.0", port=8001, log_level="debug")

ch02/schemas.py:

from pydantic import BaseModel, HttpUrlfrom typing import Sequenceclass Recipe(BaseModel):id: intlabel: strsource: strurl: HttpUrlclass RecipeSearchResults(BaseModel):results: Sequence[Recipe]class RecipeCreate(BaseModel):label: strsource: strurl: HttpUrlsubmitter_id: int

/recipe/{recipe_id} 已更新为包含response_model字段。在这里,我们通过Pydantic来定义JSON响应的结构。
新的食谱类继承自pydantic BaseModel,每个字段都使用标准类型提示进行定义,除了 url 字段,它使用了 Pydantic HttpUrl helper。这将强制执行预期的 URL 组件,例如方案(http 或 https)的存在。

我们在 /search endpointsearch 端点响应中添加了响应模型 RecipeSearchResults。我们引入了 FastAPI Query 类,它允许我们为查询参数添加额外的验证和要求,例如最小长度。请注意,由于我们设置了示例字段,因此当您"尝试"时,文档页面上会显示该示例字段。

RecipeSearchResults 类使用Pydantic的递归功能定义了一个字段,该字段指向我们之前定义的另一个Pydantic 类,即Recipe类。我们指定结果字段将是一个Recipes的Sequence(这是一个支持 len 和 getitem 的可迭代类)。

为了将函数设置为处理POST请求,我们只需调整api_router装饰器。请注意,我们还将HTTP status_code设置为 201,因为我们正在创建资源。

recipe_in 字段是 POST 请求正文。通过指定 Pydantic 模式,我们能够自动验证传入的请求,确保其主体符合我们的模式。

为了持久保存创建的配方,我们正在进行原始列表追加。当然,这只是一个玩具示例,在服务器重启时不会持久化数据。在本系列的后面,我们将介绍数据库。

RecipeCreate 模式包含一个新字段:submitter_id,因此我们要将它与 Recipe 模式区分开来。
请务必在本地通过交互式文档运行应用程序时尝试创建一些新菜谱。

参考资料

  • 软件测试精品书籍文档下载持续更新 https://github.com/china-testing/python-testing-examples 请点赞,谢谢!
  • 本文涉及的python测试开发库 谢谢点赞! https://github.com/china-testing/python_cn_resouce
  • python精品书籍下载 https://github.com/china-testing/python_cn_resouce/blob/main/python_good_books.md
  • Linux精品书籍下载 https://www.cnblogs.com/testing-/p/17438558.html

2.3 错误处理

  • 错误处理之前:

  • 新增错误处理

ch02/main2.py

from fastapi import FastAPI, APIRouter, Query, HTTPException  # 1
# skipping...@api_router.get("/recipe/{recipe_id}", status_code=200, response_model=Recipe)
def fetch_recipe(*, recipe_id: int) -> Any:"""Fetch a single recipe by ID"""result = [recipe for recipe in RECIPES if recipe["id"] == recipe_id]if not result:# the exception is raised, not returned - you will get a validation# error otherwise.# 2raise HTTPException(status_code=404, detail=f"Recipe with ID {recipe_id} not found")return result[0]

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.ryyt.cn/news/43886.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈,一经查实,立即删除!

相关文章

Winform .net 4.x 请求被中止: 未能创建 SSL/TLS 安全通道问题解决

参考https://www.cnblogs.com/Can-daydayup/p/14609089.html环境环境 版本 说明Windows Windows 10 家庭中文版 22H2 19045.4412VS Code 1.90.0Microsoft Visual Studio Microsoft Visual Studio Community 2022 (64 位) - 17.6.5 支持.net 4.x 程序需要额外配置。Microsoft .N…

更换IDEA项目的JAVA版本(8-11),

1、官网下载11的安装包 2、安装 3、修改环境变量里的JAVA_HOME变量为JAVA11的安装位置,例如C:\Program Files\Java\jdk-11 4、打开IDEA的项目,修改以下三处为java11: 4.1、修改的位置:4.2、修改complier4.3、修改project、module(我的是微服务项目,有好几个module)

1.1. 电阻篇----硬件设计指南(持续补充更新)

本系列文章是笔者对多年工作经验进行总结,结合理论与实践进行整理备忘的笔记。希望能直接指导硬件工程师的设计实操,而不是看的云里雾里的理论描述。既能帮助自己温习整理避免遗忘也能帮助其他需要参考的朋友。笔者也会不定期根据遇到的问题和想起的要点进行查漏补缺。如有谬…

stm32笔记[16]-使用usb-cdc串口.md

在stm32f103cbt6核心板使用usb cdc虚拟串口,回环发送的字符串.摘要 在stm32f103cbt6核心板使用usb cdc虚拟串口,回环发送的字符串. 关键信息STM32CubeIDE JLINK stm32f103cbt6 外部晶振:8MHz原理简介 usb-cdc简介 [https://blog.csdn.net/weixin_52296952/article/details/1357…

如何在 Linux 中使用 grep 命令的排除功能

来自grep 是一种强大的命令行工具,用于在一个或多个输入文件中搜索与正则表达式匹配的行,并将匹配的行标准输出。在本文中介绍如何在使用 grep 搜索时排除一个或多个单词或目录。排除单词或多个条件 要仅显示与搜索模式不匹配的行,请使用-v选项。例如,显示不包含nologin的…

MAVEN中的profile

---------------------------------------------------------------------------------------------------------------------------------------------------------maven的settings.xml文件用途Maven全局配置文件settings.xml详解_maven setting.xml-CSDN博客https://blog.csd…

Linux查看内存

查看 1. 使用 free 命令显示系统上可用和已用物理内存和交换内存的总量,以及内核使用的缓冲区和缓存。 # 查看命令 freetotal 总内存大小used 已被使用的内存(used= total – free – buff/cache)free 未被使用的内存 (free= total – used – buff/cache)shared…

选前端开发还是选全栈开发

选前端开发还是选全栈开发?一文带你读懂 在软件开发领域,前端开发和全栈开发是两个备受关注的职业方向。它们各自有着独特的优势和挑战,吸引着许多有志于从事软件开发的人们的目光。那么,对于初学者来说,应该如何选择呢?本文将从多个角度深入分析前端开发和全栈开发的优缺…