FastAPI的路由

Route路由, 是一种映射关系!路由是把客户端请求的url路径与视图函数进行绑定映射的一种关系。
• 路径 :是 /
• 请求方法:是 get
• 函数 :是位于「装饰器」下方的函数(位于 @app.get("/") 下方)

# 路径操作装饰器参数
# tags 文档标题
 1 from fastapi import FastAPI
 2 import uvicorn
 3 from apps.app01.urls import shop
 4 from apps.app02.urls import user
 5 app = FastAPI()
 6 1
 7 2
 8 3
 9 4
10 5
11 6
12 # 路由分发include_router
13 app.include_router(shop, prefix="/shop", tags=["购物中心接口"])
14 app.include_router(user, prefix="/user", tags=["用户中心接口"])
View Code

 


# summary 文档总结
# description 文档描述
# response_description 响应详情内容
# deprecated 接口文档是否废弃
@app.post("/items", tags=["这是items测试接口"],
summary="this is items测试 summary",
description="this is items测试 description...",
response_description="this is items测试 response_description",
deprecated=False)
def test():
return {"items": "items数据"}

1、路由分发

在main.py中的app作为主路由

from fastapi import FastAPI
import uvicorn
from apps.app01.urls import shop
from apps.app02.urls import user
app = FastAPI()
1
2
3
4
5
6
# 路由分发include_router
app.include_router(shop, prefix="/shop", tags=["购物中心接口"])
app.include_router(user, prefix="/user", tags=["用户中心接口"])

其他的子路由:

from fastapi import APIRouter
shop = APIRouter()
@shop.get("/food")
def shop_food():
return {"shop": "food"}
@shop.get("/bed")
def shop_bed():
return {"shop": "bed"}

2、路由参数

请求参数,通过路由路径携带的方式;我们称之为路由传参。参数也叫: 路由参数。你可以使用与
Python 格式化字符串相同的语法来声明路径"参数"或"变量":

@app.get("/items/{item_id}")
def read_item(item_id):
return {"item_id": item_id}

路径参数 item_id 的值将作为参数 item_id 传递给你的函数。所以,如果你运行示例并访问
[http://127.0.0.1:8000/items/foo],将会看到如下响应:

{"item_id":"foo"}

1、定义参数的类型

你可以使用标准的 Python 类型标注为函数中的路径参数声明类型。

@app.get("/items/{item_id}")
def read_item(item_id: int):
return {"item_id": item_id}

在这个例子中, item_id 被声明为 int 类型。FastAPI 通过上面的类型声明提供了对请求的自
动"解析"。
同时还提供数据校验功能:
如果你通过浏览器访问 [http://127.0.0.1:8000/items/foo],你会看到一个清晰可读的 HTTP 错误:

{
"detail": [
{
"loc": [
"path",
"item_id"
],
"msg": "value is not a valid integer",
"type": "type_error.integer"
}
]
}

因为路径参数 item_id 传入的值为 "foo" ,它不是一个 int 。
你可以使用同样的类型声明来声明 str 、float 、bool 以及许多其他的复合数据类型。

2、路由匹配的顺序
由于路由匹配操作是按顺序依次运行的,你需要确保路径 /users/me 声明在路径
/users/{user_id} 之前:

@app.get("/users/me")
def read_user_me():
return {"user_id": "the current user"}
@app.get("/users/{user_id}")
def read_user(user_id: str):
return {"user_id": user_id}

否则, /users/{user_id} 的路径还将与 /users/me 相匹配,"认为"自己正在接收一个值为
"me" 的 user_id 参数。
3、预设值参数
如果你有一个接收路径参数的路径操作,但你希望预先设定可能的有效参数值,则可以使用标准的
Python Enum 类型。
Python中的枚举数据类型:是指列出有穷集合中的所有元素,即一一列举的意思。在Python中,枚举
可以视为是一种数据类型,当一个变量的取值只有几种有限的情况时,我们可以将其声明为枚举类

from enum import Enum
from fastapi import FastAPI
class ModelName(str, Enum):
alexnet = "alexnet"
resnet = "resnet"
lenet = "lenet"
app = FastAPI()
@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"}

 





 

posted @ 2024-06-26 11:52  yongheng999  阅读(182)  评论(0)    收藏  举报