参考网站:https://fastapi.tiangolo.com/zh/tutorial/path-params/
梳理内容:路径参数、查询参数
from fastapi import FastAPI
import uvicorn
from enum import Enum
from pydantic import BaseModel
from typing import Optional, Union
# 定义模型名称的枚举类,用于模型名称的标准化管理
class ModelName(str, Enum):
alexnet = "alexnet"
resnet = "resnet"
lenet = "lenet"
# 定义用户模型,包含用户名、邮箱和全名
class User(BaseModel):
username: str
email: str
full_name: Optional[str] = None
# 模拟数据库中的项目数据
fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]
# 初始化FastAPI应用程序
app = FastAPI()
# 定义路由,获取指定ID的项目
# 路径参数
@app.get("/items/{item_id}")
async def read_item(item_id):
return {"item_id": item_id}
# 根据模型名称获取模型信息
# 使用枚举类作为路径参数,确保模型名称的准确性
@app.get("/models/{model_name}")
async def get_model(model_name: ModelName):
if model_name is 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"}
# 定义路由,获取指定路径的文件信息
@app.get("/files/{file_path:path}")
async def read_file(file_path: str):
return {"file_path": file_path}
# 获取项目列表,支持分页
# 查询参数
@app.get("/items/")
async def read_item(skip: int = 0, limit: int = 10):
return fake_items_db[skip: skip + limit]
# 获取项目信息,支持查询参数和短描述/长描述的切换
# 查询参数类型转换
@app.get("/items11/{item_id}")
async def read_item(item_id: str, q: Union[str, None] = None, short: bool = False):
item = {"item_id": item_id}
if q:
item.update({"q": q})
if not short:
item.update(
{"description": "This is an amazing item that has a long description"}
)
return item
# 获取用户项目的详细信息,支持查询参数和短描述/长描述的切换
# 多个路径和查询参数
@app.get("/users/{user_id}/items/{item_id}")
async def read_user_item(
user_id: int, item_id: str, q: Union[str, None] = None, short: bool = False
):
item = {"item_id": item_id, "owner_id": user_id}
if q:
item.update({"q": q})
if not short:
item.update(
{"description": "This is an amazing item that has a long description"}
)
return item
# 获取项目信息,强制要求提供查询参数needy
# 必选查询参数
@app.get("/items11/{item_id}")
async def read_user_item(item_id: str, needy: str):
item = {"item_id": item_id, "needy": needy}
return item
# 主函数,用于启动FastAPI应用程序
if __name__ == "__main__":
## 线上模式
# uvicorn.run("abr_server:app", host="0.0.0.0", port = 1213)
## debug 模式
uvicorn.run("test:app", host="0.0.0.0", port=1213, reload=True, )