FastAPI 基礎學習(九) 參數附加信息 (二)


作者:麥克煎蛋   出處:https://www.cnblogs.com/mazhiyong/ 轉載請保留這段聲明,謝謝!

 

三、路徑參數附加信息

對路徑參數附加信息的支持,FastAPI通過Path模塊來實現。

1、導入Path模塊

from fastapi import Path

2、添加附加信息

所有適用於請求參數的附加信息同樣適用於路徑參數,如title等。

item_id: int = Path(..., title="The ID of the item to get")  

注意,路徑參數在URL里是必選的,因此Path的第一個參數是...,即使你傳遞了None或其他缺省值,也不會影響參數的必選性。

 

代碼示例:

from fastapi import FastAPI, Path

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(
    q: str, item_id: int = Path(..., title="The ID of the item to get")
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results

四、路徑參數、請求參數順序問題

1、不帶缺省值的參數應放在前面

如果把帶有缺省值的參數放在了不帶缺省值的參數前面,Python會發出運行警告。

因此在實際使用時,我們應當把不帶缺省值的參數放在前面,無論這個參數是路徑參數還是請求參數。

from fastapi import FastAPI, Path

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(
    q: str, item_id: int = Path(..., title="The ID of the item to get")
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results

FastAPI根據參數名稱、類型以及聲明方法(如Query、Path等等)來識別具體參數意義,並不關心參數順序。

2、參數排序的技巧

通過傳遞 * 作為第一個參數,就解決了上面的參數順序問題。

from fastapi import FastAPI, Path

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(
    *, item_id: int = Path(..., title="The ID of the item to get"), q: str
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results

Python並不會對 * 做任何操作。但通過識別 *,Python知道后面所有的參數都是關鍵字參數(鍵值對),通常也叫kwargs,無論參數是否有默認值。

五、數字類型參數的校驗

借助Query、Path等模塊你可以聲明對字符串類型參數的校驗,同樣的,也可以實現對數字類型參數的校驗功能。

附加參數信息說明:

gt: 大於(greater than)
ge: 大於或等於(greater than or equal)
lt: 小於(less than)
le: 小於或等於( less than or equal)

具體示例如下:

from fastapi import FastAPI, Path

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(
    *,
    item_id: int = Path(..., title="The ID of the item to get", gt=0, le=1000),
    q: str,
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results

數字校驗同樣也適用於float類型的參數。

from fastapi import FastAPI, Path, Query

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(
    *,
    item_id: int = Path(..., title="The ID of the item to get", ge=0, le=1000),
    q: str,
    size: float = Query(..., gt=0, lt=10.5)
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM