FastAPI

FastAPI

类型提示

1
2
3
4
5
def get_full_name(first_name: str, last_name: str):
full_name = first_name.title() + " " + last_name.title()
return full_name

print(get_full_name("john", "doe"))
  • 有类型提示时,能够使用该类型的自动补全
  • 还能检查是否有语法错误

常见类型

1
2
def get_items(item_a: str, item_b: int, item_c: float, item_d: bool, item_e: bytes):
return item_a, item_b, item_c, item_d, item_d, item_e

嵌套类型

  • 有些容器数据结构可以包含其他的值,比如 dict、list、set 和 tuple。它们内部的值也会拥有自己的类型,可以使用 Python 的 typing 标准库来声明这些类型以及子类型。

列表

1
2
3
4
5
from typing import List

def process_items(items: List[str]):
for item in items:
print(item)

元组和集合

1
2
3
4
from typing import Set, Tuple

def process_items(items_t: Tuple[int, int, str], items_s: Set[bytes]):
return items_t, items_s

字典

1
2
3
4
5
6
from typing import Dict

def process_items(prices: Dict[str, float]):
for item_name, item_price in prices.items():
print(item_name)
print(item_price)

类作为类型

1
2
3
4
5
6
class Person:
def __init__(self, name: str):
self.name = name

def get_person_name(one_person: Person):
return one_person.name

Pydantic 模型

  • Pydantic 是一个用来执行数据校验的 Python 库。你可以将数据的”结构”声明为具有属性的类。每个属性都拥有类型。接着用一些值来创建这个类的实例,这些值会被校验,并被转换为适当的类型(在需要的情况下),返回一个包含所有数据的对象。将获得这个对象的所有编辑器支持。

基本操作

1
2
3
4
5
6
7
from fastapi import FastAPI # 导入 FastAPI

app = FastAPI() # 创建一个 app 实例

@app.get("/") # 编写一个路径操作装饰器,如 @app.get("/")
async def root(): # 定义一个路径操作函数
return {"message": "Hello World"}

路径参数

  • FastAPI 支持使用 Python 字符串格式化语法声明路径参数(变量):

    1
    2
    3
    @app.get("/items/{item_id}")  # 这段代码把路径参数 item_id 的值传递给路径函数的参数 item_id
    async def read_item(item_id):
    return {"item_id": item_id}
  • 声明路径参数的类型

    1
    2
    3
    @app.get("/items/{item_id}")
    async def read_item(item_id: int): # 使用 Python 标准类型注解,声明路径操作函数中路径参数的类型
    return {"item_id": item_id}
  • 数据转换:FastAPI 通过类型声明自动解析请求中的数据

  • 数据校验:FastAPI 使用 Python 类型声明实现了数据校验

顺序很重要

  • 路径操作是按顺序依次运行的,前面声明的可能会覆盖后声明的

查询参数

  • 声明的参数不是路径参数时,路径操作函数会把该参数自动解释为查询参数

请求体

1
2
3
4
5
6
7
8
9
10
11
12
13
14
from fastapi import FastAPI
from pydantic import BaseModel

class Item(BaseModel):
name: str
description: str | None = None
price: float
tax: float | None = None

app = FastAPI()

@app.post("/items/")
async def create_item(item: Item):
return item