最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

從入門到生產(chǎn)詳解Python中FastAPI的全攻略

 更新時(shí)間:2026年05月30日 10:07:17   作者:xiaoyu?  
在 Python Web 開發(fā)領(lǐng)域,FastAPI 正以驚人的速度崛起,本文將從零開始,帶你全面掌握 FastAPI 的核心知識(shí)點(diǎn),從環(huán)境搭建到生產(chǎn)部署,一次講清楚

引言:Python Web 開發(fā)的新寵兒

在 Python Web 開發(fā)領(lǐng)域,F(xiàn)astAPI 正以驚人的速度崛起。截至 2025 年,F(xiàn)astAPI 在 GitHub 上的 Star 數(shù)已突破 80k,成為增長最快的 Python Web 框架。根據(jù)統(tǒng)計(jì),2025 年已有 38% 的 Python 開發(fā)者在使用 FastAPI(較 2024 年增長 40%),超過一半的財(cái)富 500 強(qiáng)企業(yè)也在生產(chǎn)環(huán)境中部署了 FastAPI 應(yīng)用。

那么,是什么讓 FastAPI 如此受歡迎?本文將從零開始,帶你全面掌握 FastAPI 的核心知識(shí)點(diǎn),從環(huán)境搭建到生產(chǎn)部署,一次講清楚。

一、FastAPI 是什么

FastAPI 是一個(gè)用于構(gòu)建 API 的現(xiàn)代、高性能 Web 框架,基于 Python 3.7+ 的類型提示。它的核心架構(gòu)建立在兩個(gè)強(qiáng)大的底層庫之上:Starlette(高性能 ASGI 框架)和 Pydantic(高性能數(shù)據(jù)校驗(yàn)庫)。

1.1 核心特性

特性描述
高性能基于 Starlette + Pydantic,性能可媲美 Node.js 和 Go
自動(dòng) API 文檔內(nèi)置 Swagger UI(/docs)和 ReDoc(/redoc
類型提示驅(qū)動(dòng)利用 Python 類型注解自動(dòng)校驗(yàn)請(qǐng)求和響應(yīng)
原生異步支持完全支持 async/await,適合高并發(fā) I/O 場景
依賴注入系統(tǒng)靈活的 Depends 機(jī)制,支持權(quán)限校驗(yàn)、數(shù)據(jù)庫會(huì)話管理等

1.2 FastAPI 架構(gòu):ASGI + Pydantic

FastAPI 通過 ASGI 異步框架突破了傳統(tǒng) WSGI(如 Flask、Django)同步阻塞模型的性能天花板。實(shí)測數(shù)據(jù)顯示,F(xiàn)astAPI 單節(jié)點(diǎn) QPS 可達(dá) 3000+,約為 Flask 的 5-8 倍。

下面是 FastAPI 請(qǐng)求處理的整體流程:

二、環(huán)境搭建與第一個(gè) FastAPI 應(yīng)用

2.1 安裝依賴

確保你的 Python 版本 ≥ 3.7,推薦使用虛擬環(huán)境隔離項(xiàng)目依賴:

# 創(chuàng)建并激活虛擬環(huán)境
python -m venv fastapi_env
source fastapi_env/bin/activate  # Linux/macOS
# 或 fastapi_env\Scripts\activate  # Windows

# 安裝 FastAPI 和 Uvicorn(ASGI 服務(wù)器)
pip install fastapi uvicorn[standard]

2.2 第一個(gè) Hello World 應(yīng)用

創(chuàng)建一個(gè) main.py 文件:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def read_root():
    return {"message": "Hello, FastAPI!"}

運(yùn)行服務(wù):

uvicorn main:app --reload --host 0.0.0.0 --port 8000

  • --reload:代碼變更時(shí)自動(dòng)重啟,便于開發(fā)調(diào)試
  • --host 0.0.0.0:允許外部訪問(僅本地開發(fā))
  • --port 8000:指定端口

現(xiàn)在打開瀏覽器訪問 http://localhost:8000,你會(huì)看到返回的 JSON 數(shù)據(jù)。再訪問 http://localhost:8000/docs,你會(huì)驚喜地發(fā)現(xiàn) Swagger UI 自動(dòng)生成了交互式 API 文檔——無需編寫任何額外的文檔代碼。

三、路由與請(qǐng)求參數(shù)

3.1 請(qǐng)求處理的完整流程

在深入各種參數(shù)之前,我們先理解 FastAPI 的請(qǐng)求處理流程:

3.2 路徑參數(shù)

路徑參數(shù)直接從 URL 路徑中提取:

from fastapi import FastAPI

app = FastAPI()

@app.get("/users/{user_id}")
async def get_user(user_id: int):
    return {"user_id": user_id}

FastAPI 會(huì)自動(dòng)將 user_id 轉(zhuǎn)換為 int 類型,如果傳入非數(shù)字值會(huì)自動(dòng)返回 422 校驗(yàn)錯(cuò)誤。

3.3 查詢參數(shù)

查詢參數(shù)通過函數(shù)參數(shù)的默認(rèn)值或 Query 類來定義:

from fastapi import FastAPI, Query

@app.get("/items/")
async def read_items(
    item_id: int = Query(..., description="商品ID", ge=1),
    q: str = None,
    limit: int = Query(10, ge=1, le=100)
):
    return {"item_id": item_id, "q": q, "limit": limit}
  • Query(...) 中的 ... 表示必填參數(shù)
  • ge/le 表示數(shù)值的最小/最大約束
  • description 會(huì)在自動(dòng)文檔中展示參數(shù)說明

3.4 請(qǐng)求體與 Pydantic 模型

對(duì)于 POST、PUT 請(qǐng)求,使用 Pydantic 模型來定義和校驗(yàn)請(qǐng)求體:

from fastapi import FastAPI
from pydantic import BaseModel, Field

app = FastAPI()

class Item(BaseModel):
    name: str = Field(..., min_length=1, max_length=100)
    description: str | None = None
    price: float = Field(..., gt=0, description="價(jià)格必須大于0")
    tax: float | None = None
    
    # Pydantic v2 支持 model_config 進(jìn)行額外配置
    model_config = {
        "json_schema_extra": {
            "example": {
                "name": "iPhone 15",
                "description": "最新款智能手機(jī)",
                "price": 6999.0,
                "tax": 699.9
            }
        }
    }

@app.post("/items/")
async def create_item(item: Item):
    item_dict = item.model_dump()  # Pydantic v2 使用 model_dump 替代 dict
    if item.tax:
        price_with_tax = item.price + item.tax
        item_dict["price_with_tax"] = price_with_tax
    return item_dict

Pydantic 在運(yùn)行時(shí)自動(dòng)完成:

  • 字段類型檢查(如 price 必須為浮點(diǎn)數(shù))
  • 必填/可選字段控制
  • 數(shù)值范圍約束
  • 嵌套模型支持

3.5 路由分組(APIRouter)

對(duì)于大型項(xiàng)目,使用 APIRouter 進(jìn)行模塊化拆分:

from fastapi import APIRouter, FastAPI

# 創(chuàng)建路由模塊
user_router = APIRouter(prefix="/users", tags=["users"])
item_router = APIRouter(prefix="/items", tags=["items"])

@user_router.get("/{user_id}")
async def get_user(user_id: int):
    return {"user_id": user_id}

@item_router.get("/")
async def list_items():
    return {"items": []}

# 注冊(cè)到主應(yīng)用
app = FastAPI()
app.include_router(user_router)
app.include_router(item_router)

APIRouter 支持 prefix(路徑前綴)、tags(文檔分組標(biāo)簽)、responses(統(tǒng)一響應(yīng)格式)等配置,非常適合微服務(wù)架構(gòu)的模塊拆分。

四、依賴注入(Depends)

依賴注入是 FastAPI 最強(qiáng)大的特性之一。它的本質(zhì)是通過外部傳入依賴對(duì)象,而非在函數(shù)內(nèi)部直接創(chuàng)建,從而將依賴管理從業(yè)務(wù)邏輯中解耦。

4.1 依賴注入的工作原理

4.2 基礎(chǔ)函數(shù)依賴

from fastapi import FastAPI, Depends

app = FastAPI()

# 定義一個(gè)可復(fù)用的依賴函數(shù)
def get_current_user(token: str = "fake_token"):
    # 實(shí)際項(xiàng)目中會(huì)從 Header 或 Cookie 中解析 token
    return {"username": "john_doe", "role": "admin"}

@app.get("/profile")
async def read_profile(user: dict = Depends(get_current_user)):
    return {"message": f"Hello, {user['username']}!"}

4.3 數(shù)據(jù)庫連接依賴

這是依賴注入最經(jīng)典的應(yīng)用場景——管理數(shù)據(jù)庫會(huì)話生命周期:

from sqlalchemy.orm import Session
from database import SessionLocal

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()  # 請(qǐng)求結(jié)束后自動(dòng)關(guān)閉連接

@app.get("/users/")
async def read_users(db: Session = Depends(get_db)):
    return db.query(User).all()

yield 關(guān)鍵字讓 FastAPI 能夠在請(qǐng)求處理完畢后執(zhí)行 finally 塊中的清理代碼,優(yōu)雅地管理資源生命周期。

4.4 依賴鏈與緩存

from functools import lru_cache

# 使用 lru_cache 緩存昂貴資源,避免重復(fù)創(chuàng)建
@lru_cache()
def get_settings():
    # 模擬從配置文件或環(huán)境變量加載
    return {"debug": True, "database_url": "..."}

def get_db(settings: dict = Depends(get_settings)):
    db_url = settings["database_url"]
    # 創(chuàng)建數(shù)據(jù)庫連接...
    return db

@app.get("/config")
async def read_config(settings: dict = Depends(get_settings)):
    return settings

使用 @lru_cache 裝飾的依賴在整個(gè)應(yīng)用生命周期中只會(huì)執(zhí)行一次,適合配置加載、模型加載等場景。

五、中間件與 CORS 跨域

5.1 中間件的執(zhí)行流程

5.2 CORS 中間件配置

前后端分離項(xiàng)目中,CORS 跨域問題是必須要解決的:

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

# 開發(fā)環(huán)境:允許所有來源
origins = ["*"]

# 生產(chǎn)環(huán)境:精確控制
origins = [
    "https://yourdomain.com",
    "https://admin.yourdomain.com",
    "http://localhost:3000",  # 本地開發(fā)
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,  # 允許攜帶 Cookie
    allow_methods=["GET", "POST", "PUT", "DELETE"],
    allow_headers=["Content-Type", "Authorization"],
    max_age=86400,  # 預(yù)檢請(qǐng)求緩存 24 小時(shí)
)

關(guān)鍵注意點(diǎn):當(dāng) allow_credentials=True 時(shí),allow_origins 不能使用 ["*"],必須明確列出允許的來源列表。

5.3 自定義中間件

from fastapi import Request
import time

@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    start_time = time.time()
    response = await call_next(request)
    process_time = time.time() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    return response

六、數(shù)據(jù)庫集成(SQLAlchemy 2.0 異步)

FastAPI 的異步特性與 SQLAlchemy 2.0 的異步支持是天作之合。傳統(tǒng)同步 ORM 在高并發(fā)場景下會(huì)成為性能瓶頸,而異步 ORM 可以在等待數(shù)據(jù)庫響應(yīng)的 I/O 空閑期處理其他請(qǐng)求,極大提升并發(fā)能力。

6.1 異步數(shù)據(jù)庫架構(gòu)

6.2 配置異步引擎

首先安裝依賴:

pip install sqlalchemy asyncpg alembic

配置異步引擎和會(huì)話工廠:

from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from sqlalchemy.orm import DeclarativeBase

# PostgreSQL 異步驅(qū)動(dòng) URL
DATABASE_URL = "postgresql+asyncpg://user:password@localhost/dbname"

# 創(chuàng)建異步引擎
engine = create_async_engine(
    DATABASE_URL,
    echo=True,          # 開發(fā)時(shí)打印 SQL
    future=True,        # 使用 2.0 風(fēng)格 API
    pool_size=10,       # 連接池大小
    max_overflow=20,    # 最大溢出連接數(shù)
)

# 創(chuàng)建異步會(huì)話工廠
AsyncSessionLocal = async_sessionmaker(
    bind=engine,
    class_=AsyncSession,
    expire_on_commit=False,  # commit 后不使屬性過期
    autocommit=False,
    autoflush=False,
)

# 定義模型基類
class Base(DeclarativeBase):
    pass

expire_on_commit=False 是一個(gè)重要的性能優(yōu)化配置——在 Web 請(qǐng)求上下文中,我們通常在請(qǐng)求結(jié)束時(shí)就丟棄會(huì)話,無需讓屬性過期后再查詢。

6.3 異步依賴注入

from fastapi import Depends

async def get_db() -> AsyncSession:
    async with AsyncSessionLocal() as session:
        try:
            yield session
            await session.commit()
        except Exception:
            await session.rollback()
            raise
        # async with 上下文會(huì)自動(dòng)關(guān)閉 session

@app.get("/users/")
async def list_users(db: AsyncSession = Depends(get_db)):
    from sqlalchemy import select
    result = await db.execute(select(User))
    return result.scalars().all()

@app.post("/users/")
async def create_user(user_data: UserCreate, db: AsyncSession = Depends(get_db)):
    new_user = User(**user_data.model_dump())
    db.add(new_user)
    await db.flush()  # 獲取數(shù)據(jù)庫生成的 ID
    await db.refresh(new_user)
    return new_user

七、測試與部署

7.1 使用 TestClient 進(jìn)行單元測試

FastAPI 提供了 TestClient,它基于 httpx,可以模擬 HTTP 請(qǐng)求而無需真正啟動(dòng)服務(wù)器:

# test_main.py
from fastapi.testclient import TestClient
from main import app

client = TestClient(app)

def test_read_root():
    response = client.get("/")
    assert response.status_code == 200
    assert response.json() == {"message": "Hello, FastAPI!"}

運(yùn)行測試:

pip install pytest httpx
pytest test_main.py -v

7.2 依賴覆蓋——數(shù)據(jù)庫測試的殺手锏

FastAPI 的 dependency_overrides 是測試數(shù)據(jù)庫相關(guān) API 的利器。你可以將真實(shí)的數(shù)據(jù)庫依賴替換為 SQLite 內(nèi)存數(shù)據(jù)庫,實(shí)現(xiàn)“跑完即焚”:

from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from main import app, get_db

# 創(chuàng)建內(nèi)存數(shù)據(jù)庫
SQLALCHEMY_DATABASE_URL = "sqlite:///:memory:"
engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False})
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

def override_get_db():
    try:
        db = TestingSessionLocal()
        yield db
    finally:
        db.close()

# 覆蓋真實(shí)依賴
app.dependency_overrides[get_db] = override_get_db

client = TestClient(app)

def test_create_user():
    response = client.post("/users/", json={"name": "test", "email": "test@example.com"})
    assert response.status_code == 200

7.3 生產(chǎn)部署建議

生產(chǎn)環(huán)境部署命令示例:

# 使用 Gunicorn 管理 Uvicorn 多進(jìn)程
gunicorn main:app \
    --workers 4 \
    --worker-class uvicorn.workers.UvicornWorker \
    --bind 0.0.0.0:8000 \
    --access-logfile - \
    --error-logfile -

八、總結(jié)

FastAPI 憑借其類型提示驅(qū)動(dòng)、自動(dòng)文檔生成、異步高性能、依賴注入系統(tǒng)四大核心優(yōu)勢(shì),已經(jīng)成為 Python Web 開發(fā)的主流框架選擇。

本文從零開始,涵蓋了 FastAPI 的核心知識(shí)點(diǎn):

  • 環(huán)境搭建與基礎(chǔ)應(yīng)用
  • 路由設(shè)計(jì)與請(qǐng)求參數(shù)處理
  • Pydantic 數(shù)據(jù)驗(yàn)證
  • 依賴注入(Depends)系統(tǒng)
  • 中間件與 CORS 配置
  • SQLAlchemy 2.0 異步數(shù)據(jù)庫集成
  • 測試與生產(chǎn)部署

掌握這些內(nèi)容,你已經(jīng)可以獨(dú)立開發(fā)一個(gè)生產(chǎn)級(jí)別的 FastAPI 應(yīng)用了。接下來,你可以進(jìn)一步學(xué)習(xí) FastAPI 的高級(jí)特性,如 WebSocket 支持、后臺(tái)任務(wù)(BackgroundTasks)、自定義異常處理等,讓你的 FastAPI 技能更加全面。

以上就是從入門到生產(chǎn)詳解Python中FastAPI的全攻略的詳細(xì)內(nèi)容,更多關(guān)于Python FastAPI教學(xué)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • python使用xlrd模塊讀取excel的方法實(shí)例

    python使用xlrd模塊讀取excel的方法實(shí)例

    Python讀取Excel表格,相比xlwt來說,xlrd提供的接口比較多,下面這篇文章主要給大家介紹了關(guān)于python使用xlrd模塊讀取excel的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2022-03-03
  • pandas中Series的使用方式

    pandas中Series的使用方式

    這篇文章主要介紹了pandas中Series的使用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-09-09
  • Python mlxtend庫數(shù)據(jù)科學(xué)和機(jī)器學(xué)習(xí)補(bǔ)充工具功能探索

    Python mlxtend庫數(shù)據(jù)科學(xué)和機(jī)器學(xué)習(xí)補(bǔ)充工具功能探索

    這篇文章主要介紹了Python mlxtend庫數(shù)據(jù)科學(xué)和機(jī)器學(xué)習(xí)補(bǔ)充工具功能探索,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2024-01-01
  • 一文帶你了解Python中的枚舉(enum)

    一文帶你了解Python中的枚舉(enum)

    這篇文章一文帶你了解Python中的枚舉(enum),在Python中,枚舉和我們?cè)趯?duì)象中定義的類變量時(shí)一樣的,每一個(gè)類變量就是一個(gè)枚舉項(xiàng),需要的朋友可以參考下
    2023-04-04
  • 吃透Python函數(shù)從基礎(chǔ)語法到實(shí)戰(zhàn)技巧(最新推薦)

    吃透Python函數(shù)從基礎(chǔ)語法到實(shí)戰(zhàn)技巧(最新推薦)

    文章介紹了Python函數(shù)的基礎(chǔ)語法和進(jìn)階用法,包括函數(shù)的定義、調(diào)用、復(fù)用以及參數(shù)的靈活傳遞和返回值的處理,通過理解函數(shù)的概念和實(shí)踐,可以編寫更簡潔、可維護(hù)的代碼,本文給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧
    2026-01-01
  • 使用Python生成XML的方法實(shí)例

    使用Python生成XML的方法實(shí)例

    這篇文章主要介紹了使用Python生成XML的方法,結(jié)合具體實(shí)例形式詳細(xì)分析了Python生成xml文件的具體流暢與相關(guān)注意事項(xiàng),需要的朋友可以參考下
    2017-03-03
  • 妙用itchat! python實(shí)現(xiàn)久坐提醒功能

    妙用itchat! python實(shí)現(xiàn)久坐提醒功能

    python編寫的久坐提醒,給最愛的那個(gè)她,這篇文章主要為大家分享了python久坐提醒功能的實(shí)現(xiàn)代碼,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2019-11-11
  • Python實(shí)現(xiàn)Pig Latin小游戲?qū)嵗a

    Python實(shí)現(xiàn)Pig Latin小游戲?qū)嵗a

    這篇文章主要介紹了Python實(shí)現(xiàn)Pig Latin小游戲?qū)嵗a,分享了相關(guān)代碼示例,小編覺得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下
    2018-02-02
  • Python實(shí)現(xiàn)爬取網(wǎng)頁中動(dòng)態(tài)加載的數(shù)據(jù)

    Python實(shí)現(xiàn)爬取網(wǎng)頁中動(dòng)態(tài)加載的數(shù)據(jù)

    這篇文章主要介紹了Python實(shí)現(xiàn)爬取網(wǎng)頁中動(dòng)態(tài)加載的數(shù)據(jù),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-08-08
  • 利用python調(diào)用攝像頭的實(shí)例分析

    利用python調(diào)用攝像頭的實(shí)例分析

    在本篇文章里小編給大家整理了一篇關(guān)于利用python調(diào)用攝像頭的實(shí)例分析內(nèi)容,有需要的朋友們跟著參考下。
    2021-06-06

最新評(píng)論

和田市| 虹口区| 连云港市| 南乐县| 泗阳县| 呼图壁县| 小金县| 雷波县| 乌兰浩特市| 新蔡县| 延寿县| 巫山县| 岑巩县| 财经| 合作市| 丽江市| 临漳县| 马龙县| 辽阳市| 大冶市| 临海市| 九台市| 宜黄县| 南漳县| 九江县| 青冈县| 垣曲县| 汨罗市| 连江县| 舞钢市| 徐水县| 扎囊县| 七台河市| 侯马市| 芜湖市| 堆龙德庆县| 莒南县| 盖州市| 济源市| 渭源县| 宣汉县|