一、FastAPI框架简介
1.1 FastAPI框架简介
FastAPI是一个用于构建API的现代、快速(高性能)的Web框架,基于Python 3.7+的类型提示,建立在Starlette和Pydantic基础之上。
FastAPI框架有以下特性:
●Starlette:轻量级的 ASGI 框架/工具包,是构建高性能 Asyncio 服务的理想选择
●Pydantic:基于 Python 类型提示来定义数据验证、序列化和文档的库
FastAPI 的核心特性:
1.快速:可与 NodeJS 和 Go 比肩的极高性能,是最快的 Python Web 框架之一
2.智能:极佳的编辑器支持,处处皆可自动补全,减少调试时间
3.简单:设计的易于使用和学习,阅读文档的时间更短
4.简短:使代码重复最小化,通过不同的参数声明实现丰富功能
5.健壮:生产可用级别的代码,还有自动生成的交互式文档
6.标准化:基于(并完全兼容)API 的相关开放标准:OpenAPI 和 JSON Schema
![]()
1.2 为什么选择FastAPI框架
让我们从多个维度详细对比 FastAPI、Flask 和 Django REST Framework框架:
![]()
FastAPI 的性能优势:
●基于 ASGI(异步服务器网关接口),而非传统的 WSGI
●原生支持 async/await,充分利用 Python 异步特性
●使用 Uvicorn 作为 ASGI 服务器,性能接近 Go 和 Node.js
选择 FastAPI 框架的理由:
1.原生异步支持:完美支持 async/await,适合 I/O 密集型应用
2.自动数据验证:基于 Pydantic,自动验证请求数据并生成清晰的错误信息
3.自动文档生成:无需额外配置即可生成交互式 API 文档(Swagger UI 和 ReDoc)
4.类型安全:完整的类型提示支持,IDE 自动补全和类型检查
5.高性能:基于 ASGI,性能接近 Go 和 Node.js
6.现代化设计:充分利用 Python 3.7+ 的新特性
二、FastAPI开发环境配置
2.1 环境准备
系统要求:
●建议使用Python 3.12
●pip 包管理器
2.2 安装依赖
# 创建虚拟环境(推荐)
python -m venv venv
source venv/bin/activate # Linux/Mac
# 或
venv\Scripts\activate # Windows
# 安装 FastAPI 和 Uvicorn
pip install fastapi uvicorn[standard]
# 安装项目依赖
pip install tortoise-orm aiosqlite # ORM 和数据库
pip install pydantic pydantic-settings # 数据验证和配置
pip install chromadb # 向量数据库
pip install crewai # Agent 框架
pip install python-multipart # 文件上传支持
2.3 项目结构
FastAPI项目有这着其简洁清晰和可维护的项目结构,强烈推荐的最佳实践的项目结构如下:
XMaster/
├── backend/ # 后端项目
│ ├── main.py # FastAPI 应用入口
│ ├── base/ # 基础模块
│ │ ├── config.py # 配置管理
│ │ ├── db_action.py # 数据库操作
│ │ ├── embedding_vector.py # 向量嵌入
│ │ └── logger_config.py # 日志配置
│ ├── models/ # 数据模型
│ │ ├── user.py
│ │ ├── knowledge.py
│ │ └── test_case.py
│ ├── schemas/ # Pydantic 模式
│ ├── api/ # API 路由
│ ├── agents/ # Agent 智能体
│ │ ├── case_generator_agent.py
│ │ └── rag_retrieval_agent.py
│ ├── services/ # 业务逻辑
│ └── data/ # 数据存储
│ ├── sys-sqlite.db # SQLite 数据库
│ └── vector_db/ # ChromaDB 向量库
└── vue-front/ # 前端项目
├── src/
│ ├── views/ # 页面组件
│ ├── components/ # 通用组件
│ ├── stores/ # Pinia 状态管理
│ └── api/ # API 接口
└── package.json
![]()
三、FastAPI实战
3.1 最简FastAPI应用示例
import uvicorn
# 导入FastAPI类
from fastapi import FastAPI
# 创建FastAPI实例,实例名自定义
FastApp = FastAPI()
@FastApp.get("/")
async def root():
return {"message": "Hello World"}
@FastApp.get("/hello/{name}")
async def say_hello(name: str):
return {"message": f"Hello {name}"}
if __name__ == "__main__":
uvicorn.run("main:FastApp", host="0.0.0.0", port=8000, reload=True)
运行应用:
python main.py
访问http://localhost:8000,我们会看到:
{"message": "Hello World"}
访问http://localhost:8000/hello/FastAPI,我们会看到:
{"message": "Hello FastAPI"}
FastAPI 的核心特性解析:
1. 自动生成交互式 API 文档
●访问http://localhost:8000/docs,我们会看到自动生成的Swagger UI文档:
![]()
●访问http://localhost:8000/redoc,会看到ReDoc风格的文档。
2. 类型提示和自动验证
@FastApp.get("/hello/{name}")
async def say_hello(name: str): # 类型提示:name 必须是字符串
return {"message": f"Hello {name}"}
FastAPI 会自动完成下述事务:
●验证 name 是否为字符串
●在文档中显示参数类型
●提供编辑器自动补全
3. 异步支持
@FastApp.get("/")
async def root(): # 使用 async 关键字
return {"message": "Hello World"}
●使用 async def 定义异步路由
●支持 await 调用异步函数
●充分利用 Python 异步特性,提升并发性能
4. 自动 JSON 序列化
FastAPI 自动将 Python 字典转换为 JSON 响应,无需手动序列化。
3.2 FastAPI 应用类
FastAPI 应用类是整个应用的核心,负责路由注册、中间件配置、生命周期管理等。
创建 FastAPI 实例
from fastapi import FastAPI
from contextlib import asynccontextmanager
@asynccontextmanager
async def lifespan(app: FastAPI):
"""应用生命周期管理"""
# 启动时执行
print("应用启动中...")
await init_database() # 初始化数据库
yield # 应用运行中
# 关闭时执行
print("应用关闭中...")
await close_database() # 关闭数据库连接
# 创建 FastAPI 应用实例
app = FastAPI(
title="XAuto智能体平台",
version="1.0.0",
description="基于 FastAPI + CrewAI 的测试用例生成平台",
lifespan=lifespan # 生命周期管理
)
FastAPI 实例参数说明:
![]()
配置 CORS 中间件
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # 允许的源
allow_credentials=True,
allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allow_headers=["*"],
)
全局异常处理
from fastapi import Request, HTTPException
from fastapi.responses import JSONResponse
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
"""HTTP 异常处理器"""
returnJSONResponse(
status_code=exc.status_code,
content={"message": exc.detail}
)
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
"""全局异常处理器"""
returnJSONResponse(
status_code=500,
content={"message": f"服务器内部错误: {str(exc)}"}
)
3.3 FastAPI的请求路由系统
3.3.1 路由参数
路由参数(Path Parameters)是 URL 路径的一部分。
from fastapi import Path
@app.get("/items/{item_id}")
async def read_item(
item_id: int = Path(..., title="商品ID", ge=1, le=1000)
):
"""
获取商品信息
- item_id: 商品ID,范围 1-1000
"""
return{"item_id": item_id, "name": f"商品{item_id}"}
路径参数验证:
![]()
3.3.2 查询参数
查询参数(Query Parameters)是URL中?后面的参数。
from fastapi import Query
from typing import Optional, List
@app.get("/search")
async def search_items(
q: str = Query(..., min_length=1, max_length=50, description="搜索关键词"),
page: int = Query(1, ge=1, description="页码"),
size: int = Query(10, ge=1, le=100, description="每页数量"),
tags: Optional[List[str]] = Query(None, description="标签列表")
):
"""
搜索商品
- q: 搜索关键词(必填)
- page: 页码(默认 1)
- size: 每页数量(默认 10,最大 100)
- tags: 标签列表(可选)
"""
return{
"query": q,
"page": page,
"size": size,
"tags": tags or []
}
示例请求:
GET /search?q=FastAPI&page=1&size=20&tags=python&tags=web
3.3.3 请求体
使用 Pydantic 模型定义请求体。
from pydantic import BaseModel, Field
from typing import Optional
class Item(BaseModel):
"""商品模型"""
name: str = Field(..., min_length=1, max_length=100, description="商品名称")
description: Optional[str] = Field(None, max_length=500, description="商品描述")
price: float = Field(..., gt=0, description="商品价格")
tax: Optional[float] = Field(None, ge=0, description="税费")
@app.post("/items")
async def create_item(item: Item):
"""
创建商品
"""
item_dict = item.model_dump()
if item.tax:
price_with_tax = item.price + item.tax
item_dict.update({"price_with_tax": price_with_tax})
return item_dict
示例请求:
POST /items
Content-Type: application/json
{
"name": "FastAPI 教程",
"description": "一本关于 FastAPI 的书",
"price": 99.99,
"tax": 10.0
}
Pydantic 模型的优势:
●自动数据验证
●自动生成 JSON Schema
●自动生成 API 文档
●类型提示和编辑器支持
3.3.4 Form表单数据
处理 HTML 表单提交的数据。
from fastapi import Form
@app.post("/login")
async def login(
username: str = Form(..., min_length=3, max_length=50),
password: str = Form(..., min_length=6)
):
"""
用户登录
"""
return {"username": username, "message": "登录成功"}
示例请求:
POST /login
Content-Type: application/x-www-form-urlencoded
username=admin&password=123456
3.3.5 文件上传
FastAPI 支持单文件和多文件上传。
from fastapi import File, UploadFile
from typing import List
import shutil
@app.post("/upload")
async def upload_file(file: UploadFile = File(...)):
"""
单文件上传
"""
# 保存文件
file_path = f"./uploads/{file.filename}"
with open(file_path, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
return{
"filename": file.filename,
"content_type": file.content_type,
"size": file.size
}
@app.post("/upload-multiple")
async def upload_multiple_files(files: List[UploadFile] = File(...)):
"""
多文件上传
"""
uploaded_files = []
for file in files:
file_path = f"./uploads/{file.filename}"
with open(file_path, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
uploaded_files.append({
"filename": file.filename,
"size": file.size
})
return {"files": uploaded_files}
☑️转岗软件测试/野路子技能提升
☑️想了解更多涨薪技能提升方法
✔️可以到我的个人号:atstudy-js
即可加入领取 ⬇️⬇️⬇️
转行、入门、提升、需要的各种干货资料
内含AI测试、 车载测试、AI大模型开发、BI数据分析、银行测试、游戏测试、AIGC
特别声明:以上内容(如有图片或视频亦包括在内)为自媒体平台“网易号”用户上传并发布,本平台仅提供信息存储服务。
Notice: The content above (including the pictures and videos if any) is uploaded and posted by a user of NetEase Hao, which is a social media platform and only provides information storage services.