什麼是路徑
- 假設一個 url 是: http://127.0.0.1:8080/items/abcd
- 那麼路徑 path 就是 /items/abcd
路徑引數
就是將路徑上的某一部分變成引數,可通過請求傳遞,然後 FastAPI 解析
最簡單的栗子
import uvicorn
from fastapi import FastAPI app = FastAPI() # 路徑引數 item_id
@app.get("/items/{item_id}")
async def read_item(item_id):
return {"item_id": item_id} if __name__ == '__main__':
uvicorn.run(app="2_get:app", host="127.0.0.1", port=8080, reload=True, debug=True)
postman 請求結果
限定型別的路徑引數
# 指定型別的路徑引數
@app.get("/items/{item_id}/article/{num}")
async def path_test(item_id: str, num: int):
return {"item_id": item_id, "num": num}
多個路徑引數,且有指定型別
正確傳參的請求結果
123 傳進來的時候是字串,但 FastAPI 會自動解析轉換成 int,如果轉換失敗就會報錯
num 不傳 int 的請求結果
友好的錯誤提示型別不對
Swagger 介面文件的顯示效果
路徑函式順序問題
@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/{user_id} 路徑是包含 /users/me 的
當想匹配到固定路徑時,需要將固定路徑函式放在路徑引數函式前面
postman 請求結果
將兩個函式順序換過來
@app.get("/users/{user_id}")
async def read_user(user_id: str):
return {"user_id": user_id} # 順序問題
@app.get("/users/me")
async def read_user_me():
return {"user_id": "the current user"}
這樣就無法匹配到固定路徑 /users/me 的函數了
路徑轉換器
前言
- 當你有一個路徑是 /files/{file_path} ,但是不確定 file_path 到底會取什麼值,並不是固定的長度,可能是 /files/home/johndoe/myfile.txt 也可能是 /files/test/myfile.txt ,那怎麼辦呢?
- 路徑轉換器出來啦!
實際栗子
# 路徑轉換器
@app.get("/files/{file_path:path}")
async def read_file(file_path: str):
return {"file_path": file_path}
postman 請求結果
列舉型別的路徑引數
# 匯入列舉類
from enum import Enum # 自定義列舉類
class ModelName(Enum):
polo = "polo"
yy = "yy"
test = "test" @app.get("/models/{model_name}")
# 型別限定為列舉類
async def get_model(model_name: ModelName):
# 取列舉值方式一
if model_name == ModelName.polo:
return {"model_name": model_name, "message": "oh!!polo!!"} # 取列舉值方式二
if model_name.value == "yy":
return {"model_name": model_name, "message": "god!!yy"} return {"model_name": model_name, "message": "巴拉巴拉"}
引數傳列舉值的請求結果
引數傳非列舉值的請求結果
錯誤提示傳的引數值並不是列舉類中的值
重點:路徑引數可以不傳嗎?
先說答案,不行!路徑引數是必傳引數
實際栗子
# 路徑引數 item_id
@app.get("/items/{item_id}")
async def read_item(item_id):
return {"item_id": item_id}
假設不傳 item_id
總結
路徑引數是請求路徑的一部分,如果不傳,請求的是另一個路徑,如果不存在就會 404