FastAPI 基础入门-章节五(Pydantic的使用) - 详解

FastAPI 与 Pydantic 技术深度解析

FastAPI 基础入门

安装与第一个示例

# 安装 FastAPI 和 Uvicorn
pip install fastapi uvicorn
# 创建 main.py 文件
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {
"message": "Hello, FastAPI!"}
# 启动服务
uvicorn main:app --reload

解释

  1. pip install 命令安装 FastAPI 框架和 Uvicorn ASGI 服务器。
  2. FastAPI() 创建应用程序实例,@app.get("/") 定义根路径的 GET 请求处理函数。
  3. uvicorn main:app --reload 启动开发服务器,--reload 参数启用热重载功能。
  4. 访问 http://127.0.0.1:8000 将看到 JSON 格式的响应结果。

Pydantic 介绍

核心特性与作用

from pydantic import BaseModel
class User(BaseModel):
name: str
age: int
is_active: bool = True  # 默认值
user = User(name="Alice", age=30)
print(user)  # User(name='Alice', age=30, is_active=True)

解释

  1. BaseModel 是 Pydantic 的核心基类,通过类型注解定义数据模型。
  2. 默认值通过 = 指定,未传参时自动填充。
  3. 实例化时自动进行类型验证:若传入 age="thirty" 会抛出 ValidationError

Pydantic 的使用模型

常见数据类型支持

from typing import List, Optional
class Product(BaseModel):
id: int
name: str
tags: List[str] = ["default"]
price: float
description: Optional[str] = None

解释

  1. 支持基本类型(str/int/float/bool)和复杂类型(List/Dict)。
  2. Optional 表示字段可为 None,等价于 Union[str, None]
  3. 列表默认值使用 List[str] = ["default"],可选字段使用 Optional[str] = None

必选与可选参数

class Order(BaseModel):
product_id: int  # 必填字段
quantity: int = 1  # 可选字段,默认值 1
customer: Optional[str]  # 可选字段,无默认值

解释

  1. 未设置默认值的字段(如 product_id)是必填项。
  2. 通过 Optional 或默认值实现可选字段。
  3. 若调用 Order(product_id=100)quantity=1 会被自动填充。

posted on 2025-12-06 09:05  ljbguanli  阅读(0)  评论(0)    收藏  举报