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

FastAPI -- 第一弹

Hello World

经典的 Hello World

安装

pip install fastapi
pip install "uvicorn[standard]"

main.py

from typing import Unionfrom fastapi import FastAPIapp = FastAPI()@app.get("/")
def read_root():return {"Hello": "World"}@app.get("/items/{item_id}")
def read_item(item_id: int, q: Union[str, None] = None):return {"item_id": item_id, "q": q}

运行

uvicorn main:app --reload

交互式 API 文档

http://127.0.0.1:8000/doc (由 Swagger UI生成)
或者
http://127.0.0.1:8000/redoc (由 ReDoc 生成)

参数

路径参数

from fastapi import FastAPIapp = FastAPI()# http://127.0.0.1:8000/items/foo
@app.get("/items/{item_id}")
async def read_item(item_id):# return {"item_id": "foo"}return {"item_id": item_id}
声明路径参数的类型
from fastapi import FastAPIapp = FastAPI()@app.get("/items/{item_id}")
async def read_item(item_id: int):	#  通过类型注解,声明 item_id 为 int 类型return {"item_id": item_id}
数据转换
from fastapi import FastAPIapp = FastAPI()@app.get("/items/{item_id}")
async def read_item(item_id: int):	#  通过类型注解,声明 item_id 为 int 类型return {"item_id": item_id}

运行上面的示例代码,并访问 http://127.0.0.1:8000/items/3,
返回的响应如下:
{"item_id": 3}

顺序很重要

url /users/me/users/{user_id} , 路径操作是按顺序依次运行的,因此,一定要在/users/{user_id}之前声明 /users/me

from fastapi import FastAPIapp = FastAPI()@app.get("/users/me")
async def read_user_me():return {"user_id": "the current user"}@app.get("/users/{user_id}")
async def read_user(user_id: str):return {"user_id": user_id}

否则,/users/{user_id} 将匹配 /users/me,FastAPI 会认为正在接收值为 “me” 的 user_id 参数

查询参数(问号参数)

声明的参数不是路径参数时,路径操作函数会把该参数自动解释为查询参数。
参数优先级: 路径参数> 查询参数

默认值 | 可选参数,必填参数
from fastapi import FastAPIapp = FastAPI()fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]# skip: int = 0, limit: int = 10
# skip 和 limit 都设置了默认值
# 
# 访问 http://127.0.0.1:8000/items/
# 访问 http://127.0.0.1:8000/items/?skip=0&limit=10
# 访问 http://127.0.0.1:8000/items/?skip=20
# 上面的三种访问方式是等效的,
# 所以设置默认值之后的参数等效于可选参数
#
# 同理 将其他类型的字段设置为其对应的**默认值**或者**None**,就可以使该字段变为 **可选字段**
# 例如: int = 0, str = "",  bool = False
#       int|None = None , str|None = None,  bool|None = None
# 建议使用 
@app.get("/items/")
async def read_item(skip: int = 0, limit: int = 10):return fake_items_db[skip : skip + limit]

必选参数

不设置默认值的参数,就是必选参数

使用 Query 作为默认值
from typing import Unionfrom fastapi import FastAPI, Queryapp = FastAPI()@app.get("/items/")
async def read_items(q: Union[str, None] = Query(default=None, max_length=50)):results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}if q:results.update({"q": q})return results
使用 Query 添加更多校验
from typing import Unionfrom fastapi import FastAPI, Queryapp = FastAPI()@app.get("/items/")
async def read_items(q: Union[str, None] = Query(default=None, min_length=3, max_length=50,alias="An alternative name for the parameter field.",title="Human-readable title",description="Human-readable description",deprecated="Mark this parameter field as deprecated.",pattern="RegEx pattern for strings.",),
):results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}if q:results.update({"q": q})return results

请求体

创建数据模型&声明请求体
from fastapi import FastAPI
from pydantic import BaseModel# 创建数据模型
class Item(BaseModel):name: strdescription: str | None = Noneprice: floattax: float | None = Noneapp = FastAPI()@app.post("/items/")
async def create_item(item: Item):	
# item: Item, 声明 item Item 类型,
# 由于 Item 属于 BaseModel类型,所以会被识别为请求体 return item
参数识别规则

函数参数按如下规则进行识别:

  • 路径中声明了相同参数的参数,是路径参数
  • 类型是(int、float、str、bool 等)单类型的参数,是查询参数
  • 类型是 Pydantic 模型的参数,是请求体
校验请求体字段
from typing import Annotatedfrom fastapi import Body, FastAPI
from pydantic import BaseModel, Fieldapp = FastAPI()class Item(BaseModel):name: str# 通过 Field 为字段 description 增加更多信息 或者校验# TODO: # 		from pydantic import Field# 		from fastapiimport Query,Path,Bodydescription: str | None = Field(default=None, title="The description of the item", max_length=300)price: float = Field(gt=0, description="The price must be greater than zero")tax: float | None = None@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Annotated[Item, Body(embed=True)]):results = {"item_id": item_id, "item": item}return results
多个请求体参数&请求体中的单一值
from typing import Annotatedfrom fastapi import Body, FastAPI
from pydantic import BaseModelapp = FastAPI()class Item(BaseModel):name: strdescription: str | None = Noneprice: floattax: float | None = Noneclass User(BaseModel):username: strfull_name: str | None = None@app.put("/items/{item_id}")
async def update_item(# 多个请求体参数item_id: int, item: Item, user: User, # 通过 Annotated[int, Body()] 将 声明为请求体参数,# 否则根据参数识别规则,将被识别为 查询参数importance: Annotated[int, Body()] 
):results = {"item_id": item_id, "item": item, "user": user, "importance": importance}return results

期望请求体示例

{"item": {"name": "Foo","description": "The pretender","price": 42.0,"tax": 3.2},"user": {"username": "dave","full_name": "Dave Grohl"},"importance": 5
}

模型

嵌入单个请求体

from typing import Annotatedfrom fastapi import Body, FastAPI
from pydantic import BaseModelapp = FastAPI()class Item(BaseModel):name: strdescription: str | None = Noneprice: floattax: float | None = None@app.put("/items/{item_id}")
async def update_item(item_id: int, # 通过 Annotated[Item, Body(embed=True)]# 将 item 作为 key 嵌入到请求体中item: Annotated[Item, Body(embed=True)],):results = {"item_id": item_id, "item": item}return results

期望请求体示例

{"item": {"name": "Foo","description": "The pretender","price": 42.0,"tax": 3.2}
}

嵌套模型 & List

from typing import List, Unionfrom fastapi import FastAPI
from pydantic import BaseModel, HttpUrlapp = FastAPI()class Image(BaseModel):url: HttpUrlname: strclass Item(BaseModel):name: strdescription: str | None = Noneprice: floattax: float | None = Nonetags: set[str] = set()# 通过 list 将 Image 作为 元素嵌入到 Item中images: list[Image] | None = None# 同理,通过 list 将 str作为 元素嵌入到 Item 中# images: List[str] | None = None# images: List[int] | None = None# 同理,将 Image 直接 嵌入到 Item 中# images: Image | None = None@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):results = {"item_id": item_id, "item": item}return results

期望请求体示例

{"name": "Foo","description": "The pretender","price": 42.0,"tax": 3.2,"tags": ["rock","metal","bar"],"images": [{"url": "http://example.com/baz.jpg","name": "The Foo live"},{"url": "http://example.com/dave.jpg","name": "The Baz"}]
}

多层嵌套模型

from fastapi import FastAPI
from pydantic import BaseModel, HttpUrlapp = FastAPI()class Image(BaseModel):url: HttpUrlname: strclass Item(BaseModel):name: strdescription: str | None = Noneprice: floattax: float | None = Nonetags: set[str] = set()images: list[Image] | None = Noneclass Offer(BaseModel):name: strdescription: str | None = Noneprice: floatitems: list[Item]@app.post("/offers/")
async def create_offer(offer: Offer):return from fastapi import FastAPI
from pydantic import BaseModel, HttpUrlapp = FastAPI()class Image(BaseModel):url: HttpUrlname: strclass Item(BaseModel):name: strdescription: str | None = Noneprice: floattax: float | None = Nonetags: set[str] = set()images: list[Image] | None = Noneclass Offer(BaseModel):name: strdescription: str | None = Noneprice: floatitems: list[Item]@app.post("/offers/")
async def create_offer(offer: Offer):# 多层嵌套# offer -> Item         -> Image#       -> list[Item]#                       -> list[Image]return offer

为模型添加额外信息

from fastapi import FastAPI
from pydantic import BaseModelapp = FastAPI()class Item(BaseModel):name: strdescription: str | None = Noneprice: floattax: float | None = Nonemodel_config = {"json_schema_extra": {"examples": [{"name": "Foo","description": "A very nice Item","price": 35.4,"tax": 3.2,}]}}@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):results = {"item_id": item_id, "item": item}return results

到此结  DragonFangQy 2024.07.11

相关文章:

FastAPI -- 第一弹

Hello World 经典的 Hello World 安装 pip install fastapi pip install "uvicorn[standard]"main.py from typing import Unionfrom fastapi import FastAPIapp FastAPI()app.get("/") def read_root():return {"Hello": "World"}…...

C++入门基础篇(1)

欢迎大家来到海盗猫鸥的博客—— 断更许久,让我们继续好好学习吧! 目录 1.namespace命名空间 命名空间的存在价值: 命名空间的定义: 命名空间的使用: 2.C输入输出函数 使用: 3.缺省参数 4.函数重载…...

基于html开发的在线网址导航在线工具箱源码

基于html开发的在线网址导航在线工具箱源码,将全部文件复制到服务器,入口文件是index.html 如需修改网址,可修改index.html 如需修改关于页面,可修改about里面的index页面 源码下载:https://download.csdn.net/down…...

【密码学】大整数分解问题和离散对数问题

公钥密码体制的主要思想是通过一种非对称性,即正向计算简单,逆向计算复杂的加密算法设计,来解决安全通信。本文介绍两种在密码学领域内最为人所熟知、应用最为广泛的数学难题——大整数分解问题与离散对数问题 一、大整数分解问题 &#xf…...

解析 pdfminer layout.py LAParams类及其应用实例

解析 pdfminer layout.py LAParams类及其应用实例 引言类的定义1. line_overlap2. char_margin3. word_margin4. line_margin5. boxes_flow6. detect_vertical7. all_texts 类的初始化参数验证类的表示总结 引言 在这篇文章中,我们将解析一个叫做 LAParams 的类。这…...

Redis官方可视化管理工具

版权声明 本文原创作者:谷哥的小弟作者博客地址:http://blog.csdn.net/lfdfhl RedisInsight是一个Redis可视化工具,提供设计、开发和优化 Redis 应用程序的功能。RedisInsight分为免费的社区版和一个付费的企业版,免费版具有基本…...

android 固定图片大小

在Android中,固定图片大小可以通过多种方法实现,这些方法主要涉及到ImageView控件的使用、Bitmap类的操作,以及第三方库(如Glide)的辅助。以下是几种常见的方法: 1. 使用ImageView控件 在Android的布局文…...

操作系统——内存管理(面试准备)

虚拟内存 单片机没有操作系统,每次写完代码,都需要借助工具把程序烧录进去,这样程序才能跑起来。 另外,单片机的CPU是直接操作内存的物理地址。 在这种情况下,想在内存中同时运行两个程序是不可能的,如果第…...

vue3实现vuedraggable实现拖拽到垃圾桶图标位置进行删除

当使用Vue 3和vuedraggable库时,你可以按照以下方式实现拖拽到垃圾桶图标位置进行删除的功能: 首先,确保你已经安装了vuedraggable库。如果没有安装,可以通过以下命令进行安装: vuedraggable 和vue-draggable-plus使…...

MySQL向自增列插入0失败问题

问题 在一次上线时,发现通过脚本添加的状态表中,待提交的状态不正确,本来应该是0,线上是101。 原因 默认情况下,MySQL对应自增列,认为0和null等价(因为mysql认为0不是最佳实践不推荐使用&…...

Python:Python基础知识(注释、命名、数据类型、运算符)

.注释 Python有两种注释方法:单行注释和多行注释。单行注释以#开头,多行注释以三个单引号 或三个双引号 """ 开头和结尾。 2.命名规则 命名规则: 大小写字母、数字、下划线和汉字等字符及组合; 注意事项: 大小写敏感、首…...

Protobuf: 大数据开发中的高效数据传输利器

作为一名大数据开发者,我经常需要处理海量的数据传输和存储。在这个过程中,选择一个高效、可靠的数据序列化工具至关重要。今天,我想和大家分享一下我在项目中使用 Protobuf 的经历。 目录 故事背景Protobuf 简介优点: 实战案例示…...

MySQL 面试相关问题

写在前面: 不喜勿喷,暴躁作者又不求你给钱【没办法,遇见的狗喷子太多了🐶】欢迎大家在评论区留言,指正文章中的信息错误有一些其他相关的问题,可以直接评论区留言,作者看到会及时更新到文章末尾…...

java org.aeonbits.owner库介绍

org.aeonbits.owner 是一个用于简化Java应用程序配置管理的库。它通过使用接口和注解来定义和读取配置,使得配置管理更加简洁和类型安全。以下是对这个库的一些主要特性和功能的介绍: 主要特性 类型安全的配置: OWNER 库允许开发者使用接口定义配置,从而提供了编译时的类型…...

YOLOv10改进 | 添加注意力机制篇 | 添加LSKAttention大核注意力机制助力极限涨点

一、本文介绍 在这篇文章中,我们将讲解如何将LSKAttention大核注意力机制应用于YOLOv10,以实现显著的性能提升。首先,我们介绍LSKAttention机制的基本原理,它主要通过将深度卷积层的2D卷积核分解为水平和垂直1D卷积核&#xff0…...

学习笔记——动态路由——IS-IS中间系统到中间系统(特性之路由撤销)

6、路由撤销 ISIS路由协议的路由信息是封装在LSP报文中的TLV中的,但是它对撤销路由的处理和OSPF的处理方式类似。 在ISIS中撤销一条路由实则是将接口下的ISIS关闭: 撤销内部路由: 在ISIS中路由信息是由IP接口TLV和IP内部可达性TLV共同来描…...

智能无人机控制:STM32微控制器与机器学习集成(内附资料)

智能无人机控制结合了STM32微控制器的实时处理能力和机器学习算法的决策能力,以实现更高级的自主飞行和任务执行。以下是智能无人机控制系统的概述,包括系统架构、关键组件、集成方法和示例代码。 系统概述 智能无人机控制系统利用STM32微控制器进行实…...

力扣 454四数相加

这个题给了四个数组,可以两两判断,就类比两数相加那道题了 对于num1 num2 用unordered_map存储,key是num1,num2中数字相加之和,value是值出现的次数 for(int a:num1) {for(int b:num2 {map[ab]; 最后要计算四个数…...

Java面试题系列 - 第9天

题目:深入探讨Java中的设计模式及其应用场景 背景说明:设计模式是软件工程中解决问题的常见方案,它们提供了经过验证的模板,帮助开发者解决在软件设计过程中遇到的特定问题。在Java中,熟悉并正确应用设计模式能够显著…...

数据结构【顺序表】

目录 ​ 线性表 顺序表 概念与结构 分类 静态顺序表 动态顺序表 动态顺序表的实现 在头文件中创建结构体 初始化顺序表 销毁顺序表(可以留到后面再看) 尾插数据 申请空间 打印顺序表数据 头插数据 尾删除数据 头删除数据 在指定位置插…...

基于大模型的 UI 自动化系统

基于大模型的 UI 自动化系统 下面是一个完整的 Python 系统,利用大模型实现智能 UI 自动化,结合计算机视觉和自然语言处理技术,实现"看屏操作"的能力。 系统架构设计 #mermaid-svg-2gn2GRvh5WCP2ktF {font-family:"trebuchet ms",verdana,arial,sans-…...

React hook之useRef

React useRef 详解 useRef 是 React 提供的一个 Hook,用于在函数组件中创建可变的引用对象。它在 React 开发中有多种重要用途,下面我将全面详细地介绍它的特性和用法。 基本概念 1. 创建 ref const refContainer useRef(initialValue);initialValu…...

Redis相关知识总结(缓存雪崩,缓存穿透,缓存击穿,Redis实现分布式锁,如何保持数据库和缓存一致)

文章目录 1.什么是Redis?2.为什么要使用redis作为mysql的缓存?3.什么是缓存雪崩、缓存穿透、缓存击穿?3.1缓存雪崩3.1.1 大量缓存同时过期3.1.2 Redis宕机 3.2 缓存击穿3.3 缓存穿透3.4 总结 4. 数据库和缓存如何保持一致性5. Redis实现分布式…...

屋顶变身“发电站” ,中天合创屋面分布式光伏发电项目顺利并网!

5月28日,中天合创屋面分布式光伏发电项目顺利并网发电,该项目位于内蒙古自治区鄂尔多斯市乌审旗,项目利用中天合创聚乙烯、聚丙烯仓库屋面作为场地建设光伏电站,总装机容量为9.96MWp。 项目投运后,每年可节约标煤3670…...

土地利用/土地覆盖遥感解译与基于CLUE模型未来变化情景预测;从基础到高级,涵盖ArcGIS数据处理、ENVI遥感解译与CLUE模型情景模拟等

🔍 土地利用/土地覆盖数据是生态、环境和气象等诸多领域模型的关键输入参数。通过遥感影像解译技术,可以精准获取历史或当前任何一个区域的土地利用/土地覆盖情况。这些数据不仅能够用于评估区域生态环境的变化趋势,还能有效评价重大生态工程…...

MySQL用户和授权

开放MySQL白名单 可以通过iptables-save命令确认对应客户端ip是否可以访问MySQL服务: test: # iptables-save | grep 3306 -A mp_srv_whitelist -s 172.16.14.102/32 -p tcp -m tcp --dport 3306 -j ACCEPT -A mp_srv_whitelist -s 172.16.4.16/32 -p tcp -m tcp -…...

Reasoning over Uncertain Text by Generative Large Language Models

https://ojs.aaai.org/index.php/AAAI/article/view/34674/36829https://ojs.aaai.org/index.php/AAAI/article/view/34674/36829 1. 概述 文本中的不确定性在许多语境中传达,从日常对话到特定领域的文档(例如医学文档)(Heritage 2013;Landmark、Gulbrandsen 和 Svenevei…...

如何更改默认 Crontab 编辑器 ?

在 Linux 领域中,crontab 是您可能经常遇到的一个术语。这个实用程序在类 unix 操作系统上可用,用于调度在预定义时间和间隔自动执行的任务。这对管理员和高级用户非常有益,允许他们自动执行各种系统任务。 编辑 Crontab 文件通常使用文本编…...

elementUI点击浏览table所选行数据查看文档

项目场景&#xff1a; table按照要求特定的数据变成按钮可以点击 解决方案&#xff1a; <el-table-columnprop"mlname"label"名称"align"center"width"180"><template slot-scope"scope"><el-buttonv-if&qu…...

AxureRP-Pro-Beta-Setup_114413.exe (6.0.0.2887)

Name&#xff1a;3ddown Serial&#xff1a;FiCGEezgdGoYILo8U/2MFyCWj0jZoJc/sziRRj2/ENvtEq7w1RH97k5MWctqVHA 注册用户名&#xff1a;Axure 序列号&#xff1a;8t3Yk/zu4cX601/seX6wBZgYRVj/lkC2PICCdO4sFKCCLx8mcCnccoylVb40lP...