偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

FastAPI, 一個(gè)神奇的 Python 庫(kù)

開(kāi)發(fā) 數(shù)據(jù)庫(kù)
FastAPI 是一個(gè)用于構(gòu)建 API 的現(xiàn)代、快速(高性能)的 web 框架,使用 Python 并基于標(biāo)準(zhǔn)的 Python類(lèi)型提示。

FastAPI 是一個(gè)用于構(gòu)建 API 的現(xiàn)代、快速(高性能)的 web 框架,使用 Python 并基于標(biāo)準(zhǔn)的 Python類(lèi)型提示。

安裝

安裝 FastAPI 很簡(jiǎn)單,這里我們使用 pip 命令來(lái)安裝。

pip install fastapi

另外我們還需要一個(gè) ASGI 服務(wù)器,生產(chǎn)環(huán)境可以使用 Uvicorn 或者 Hypercorn

pip install uvicorn[standard]

資料:

  • FastAPI 文檔:https://fastapi.tiangolo.com/zh/
  • FastAPI 源碼:https://github.com/tiangolo/fastapi

簡(jiǎn)單示例

# main.py

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}

啟動(dòng)服務(wù):

uvicorn main:app --reload
  • --reload:開(kāi)發(fā)時(shí)自動(dòng)重載(生產(chǎn)環(huán)境移除)
  • 訪(fǎng)問(wèn):http://localhost:8000

關(guān)鍵功能

(1) 路徑參數(shù)和查詢(xún)參數(shù)

  • {user_id}:路徑參數(shù)(必須)
  • limit 和 skip:查詢(xún)參數(shù)(可選,帶默認(rèn)值)
@app.get("/users/{user_id}")
async def read_user(user_id: int, 
                    limit: int = 10, 
                    skip: int = 0):
  return {"user_id": user_id, "limit": limit, "skip": skip}

(2) 請(qǐng)求體(POST/PUT)

使用 Pydantic 模型驗(yàn)證數(shù)據(jù):

from pydantic import BaseModel

class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None

@app.post("/items/")
async def create_item(item: Item):
    return {"item": item.dict()}

(3) 自動(dòng)文檔

  • Swagger UI:http://localhost:8000/docs
  • ReDoc:http://localhost:8000/redoc

(4) 異步支持

@app.get("/slow-endpoint")
async def slow_operation():
    # 如數(shù)據(jù)庫(kù)查詢(xún)
    await some_async_task() 
    return {"status": "done"}

進(jìn)階功能

(1) 依賴(lài)注入

復(fù)用代碼邏輯(如認(rèn)證、數(shù)據(jù)庫(kù)連接)。

from fastapi import Depends

def common_params(q: str = None, skip: int = 0, limit: int = 100):
    return {"q": q, "skip": skip, "limit": limit}

@app.get("/items/")
async def read_items(commons: dict = Depends(common_params)):
    return commons

(2) 中間件

處理請(qǐng)求前/后的邏輯(如 CORS、日志)。

from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
)

(3) WebSocket 支持

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    while True:
        data = await websocket.receive_text()
        await websocket.send_text(f"Message: {data}")

(4) 后臺(tái)任務(wù)

執(zhí)行無(wú)需即時(shí)響應(yīng)的操作(如發(fā)送郵件、短信)

from fastapi import BackgroundTasks

def log_task(message: str):
    with open("log.txt", "a") as f:
        f.write(message)

@app.post("/send-email")
async def send_email(background_tasks: BackgroundTasks):
    background_tasks.add_task(log_task, "Email sent")
    return {"status": "ok"}

適用場(chǎng)景

  • 構(gòu)建高性能 REST API
  • 微服務(wù)后端
  • 實(shí)時(shí)應(yīng)用(WebSocket)
  • 結(jié)合sqlalchemy進(jìn)行 web 開(kāi)發(fā)
責(zé)任編輯:趙寧寧 來(lái)源: 程序員老朱
相關(guān)推薦

2025-06-04 08:05:00

Peewee?數(shù)據(jù)庫(kù)開(kāi)發(fā)

2025-08-01 09:07:00

RapidFuzz字符串匹配庫(kù)Python

2025-06-10 08:00:00

Pygalpython庫(kù)

2025-05-29 10:00:00

ZODBPython數(shù)據(jù)庫(kù)

2025-08-01 06:15:00

RQPython庫(kù)

2025-06-05 10:00:00

GensimPython庫(kù)

2025-06-09 07:25:00

filelock庫(kù)數(shù)據(jù)庫(kù)

2025-06-04 10:05:00

Gooey開(kāi)源Python

2025-05-27 08:00:00

Pythonemoji庫(kù)

2025-06-05 08:10:00

PyneconePythonWeb 應(yīng)用

2024-04-01 05:00:00

GUIpythonDearPyGui

2025-05-28 08:00:00

Pythonpython-jos開(kāi)發(fā)

2025-06-03 10:00:00

LiteLLMPython庫(kù)

2014-04-23 11:11:27

Linux下載管理器uGet

2025-06-03 08:30:00

PotteryRedisPython

2020-06-08 07:52:31

Python開(kāi)發(fā)工具

2023-01-16 18:16:49

CinnamonLinux桌面環(huán)境

2011-11-02 12:38:12

華為華為ARG3

2023-11-28 14:22:54

Python音頻

2022-07-21 09:50:20

Python日期庫(kù)pendulum
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)