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

一文帶你搞懂Python?FastAPI中所有核心參數(shù)的設置

 更新時間:2025年12月31日 09:02:18   作者:曲幽  
本文帶你一次搞懂?FastAPI?中的所有核心參數(shù)類型,從簡單的查詢字符串,再到處理復雜?JSON?或表單數(shù)據(jù)的請求體,感興趣的小伙伴可以了解下

本文帶你一次搞懂 FastAPI 中的所有核心參數(shù)類型:從簡單的查詢字符串(?name=value),到定義URL片段的路徑參數(shù),再到處理復雜 JSON 或表單數(shù)據(jù)的請求體。重點深入 Pydantic BaseModel,教你如何用它優(yōu)雅地定義、驗證和組織復雜數(shù)據(jù),并自動生成 API 文檔。讀完你就能清晰地規(guī)劃 API 的數(shù)據(jù)接口了。

 查詢參數(shù)與路徑參數(shù):地基要打牢

這是兩種最基礎、最常用的參數(shù),都直接體現(xiàn)在 URL 中。

查詢參數(shù)(Query Parameters):跟在 URL 問號?后面,格式為key1=value1&key2=value2。在 FastAPI 中,函數(shù)參數(shù)不是路徑的一部分的,默認就是查詢參數(shù)。

from fastapi import FastAPI
app = FastAPI()

@app.get("/items/")
async def read_items(skip: int = 0, limit: int = 10):
    # `skip`和`limit`就是查詢參數(shù),如:/items/?skip=20&limit=5
    return {"skip": skip, "limit": limit}

使用 skip: int = 0 形式,就定義了帶默認值的可選參數(shù)。如果沒有默認值(如 name: str),它就是必需的查詢參數(shù)。

路徑參數(shù)(Path Parameters):直接是 URL 路徑的一部分,用花括號{}聲明。通常用于唯一標識資源,比如根據(jù)ID獲取某篇文章。

@app.get("/items/{item_id}")
async def read_item(item_id: int):  # item_id 是路徑參數(shù)
    return {"item_id": item_id}

注意它們的順序!如果把 /items/{item_id} 和 /items/me 兩個端點都定義,要把具體的路徑(/items/me)放在前面,否則me會被當成item_id的值。

請求體參數(shù):處理復雜數(shù)據(jù)

當你需要客戶端發(fā)送較多數(shù)據(jù)(如創(chuàng)建新文章)時,就需要請求體。FastAPI 用 Body()Form() 等工具函數(shù)來聲明。

JSON 請求體(Body):最常見的 REST API 數(shù)據(jù)格式。使用 Pydantic 的 BaseModel 是最佳實踐(下文詳解),也可用 Body() 直接聲明多個參數(shù)。

from fastapi import Body

@app.put("/items/{item_id}")
async def update_item(
    item_id: int,
    name: str = Body(...),  # Body(...) 表示必需項
    description: str = Body(None)  # Body(None) 表示可選項
):
    return {"item_id": item_id, "name": name, "description": description}

表單數(shù)據(jù)(Form):當數(shù)據(jù)來自 HTML 表單或需要上傳文件時使用。如何要上傳大文件,需要先安裝 python-multipart。

from fastapi import Form

@app.post("/login/")
async def login(username: str = Form(...), password: str = Form(...)):
    return {"username": username}

混合參數(shù):自由組合,各司其職

FastAPI 能智能地區(qū)分參數(shù)來源,你可以同時使用路徑、查詢和請求體參數(shù)。

from fastapi import Path, Query, Body

@app.put("/mixed-items/{item_id}")
async def update_mixed_item(
    *,
    item_id: int = Path(..., title="商品ID", ge=1),  # 路徑參數(shù),>=1
    q: str = Query(None, alias="query-string"),      # 可選查詢參數(shù),別名
    item: dict = Body(...)                           # 必需的JSON請求體
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    results.update({"item": item})
    return results

這里用到了參數(shù)校驗:ge=1 表示值大于等于1。QueryPathBody 等函數(shù)讓聲明更明確且功能更強大(如添加描述、別名、校驗)。

結構化利器:Pydantic BaseModel

這是 FastAPI 的靈魂特性之一。 BaseModel 讓你用 Python 類來定義數(shù)據(jù)模型,它自動處理數(shù)據(jù)驗證、序列化和文檔生成。

from pydantic import BaseModel, EmailStr
from typing import Optional, List

class UserCreate(BaseModel):
    # 必需字段
    username: str
    email: EmailStr  # 內(nèi)置郵箱格式驗證
    # 可選字段,帶默認值
    full_name: Optional[str] = None
    # 列表類型
    tags: List[str] = []

@app.post("/users/")
async def create_user(user: UserCreate):  # 一個參數(shù)接管整個請求體
    # 直接訪問已驗證好的數(shù)據(jù)
    if user.full_name:
        greeting = f"Hello, {user.full_name}!"
    else:
        greeting = f"Hello, {user.username}!"
    return {"message": greeting, "user_info": user.dict()}

BaseModel 的優(yōu)勢:

  • 聲明即驗證: 字段類型不對、郵箱格式錯誤等會自動返回 422 錯誤。
  • 自動文檔: Swagger UI 和 ReDoc 會自動顯示模型結構和示例。
  • 代碼清晰: 數(shù)據(jù)契約明確,業(yè)務邏輯與數(shù)據(jù)驗證分離。
  • 嵌套自由: 模型可以嵌套其他模型,輕松處理復雜數(shù)據(jù)。

完整代碼示例

下面是一個融合了主要參數(shù)類型的實戰(zhàn)示例,你可以直接復制運行。

from fastapi import FastAPI, Path, Query, Body
from pydantic import BaseModel
from typing import Optional
from datetime import datetime

app = FastAPI(title="參數(shù)詳解示例")

class Item(BaseModel):
    name: str
    description: Optional[str] = None
    price: float = Body(..., gt=0)
    tax: Optional[float] = None
    tags: list = []

@app.post("/advanced-items/{category}")
async def create_advanced_item(
    category: str = Path(..., description="物品分類"),
    item_id: int = Query(..., ge=1, description="物品ID"),
    q: Optional[str] = Query(None, max_length=50),
    urgent: bool = Query(False),
    item: Item = Body(..., example={  # 為文檔提供示例
        "name": "Foo",
        "price": 50.5,
        "tags": ["cool", "new"]
    })
):
    """創(chuàng)建新物品的復雜端點"""
    total = item.price + (item.tax if item.tax else 0)
    result = {
        "category": category,
        "item_id": item_id,
        "query_string": q,
        "urgent": urgent,
        "item_name": item.name,
        "total_price": total,
        "created_at": datetime.now().isoformat()
    }
    return result

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

運行后,訪問 http://127.0.0.1:8000/docs,你將看到一個功能齊全的交互式 API 文檔,所有參數(shù)和模型都清晰可見。

到此這篇關于一文帶你搞懂Python FastAPI中所有核心參數(shù)的設置的文章就介紹到這了,更多相關Python FastAPI參數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論

乐陵市| 政和县| 清新县| 湘潭市| 旺苍县| 双江| 滦平县| 荥经县| 金阳县| 尉氏县| 夹江县| 常州市| 延吉市| 报价| 丰台区| 双江| 泗洪县| 特克斯县| 三江| 泗水县| 澎湖县| 华蓥市| 左云县| 登封市| 偃师市| 柘城县| 柳江县| 湟中县| 新宾| 元江| 台南县| 花莲市| 洛川县| 兴国县| 宁阳县| 绥棱县| 克拉玛依市| 清徐县| 米泉市| 获嘉县| 全椒县|