美文网首页
FastAPI 教程(五)

FastAPI 教程(五)

作者: Frederich | 来源:发表于2020-07-09 10:15 被阅读0次

Body Field 校验

检验可以写在路由方法中,用 Query、Body、Path 等方法来写入校验条件,也可以使用 Pydantic 中的 Field 类来实现,Field 的用法与前面讲到的 Query、Body 等类似,例如:

from typing import Optional
from fastapi import Body, FastAPI
from pydantic import BaseModel, Field

app = FastAPI()


class Item(BaseModel):
    name: str
    description: Optional[str] = Field(
        None, title="The description of the item", max_length=300
    )
    price: float = Field(..., gt=0, description="The price must be greater than zero")
    tax: Optional[float] = None


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

在使用的时候,还可以加入一些额外的信息,都会生成在最终的 JSON Schema 中。

使用 typing 中的 List 和 Set 类型

我们可以使用 typing 中 List 和 Set 类型来指定 Model 中的数据类型,例如:

from typing import Optional, List, Set
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] = []
    categories: Set[str] = set()


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

我们在测试的时候就可以输入类似这样的数据:


image.png

嵌套 Model

我们定义的 Model 中可以包含其他 Model 类型的数据,例如:

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

app = FastAPI()


class Image(BaseModel):
    url: str
    name: str


class Item(BaseModel):
    name: str
    description: Optional[str] = None
    price: float
    tax: Optional[float] = None
    tags: Set[str] = []
    # 下面是 image 类型的数据
    image: Optional[Image] = None


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

这样我i们的请求体的数据就是类似下面的形式:

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

在请求体中接收Model的列表

我们在请求体中可以输入多个 Model 组成的列表,例如:

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

app = FastAPI()


class Image(BaseModel):
    url: HttpUrl
    name: str


@app.post("/images/multiple/")
async def create_multiple_images(images: List[Image]):  # 接收一个 image 类型的列表
    return images

在请求体中接收 dict 类型

我们可以先引入 typing 中的 Dict ,然后作为路由方法的参数,例如:

from typing import Dict
from fastapi import FastAPI

app = FastAPI()


@app.post("/index-weights/")
async def create_index_weights(weights: Dict[int, float]):
    return weights

那么我们就可以传入类似这样的数据:

{
  "1": 2.2,
  "2": 3.3,
  "3": 5.5
}

这里1,2,3之所以要加引号,是因为 JSON 格式对 key 的要求,不能直接用数字。

其他数据类型

Pydantic 模型支持很丰富的数据类型,除了常用的 str、int、float外还有:

  • UUID: 需要先 from uuid import UUID
  • datetime.date: 日期
  • datetime.time: 时间
  • FilePath: pydantic 自带的类型,文件必须存在
  • EmailStr: 需要安装 email_validator
  • AnyUrl、AnyHttpUrl、HttpUrl: url类型

详细文档可以查看 https://pydantic-docs.helpmanual.io/usage/types/

相关文章

  • FastAPI 教程(五)

    Body Field 校验 检验可以写在路由方法中,用 Query、Body、Path 等方法来写入校验条件,也可...

  • SqlAlchemy:'users' 中的列 'email' 的

    最近在学fastapi,使用的数据库是SQL Server在FastApi官方教程的SQL Database章节[...

  • FastAPI 教程(四)

    参数校验 基本的类型验证可以通过指定参数类型来实现。 如果需要更复杂的校验,就需要引入 fastapi 的 Que...

  • FastAPI 教程(六)

    Cookie 变量 从 fastapi 引入 Cookie 后,可以使用类似 Query、Path 的方式来获取 ...

  • FastAPI 教程(三)

    表单 如果要获取表单的数据,需要进行一下步骤: 导入 fastapi 中的 Form 在模板中通过 Form(.....

  • FastAPI 教程(七)

    异常处理 异常处理需要先从 fastapi 中引入 HTTPException,有异常的时候就 raise 一个 ...

  • FastAPI 教程(一)

    安装 FastAPI 需要安装 fastapi、uvicorn 以及 python-multipart 三个库。 ...

  • FastAPI 教程(二)

    路径参数(Path Parameter) 路径参数在路由里面用大括号括起来,在方法中需要把参数写出来,还可以标注参...

  • fastapi教程翻译(一):了解FastAPI结构

    一、编写一个简单的FastAPI程序 最简单的FastAPI文件可能如下: 将上面代码块复制到 main.py. ...

  • 1.FastAPI介绍

    一、 Fastapi是什么 FastAPI 框架,高性能,易于学习,高效编码,生产可用 FastAPI 是一个用于...

网友评论

      本文标题:FastAPI 教程(五)

      本文链接:https://www.haomeiwen.com/subject/isaccktx.html