一、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.