【FastAPI基础】9、请求体-嵌套类型

引言:

最近工作中有机会接触FastAPI这个框架,所以就把官方文档看了一遍,对框架的各个特性及使用方法做了总结,会逐步的发出来,希望对您有用。

如果您之前接触过python的其他框架,看起来会非常简单和顺畅,其实就是很简单。

【上一篇】:【FastAPI基础】8、请求体-Field字段
【下一篇】:【FastAPI基础】10、模型的额外信息-示例
【FastAPI搭建好的产品框架源码,直接上手】:【FastAPI搭建好的产品架构】,直接上手

1、具有子类型的 List 字段
但是 Python 有一种特定的方法来声明具有子类型的列表:
从 typing 导入 List
首先,从 Python 的标准库 typing 模块中导入 List:

from typing import List, Optional
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
     name: str
    description: Optional[str] = None
    price: float
    tax: Optional[float] = None
    tags: List[str] = []


@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
    results = {
   "item_id": item_id, "item": item}
    return results

2、声明具有子类型的 List
要声明具有子类型的类型,例如 list、dict、tuple:
从 typing 模块导入它们,使用方括号 [ 和 ] 将子类型作为「类型参数」传入.

from typing import List
my_list: List[str]

这完全是用于类型声明的标准 Python 语法。
对具有子类型的模型属性也使用相同的标准语法。
因此,在我们的示例中,我们可以将 tags 明确地指定为一个「字符串列表」:

from typing import List, Optional
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    name: str
    description: Optional[str] = None
    price: float
    tax: Optional[float] = None
    tags: List[str] = []


@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
    results = {
   "item_id": item_id, "item": item}
    return results
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陈建华呦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值