fastapi 请求体 - 多个参数 / 字段Field / 嵌套模型
文章目录
- 1. 混合使用 Path、Query 和请求体参数
- 2. 多个请求体参数
- 3. 请求体中的单一值
- 4. 多个请求体参数和查询参数
- 5. 嵌入单个请求体参数
- 6. 字段
- 7. 嵌套模型
- 7.1 List 字段
- 7.2 子模型作为类型
- 8. 特殊类型校验
- 9. 带有一组子模型的属性
- 10. 任意 dict 构成的请求体
learn from https://fastapi.tiangolo.com/zh/tutorial/body-multiple-params/
1. 混合使用 Path、Query 和请求体参数
from fastapi import FastAPI, Path
from typing import Optional
from pydantic import BaseModel
app = FastAPI()class Item1(BaseModel):name: strprice: floatdescription: Optional[str] = Nonetax: Optional[float]@app.put("/items/{item_id}")
async def update_item(*,item_id: int = Path(..., title="id of item to get", ge=0, le=1000),q: Optional[str] = None,item: Optional[Item1] = None,
):res = {"item_id": item_id}if q:res.update({"q": q})if item:res.update({"item": item})return res
2. 多个请求体参数
from pydantic import BaseModelclass Item(BaseModel):name: strprice: floatdescription: Optional[str] = Nonetax: Optional[float]
class User(BaseModel):username: strfull_name: Optional[str] = None@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item, user: User):res = {"item_id" : item_id, "item" : item, "user": user}return res
- 使用 参数名称 最为 key 的 字典传入
3. 请求体中的单一值
- 传参时,
varname : type = Body(...)
,如果不这么写,会被作为查询参数?varname=xxx
from fastapi import Bodyclass Item(BaseModel):name: strprice: floatdescription: Optional[str] = Nonetax: Optional[float]
class User(BaseModel):username: strfull_name: Optional[str] = None@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item, user: User, importance : int = Body(...)):res = {"item_id" : item_id, "item" : item, "user": user}return res
现在可以写在请求体内:
4. 多个请求体参数和查询参数
由于默认情况下单一值被解释为查询参数,因此你不必显式地添加 Query,你可以仅执行操作:q: str = None
5. 嵌入单个请求体参数
如果你只有一个请求体参数
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):res = {"item_id" : item_id, "item" : item}return res
你的请求体需要写成如下形式:
如果你想写成 带 key 的 json 形式,添加一个传入参数 embed,item: Item = Body(..., embed=True)
6. 字段
可以使用 Pydantic
的 Field
在 Pydantic 模型
内部声明校验和元数据
from fastapi import FastAPI, Path, Body
from typing import Optional
from pydantic import BaseModel, Field
app = FastAPI()class Item(BaseModel):name: strprice: float = Field(..., gt=0, description="price must be greater than 0")description: Optional[str] = Field(None, title="description of item", max_length=30)tax: Optional[float] = None@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item = Body(..., embed=True)):res = {"item_id" : item_id, "item" : item}return res
Field
的工作方式和 Query、Path 和 Body 相同,包括它们的参数等等也完全相同
- 注意,from pydantic import Field
7. 嵌套模型
7.1 List 字段
将一个属性定义为拥有子元素的类型,如 list
class Item(BaseModel):name: strprice: float = Field(..., gt=0, description="price must be greater than 0")description: Optional[str] = Field(None, title="description of item", max_length=30)tax: Optional[float] = Nonetags: list = [] # 没有声明元素类型
- 具有子类型的 List,
from typing import List
tags: List[str] = []
7.2 子模型作为类型
from fastapi import FastAPI, Path, Body
from typing import Optional, List, Set
from pydantic import BaseModel, Field
app = FastAPI()class Image(BaseModel):url:strname: strclass Item(BaseModel):name: strprice: float = Field(..., gt=0, description="price must be greater than 0")description: Optional[str] = Field(None, title="description of item", max_length=30)tax: Optional[float] = Nonetags: Set[str] = []image: Optional[Image] = None@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item = Body(..., embed=True)):res = {"item_id" : item_id, "item" : item}return res
8. 特殊类型校验
HttpUrl
,检查是不是有效的 URL
from pydantic import BaseModel, Field, HttpUrl
app = FastAPI()class Image(BaseModel):url: HttpUrlname: str
则上面的输入应改的地方 "url":"http://www.michael.com",
否则不是有效的 URL
9. 带有一组子模型的属性
- 更改为
image: Optional[List[Image]] = None
输入需要改为
@app.post("/images/multiple/")
async def create_multiple_images(images: List[Image]):return images
10. 任意 dict 构成的请求体
from typing import Optional, List, Set, Dict
@app.post("/index-weights/")
async def create_index_weights(weights: Dict[int, float]): # key 为 int, value 为浮点return weights
请记住 JSON 仅支持将 str
作为键。 但是 Pydantic 具有自动转换数据的功能。
fastapi 请求体 - 多个参数 / 字段Field / 嵌套模型相关推荐
- fastapi 用户指南(路径参数、查询参数、请求体)
文章目录 1. 第一步 1.1 小结 2. 路径参数 2.1 顺序很重要 2.2 预设值 2.3 包含路径的路径参数 3. 查询参数 3.1 查询参数类型转换 4. 请求体 learn from ht ...
- Spring拦截器获取request请求体中的json数据,并转换成Java对象的解决办法
1.要被拦截的Controller接口 我们需要一个更新用户信息接口,请求方式为POST,参数类型为对象类型(UserInfo),代码如下: @Resource private UserService ...
- 请求体的方式传参_Angularjs中$http以post请求通过消息体传递参数的实现方法
本文实例讲述了Angularjs中$http以post请求通过消息体传递参数的方法.分享给大家供大家参考,具体如下: Angularjs中,$http以post在消息体中传递参数,需要做以下修改,以确 ...
- ajax中POST请求与参数(请求体)设置
回到文章总目录 1.创建在testthree文件夹并在这个文件夹里面 2.创建post.html文件 3.创建server.js文件 本篇文章使用了当鼠标移动至方框内则发送请求示例 post.html ...
- Spring/SpringBoot 过滤器修改、获取http 请求request中的参数 和 response返回值,比如修改请求体和响应体的字符编码
通过自定义filter,RequestWrapper,ResponseWrapper 处理请求和响应数据,比如修改请求体和响应体的字符编码 1.request 和 response 中的数据都是 存在 ...
- 接口测试平台插播: 同名字段请求体-其他涉及代码
我们上节课,成功的把单接口调试的底层请求代码中form-data等格式的请求体从字典转变为了多元元组,实现了同名字段的正常请求.本节就来搞定首页请求/用例请求/异常测试/登陆态的底层代码. 首先是异常 ...
- feign 使用示例:动态url、动态参数、下载文件、请求体
文章目录 构建FeignClient接口实现 动态url 带参数的请求 @Param 带动态参数的请求 @QueryMap 下载文件的请求 带请求体的请求 @Body 官方使用文档: 链接 https ...
- fastapi 请求文件 / 表单 / 处理错误 / 路径操作配置 / jsonable_encoder
文章目录 1. File 参数 2. 多文件上传 3. 请求表单与文件 4. 处理错误 5. 自定义响应头 6. 自定义异常处理器 7. 覆盖默认异常处理器 8. 使用 RequestValidati ...
- python:Fastapi - 请求表单与文件
简单絮叨下,如有问题请私信 上篇文章主要唠了接口响应的一些东西,今天主要是唠Form表单和文件处理.表单可以理解为数据采集,而文件处理就是在获得客户端的文件进行数据返回或者直接上传服务器. fasta ...
最新文章
- springboot集成logback日志 通用logback.xml模板详解
- java实现在pdf文档上填充内容
- 潜移默化学会WPF(难点控件treeview)--改造TreeView(CheckBox多选择版本),递归绑定数据...
- rest-framework 视图
- R语言数据可视化 ggplot2基础1 ggplot2 图形的分层语法 Layered Grammar 简介
- asp.net三层架构连接Oracle 11g详解
- CRM Order confirmation form布局
- class对象和class文件_Class文件格式
- 计算机专业学生创新创优创业情况,高校计算机专业学生创新创业教育模式研究...
- 【数据科学系统学习】机器学习算法 # 西瓜书学习记录 [8] 支持向量机(二)...
- ARM指令ldr、str、stm、ldm理解
- Java 多线程 简单实例 (Thread)
- pat1032. Sharing (25)
- java反射机制面试详解
- Notepad++实现verilog语法检查
- C语言链表详解(通俗易懂)
- 户外广告的创新思考,媒体运用上的创新
- vue 3 的devtools beta 版离线下载
- 《BPF( 伯克利数据包过滤器 ) Performance Tools》 第六章 CPU
- sciter 进度条 百分比计算函数
热门文章
- kafka 异常:return ‘<SimpleProducer batch=%s>‘ % self.async ^ SyntaxError: invalid syntax
- 喇叭正反相位测试音频_FIR滤波器能给音频扩声带来怎样的帮助?
- 挖矿为什么要用显卡_Conflux显卡挖矿收益很高吗?挖矿指南与核算手册
- an 转换器_400V耐压场效应管替代IRF730B型号参数,使用在DC-DC电源转换器。_场效应管吧...
- 【机器学习实战之一】:C++实现K-近邻算法KNN
- iOS10 xcode8 分页请求MJRefresh崩溃问题
- vs2017常量文本字符串无法转换成char*
- j.u.c系列(08)---之并发工具类:CountDownLatch
- 在Linux下不使用密码远程登陆其他Linux
- js中的四舍五入函数