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

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

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

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

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

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

查詢參數(shù)(Query Parameters):跟在 URL 問(wèn)號(hào)?后面,格式為key1=value1&key2=value2。在 FastAPI 中,函數(shù)參數(shù)不是路徑的一部分的,默認(rèn)就是查詢參數(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 形式,就定義了帶默認(rèn)值的可選參數(shù)。如果沒(méi)有默認(rèn)值(如 name: str),它就是必需的查詢參數(shù)。

路徑參數(shù)(Path Parameters):直接是 URL 路徑的一部分,用花括號(hào){}聲明。通常用于唯一標(biāo)識(shí)資源,比如根據(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 兩個(gè)端點(diǎn)都定義,要把具體的路徑(/items/me)放在前面,否則me會(huì)被當(dāng)成item_id的值。

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

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

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

from fastapi import Body

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

表單數(shù)據(jù)(Form):當(dāng)數(shù)據(jù)來(lái)自 HTML 表單或需要上傳文件時(shí)使用。如何要上傳大文件,需要先安裝 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ù)來(lái)源,你可以同時(shí)使用路徑、查詢和請(qǐng)求體參數(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請(qǐng)求體
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    results.update({"item": item})
    return results

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

結(jié)構(gòu)化利器:Pydantic BaseModel

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

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

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

@app.post("/users/")
async def create_user(user: UserCreate):  # 一個(gè)參數(shù)接管整個(gè)請(qǐng)求體
    # 直接訪問(wèn)已驗(yàn)證好的數(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)勢(shì):

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

完整代碼示例

下面是一個(gè)融合了主要參數(shù)類(lèi)型的實(shí)戰(zhàn)示例,你可以直接復(fù)制運(yù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="物品分類(lèi)"),
    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)建新物品的復(fù)雜端點(diǎn)"""
    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)

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

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

相關(guān)文章

最新評(píng)論

微博| 鹿邑县| 鹤山市| 镇江市| 搜索| 福安市| 邳州市| 万安县| 车致| 循化| 湖南省| 沽源县| 得荣县| 汕尾市| 比如县| 江永县| 裕民县| 虞城县| 达日县| 商城县| 隆尧县| 怀柔区| 新河县| 垦利县| 云安县| 澎湖县| 健康| 永年县| 阜南县| 缙云县| 十堰市| 合肥市| 沧源| 平山县| 韶山市| 永福县| 阳信县| 泰顺县| 阳东县| 大新县| 内黄县|