FastAPI 基礎學習(四) 路徑參數


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

 

一、路徑參數聲明

我們可以用以下的方式來聲明URL路徑參數。

from fastapi import FastAPI

app = FastAPI()


@app.get("/items/{item_id}")
async def read_item(item_id):
    return {"item_id": item_id}

這里,路徑參數item_id的值會直接作為實參item_id傳遞給函數read_item。

運行這個示例並訪問:http://127.0.0.1:8000/items/foo,結果如下:

{"item_id":"foo"}

二、路徑參數的變量類型

基於標准的Python類型注釋,你可以在路徑函數中聲明路徑參數的變量類型。

from fastapi import FastAPI

app = FastAPI()


@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}

這里,item_id被聲明為int類型。

三、數據轉換

運行代碼並訪問 http://127.0.0.1:8000/items/3,你會得到結果:

{"item_id":3}

注意這里函數接收到的數據是int類型的3,而不是字符串"3"。

也就是說,借助類型聲明,FastAPI可以對Request內容自動進行數據解析和數據轉換。

四、數據校驗

如果訪問 http://127.0.0.1:8000/items/foo,你會看到如下的錯誤:

{
    "detail": [
        {
            "loc": [
                "path",
                "item_id"
            ],
            "msg": "value is not a valid integer",
            "type": "type_error.integer"
        }
    ]
}

因為這里路徑參數item_id的值是"foo",無法轉換成int。

如果提供給item_id一個float類型的值,如4.2,也會發生類似的錯誤。

 

因此借助類型聲明,FastAPI給了你自動進行數據校驗的能力。返回結果里清晰的指出了具體錯誤內容,這非常有利於你的代碼開發和調試。

所有的數據校驗能力都是在Pydantic的底層支持下得以實現的。你可以利用通用的數據類型如str、float、bool或者其他更復雜的數據類型進行類型注釋。

五、路徑的順序問題

在有些情況下,路徑聲明的順序不同會影響訪問結果,這里應該留意下。

from fastapi import FastAPI

app = FastAPI()


@app.get("/users/me")
async def read_user_me():
    return {"user_id": "the current user"}


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

 這里路徑 /users/me 應該在路徑 /users/{user_id} 之前進行聲明。否則,針對路徑 /users/me 的訪問就會被匹配到 /users/{user_id},因為"me"會被認為是路徑參數 user_id 的值。

六、路徑參數的預定義值

我們可以使用Python Enum來聲明路徑參數的預定義值。

from enum import Enum

class ModelName(str, Enum):
    alexnet = "alexnet"
    resnet = "resnet"
    lenet = "lenet"

這里,我們聲明了一個類ModelName,它繼承自str(這樣限制了值的類型必須是字符串類型)和Enum。

這里也給出了ModelName類屬性的值。

使用示例如下:

from enum import Enum from fastapi import FastAPI


class ModelName(str, Enum):
    alexnet = "alexnet"
    resnet = "resnet"
    lenet = "lenet"


app = FastAPI()


@app.get("/model/{model_name}")
async def get_model(model_name: ModelName):
    if model_name == ModelName.alexnet:
        return {"model_name": model_name, "message": "Deep Learning FTW!"}
    if model_name.value == "lenet":
        return {"model_name": model_name, "message": "LeCNN all the images"}
    return {"model_name": model_name, "message": "Have some residuals"}

這時路徑參數model_name的類型是我們定義的枚舉類ModelName

我們可以訪問可交互式文檔 http://127.0.0.1:8000/docs 來快速進行接口驗證。

七、路徑參數中包含文件路徑

當路徑參數中包含文件路徑時,比如 /files/{file_path},我們可以用聲明file_path類型的方式進行支持。

/files/{file_path:path}

這里:path指出了file_path可以匹配任何文件路徑。

from fastapi import FastAPI

app = FastAPI()


@app.get("/files/{file_path:path}")
async def read_file(file_path: str):
    return {"file_path": file_path}

八、路徑操作的其他參數

我們可以在路徑操作中添加其他參數,比如標簽列表。

@app.post("/items/", response_model=Item, tags=["items"])
async def create_item(*, item: Item):
    return item


@app.get("/items/", tags=["items"])
async def read_items():
    return [{"name": "Foo", "price": 42}]


@app.get("/users/", tags=["users"])
async def read_users():
    return [{"username": "johndoe"}]

也可以添加summarydescription參數。

@app.post(
    "/items/",
    response_model=Item,
    summary="Create an item",
    description="Create an item with all the information, name, description, price, tax and a set of unique tags",
)

以及文檔字符串。

@app.post("/items/", response_model=Item, summary="Create an item")
async def create_item(*, item: Item):
    """
    Create an item with all the information:

    - **name**: each item must have a name
    - **description**: a long description
    - **price**: required
    - **tax**: if the item doesn't have tax, you can omit this
    - **tags**: a set of unique tag strings for this item
    """
    return item

或者deprecated參數表示該路徑操作已過期。

@app.get("/elements/", tags=["items"], deprecated=True)
async def read_elements():
    return [{"item_id": "Foo"}]

 

可以在交互式文檔中查看顯示效果。(略)

 


免責聲明!

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



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