fastapi 查询参数和字符串校验 / 路径参数和数值校验
文章目錄
- 1. 約束限制
- 2. 必須參數
- 3. 查詢參數列表 / 多個值
- 4. 聲明更多元數據
- 5. 別名參數
- 6. 棄用參數
- 7. Path 路徑參數
- 8. 按需對參數排序
learn from https://fastapi.tiangolo.com/zh/tutorial/query-params-str-validations/
1. 約束限制
from typing import Optional from fastapi import FastAPI, Queryapp = FastAPI()@app.get("/items/") async def read_items(q: Optional[str] = Query(None, max_length=50)):res = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}if q:res.update({"q":q})return res-
Query(None, max_length=50) 顯示聲明為查詢參數,默認為 None, 最大長度50
-
更多限制 Query(None, min_length=3, max_length=50)
-
正則限制 Query(None, min_length=3, max_length=50, regex="^fixedquery"), 以 ^ 后面的字符開頭
注意 None 是默認值,也可以是其它默認值,改參數是可選的
2. 必須參數
- 將 默認值替換成 ...
- q: Optional[str] = Query(..., min_length=3, max_length=50, regex="^fixedquery$")
3. 查詢參數列表 / 多個值
-
添加 List[str],q: Optional[List[str]] = Query(None)
-
http://127.0.0.1:8000/items/?q=123456&q=7890&q=hahha
-
在沒有任何給定值時,賦予默認值 q: Optional[List[str]] = Query(["mike","jason"]
-
也可以使用 內置list ,注意此時程序不會檢查list內的參數類型 q: list = Query(["mike","jason"])
4. 聲明更多元數據
- 添加 title,description
5. 別名參數
你需要在瀏覽器里使用 參數 item-good,但是 python 不支持 - 作為變量名
- q: Optional[str] = Query(None, alias = "item-good")
6. 棄用參數
將參數 deprecated=True 傳入 Query
7. Path 路徑參數
from fastapi import Path @app.get("/items/{item_id}") async def read_items(item_id:int = Path(..., title="the id of the item"),q : Optional[str] = Query(None, alias="item-query")):results = {"item_id": item_id}if q:results.update({"q": q})return results- 限制大小 item_id:int = Path(..., title="the id of the item", ge=23, le=24),[23.0, 24.0] 之間的 int
- 路徑參數總是 必需的
8. 按需對參數排序
fastapi 會自動根據 參數的名稱、類型和默認值聲明(Query、Path 等)來檢測參數
from fastapi import Path @app.get("/items/{item_id}") async def read_items(q: str, item_id: int = Path(..., title="The ID of the item to get, hha", description="my description") ):results = {"item_id": item_id}if q:results.update({"q": q})return results @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對上面的代碼,參數 q,item_id 的順序如果調換了,會報錯
item_id: int = Path(..., title="The ID of the item to get"), q: str^ SyntaxError: non-default argument follows default argument加入第一個參數 *,表示讓后面的所有參數作為鍵值對參數
@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總結
以上是生活随笔為你收集整理的fastapi 查询参数和字符串校验 / 路径参数和数值校验的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode 1786. 从第一个节
- 下一篇: pip install时发生raise