路径参数
比如访问:
127.0.0.1/user/123/
from fastapi import FastAPI import uvicorn app = FastAPI() @app.get("/user/{id}/") async def main(id: int): return {"id":id} if __name__ == '__main__': uvicorn.run( app = app, host = "127.0.0.1", port = 80, )
固定的路径参数
@app.get("/user/id/") async def main(): return {"id": "the current user"} @app.get("/user/{id}/") async def main(id: int): return {"id":id}
预留路径值
传入的路径参数 只能在预留路径里,不然就报错
from fastapi import FastAPI # 导入枚举类 from enum import Enum import uvicorn # 预留路径类 继承 str,文档将能够知道这些值的类型 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"} if __name__ == '__main__': uvicorn.run( app = app, host = "127.0.0.1", port = 80, )
路径转换器
访问
/files/bigdataboy/a.txt
,file_path
将能得到bigdataboy/a.txt
# 添加上 :path 即可 @app.get("/files/{file_path:path}") async def read_file(file_path: str): return {"file_path": file_path}
查询参数
查询参数是指
?
后面的&
分割的键值对
http://127.0.0.1:8000/items/?skip=0&limit=2
from fastapi import FastAPI import uvicorn app = FastAPI() fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}] @app.get("/items/") # 设置的默认值,当默认值是 None 时,表示该值为可选 async def read_item(skip: int = 0, limit: int = 2, default: str =None): # 一个列表切片 return fake_items_db[skip : skip + limit] if __name__ == '__main__': uvicorn.run( app = app, host = "127.0.0.1", port = 80, )
注意
如果
声明可选时
出现以下类似错误
# 声明可选
limit: int = None
# 出现以下类似错误
Incompatible types in assignment (expression has type "None", variable has type "int")
这是你需要这样做
from typing import Optional limit: Optional[int] = None
完整实例
from fastapi import FastAPI from typing import Optional import uvicorn app = FastAPI() @app.get("/items/") async def read_item(skip: str, limit: Optional[int] = None): item = {"skip": skip, "limit": limit} return item if __name__ == '__main__': uvicorn.run( app = app, host = "127.0.0.1", port = 80, )
版权声明:《 【FastAPI】 GET 方法 》为明妃原创文章,转载请注明出处!
最后编辑:2020-5-26 10:05:07