FastAPI系列:查询字符串参数额外校验Query
设置默认值
@app.get("/items/")
async def read_items(q: Union[str, None] = Query(default=None, max_length=50)): # Query适用于查询参数中,设置默认值为None,并且规定最大长度为50
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
return results
不设置默认值,必填查询字符串
@app.get("/items/")
async def read_items(q: str = Query(min_length=3)):
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
return results
不设置默认值,必填查询字符串的另一种写法(...)省略号
@app.get("/items/")
async def read_items(q: str = Query(default=..., min_length=3)):
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
return results
不设置默认值,必填查询字符串的另一种写法Required
from pydantic import Required
@app.get("/items/")
async def read_items(q: str = Query(default=Required, min_length=3)):
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
return results
-------------------------------------------
个性签名:代码过万,键盘敲烂!!!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!