FastAPI框架

前提

偶然在知乎看到一个极简的PythonWEB框架,想尝试玩玩

FastAPI官方文档

安装

1
2
pip install fastapi
pip install uvicorn

简单运行

1
2
3
4
5
6
7
8
# fastApi.py
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
return {"Hello": "fast"}
  • 终端运行uvicorn fastApi:app --reload

    • fastApifastApi.py 文件(一个 Python “模块”)。
    • app:在 fastApi.py 文件中通过 app = FastAPI() 创建的对象。
    • --reload:让服务器在更新代码后重新启动。仅在开发时使用该选项。
  • 程序中运行

1
2
if __name__ == "__main__":
uvicorn.run(app="fastApi:app", host="127.0.0.1", port=8000, reload=True, debug=True)

Swagger UI、ReDoc

http://localhost:8000/docs —— 自带Swagger

http://localhost:8000/redoc —— 自带ReDoc

GET请求路径参数写法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 常规请求---默认参数q为可选参数,item_id只能为int类型
@app.get("/items/{item_id}")
def read_item(item_id: int, q: Optional[str] = None):
return {"item_id": item_id, "q": q}

# 枚举类
class ModelName(str, Enum):
next = "next"
year = "year"
name = "name"

# 枚举类请求,此时model_name值只能从上面的枚举数值取
@app.get("/model/{model_name}")
def get_model(model_name: ModelName):
return {"modelName": model_name.year.value}

GET请求查询参数写法

1
2
3
4
5
6
7
8
9
10
11
12
13
# 此时 访问/items/ 等同于 /items/?skip=0&limit=10
# 此时 访问/items/?skip=20 等同于 /items/?skip=20&limit=10
# 取fake_items_db数组的前10个数据
@app.get("/items/")
async def read_item(skip: int = 0, limit: int = 10):
return fake_items_db[skip : skip + limit]

# bool类型的自动转换
# 当is_seed参数为on、yes、true、1时值为true
# 相反 当is_seed参数为off、no、false、0时值为false
@app.get("/getBool")
def get_bool(is_seed: bool = False):
return is_seed

POST请求体写法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
from pydantic import BaseModel
from fastapi import FastAPI,Query

# 创建数据模型 申明继承BaseModel类
class Item(BaseModel):
name: str
description: Optional[str] = None

@app.post("/items/")
async def create_item(item: Item):
return item

# 将请求对象转为字典 类似JAVA的Map
@app.post("/getMsg")
def get_msg(item: Item):
item_dict = item.dict()
item_dict.update({'name': 'ymt'})
return people_dict.get("name")

# 接收一个List请求
# 只适用于Post请求
@app.post("/getList")
def get_list(people_list: List[People]):
result = []
for people in people_list:
name = people.name
result.append(name)
return result

# 适用于任何请求
@app.get("/items/list/get")
async def read_items(q: List[str] = Query(None)):
query_items = {"q": q}
return query_items

请求体–字段

赏个🍗吧
0%