FastAPI 入門:為什么選擇 FastAPI?它比 Flask 強(qiáng)在哪里?
FastAPI 是什么?
FastAPI[1] 是一個(gè)基于 Python 3.7+ 的現(xiàn)代化 異步 Web 框架,適用于構(gòu)建 高性能 API。它具有以下特點(diǎn):
- 超快性能(接近 Node.js 和 Go)
- 自動生成文檔(Swagger & ReDoc)
- Pydantic 強(qiáng)類型數(shù)據(jù)驗(yàn)證
- 異步支持(async/await),天生適合高并發(fā)任務(wù)
- 與 Flask 語法相似,上手簡單
FastAPI = Flask + Pydantic + 自動文檔 + 超快性能。
FastAPI vs Flask:到底哪個(gè)好?
?? 對比項(xiàng) | ?? FastAPI | ?? Flask |
性能 | 異步支持,超快 (比 Flask 快 3~5 倍) | 同步阻塞 ,性能相對較低 |
類型檢查 | Pydantic 強(qiáng)類型驗(yàn)證,減少錯(cuò)誤 | 手動解析請求數(shù)據(jù),易出錯(cuò) |
自動文檔 | 內(nèi)置 Swagger 和 ReDoc | 需手動集成 Swagger |
異步支持 | 天生支持 async/await,高并發(fā)任務(wù)不阻塞 | 需要手動使用線程池或協(xié)程 |
學(xué)習(xí)成本 | 比 Flask 略高,但上手快 | 語法簡單,適合初學(xué)者 |
適用場景 | 高性能 API、微服務(wù)、異步應(yīng)用 | 小型 Web 項(xiàng)目、簡單 API |
結(jié)論:
- 想要極致性能?→ 選 FastAPI!
- 項(xiàng)目簡單,團(tuán)隊(duì)習(xí)慣 Flask?→ 選 Flask!
- 未來趨勢?→ FastAPI 正在取代 Flask!
快速上手:第一個(gè) FastAPI API
安裝 FastAPI 和 Uvicorn(服務(wù)器):
pip install fastapi uvicorn
創(chuàng)建 main.py:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "?? Hello, FastAPI!"}
啟動服務(wù):
uvicorn main:app --reload
訪問 API:
- Swagger 文檔 ?? http://127.0.0.1:8000/docs
- ReDoc 文檔 ?? http://127.0.0.1:8000/redoc
?? FastAPI 直接生成交互式 API 文檔,開發(fā)體驗(yàn)超級棒!
FastAPI 的異步支持(async/await)
FastAPI 原生支持異步(async/await),相比 Flask 只能同步處理請求,F(xiàn)astAPI 可以同時(shí)處理多個(gè)請求,避免阻塞,大幅提升性能。
(1) Flask(同步處理)
Flask 處理請求時(shí)是 阻塞的,一個(gè)請求執(zhí)行時(shí),其他請求必須等待:
from flask import Flask
import time
app = Flask(__name__)
@app.route("/")
def slow():
time.sleep(5) # 模擬耗時(shí)任務(wù)
return "Flask 任務(wù)完成!"
app.run(debug=True)
如果有多個(gè)請求,F(xiàn)lask 會一個(gè)個(gè)處理,性能較低。
(2) FastAPI(異步處理)
FastAPI 允許 異步執(zhí)行任務(wù),多個(gè)請求可以同時(shí)執(zhí)行:
from fastapi import FastAPI
import asyncio
app = FastAPI()
@app.get("/")
async def slow():
await asyncio.sleep(5) # 使用 async/await 實(shí)現(xiàn)異步
return {"message": "FastAPI 任務(wù)完成!"}
FastAPI 采用 異步 I/O,多個(gè)請求可以 同時(shí)進(jìn)行,大幅提升響應(yīng)速度!
FastAPI 的多任務(wù)特性(異步并發(fā)處理)
FastAPI 支持多任務(wù)異步執(zhí)行,適用于 I/O 密集型任務(wù),如:
- 多個(gè)數(shù)據(jù)庫查詢(避免阻塞)
- 爬蟲、批量網(wǎng)絡(luò)請求(加速處理)
- 同時(shí)下載多個(gè)文件(并發(fā)提升速度)
(1) 讓多個(gè)任務(wù)同時(shí)執(zhí)行(asyncio.gather)
from fastapi import FastAPI
import asyncio
app = FastAPI()
asyncdeftask_1():
await asyncio.sleep(3)
return"任務(wù) 1 完成"
asyncdeftask_2():
await asyncio.sleep(2)
return"任務(wù) 2 完成"
@app.get("/multi-task")
asyncdefmulti_task():
result = await asyncio.gather(task_1(), task_2()) # 并發(fā)執(zhí)行兩個(gè)任務(wù)
return {"results": result}
解析:
- asyncio.gather(task_1(), task_2()) 會同時(shí)執(zhí)行 task_1() 和 task_2(),而不是順序執(zhí)行
- 執(zhí)行時(shí)間不會疊加,而是取最長的那個(gè)(本例中 3 秒)
- 比同步執(zhí)行快 50%+!
(2) 使用后臺任務(wù)(BackgroundTasks)
FastAPI 提供 BackgroundTasks,適用于不影響主請求的任務(wù)(如發(fā)送郵件、日志記錄):
from fastapi import FastAPI, BackgroundTasks
app = FastAPI()
def write_log(msg: str):
with open("log.txt", "a") as f:
f.write(msg + "\n")
@app.get("/task")
def start_task(background_tasks: BackgroundTasks):
background_tasks.add_task(write_log, "異步任務(wù)執(zhí)行!")
return {"message": "任務(wù)已提交"}
解析:
- background_tasks.add_task(write_log, "異步任務(wù)執(zhí)行!") 不會阻塞主請求
- 請求立即返回 "任務(wù)已提交",而后臺任務(wù) write_log() 繼續(xù)運(yùn)行
適用于日志、郵件、緩存更新等場景!
FastAPI 的核心功能
- 路由(GET, POST, PUT, DELETE)
- 路徑參數(shù) & 查詢參數(shù)
- 數(shù)據(jù)驗(yàn)證(Pydantic)
- 依賴注入(Depends)
- 數(shù)據(jù)庫支持(SQLAlchemy, Tortoise-ORM)
- JWT 認(rèn)證 & OAuth2
- WebSockets & 背景任務(wù)
- Docker & 部署優(yōu)化
什么時(shí)候選擇 FastAPI?
如果你的項(xiàng)目需要:
- 高并發(fā)、異步處理(如爬蟲、微服務(wù)、實(shí)時(shí)數(shù)據(jù))
- 自動生成 API 文檔,快速對接前端
- 更嚴(yán)格的數(shù)據(jù)驗(yàn)證,減少錯(cuò)誤
- 更快的響應(yīng)速度(比 Flask 快 3~5 倍)
那么 FastAPI 是你的最佳選擇!
結(jié)論:FastAPI 是未來!
Flask 適合簡單項(xiàng)目,但 FastAPI 更現(xiàn)代化、更快、更強(qiáng)大,已經(jīng)成為 Python Web 開發(fā)的新寵。