全面拥抱FastApi — 蓝图APIRouter

简介: 全面拥抱FastApi — 蓝图APIRouter

640.png

我们都知道在大型的应用程序或者 web api 中, 我们很少在一个文件中写入多个路由

将所有的请求方法写在同一个处理文件下面的话,会导致我们的代码显得很没有逻辑性

这样既不利于程序的扩展,也不利于程序日后的维护

在 Flask 中,我们一般用蓝图 Blueprint 来处理

那么在FastApi 中如何处理呢?

当然可以,在 FastApi 中使用 APIRouter 处理这种多程序分类

即类似 Flask 中的蓝图

APIRouter

假设专门用于处理用户的文件是的子模块/app/routers/users.py

您希望将与用户相关的路径操作与其余代码分开,使其看起来简洁明了。

可以使用来为该模块创建路径操作 APIRouter。

from fastapi import APIRouter
router = APIRouter()
@router.get("/users/", tags=["users"])
async def read_users():
    return [{"username": "Rick"}, {"username": "Morty"}]
@router.get("/users/me", tags=["users"])
async def read_user_me():
    return {"username": "fakecurrentuser"}
@router.get("/users/{username}", tags=["users"])
async def read_user(username: str):
    return {"username": username}

web 服务中还有另外一个应用模块,item

同样的 通过 APIRouter 来对其路由进行注册,代码如下:app/routers/items.py

from fastapi import APIRouter, Depends, HTTPException
from ..dependencies import get_token_header
router = APIRouter(
    prefix="/items",
    tags=["items"],
    responses={404: {"description": "Not found"}},
)
@router.get("/")
async def read_items():
    return fake_items_db
@router.get("/{item_id}")
async def read_item(item_id: str):
    if item_id not in fake_items_db:
        raise HTTPException(status_code=404, detail="Item not found")
    return {"name": fake_items_db[item_id]["name"], "item_id": item_id}

这样就将两个功能模块 item, user 给分离开来了

后期我们想更新或扩展 user 模块的功能,并不会对 item 造成影响!

上面便是 APIRouter 最最基础也是最强大之处,还有其他功能吗?

当然有!

自定义的tags,responses

细心的朋友应该发现了,在上述 item.py 中实例化 router的时候,传了好几个参数

一起来看看分别代表什么含义!

prefix 参数,路由的前缀

tags 将应用于特定路径操作的内容

responses 指特定于该路径下的响应内容,如上述便指定 404 的返回信息

@router.put(
    "/{item_id}",
    tags=["custom"],
    responses={403: {"description": "Operation forbidden"}},
)
async def update_item(item_id: str):
    if item_id != "plumbus":
        raise HTTPException(
            status_code=403, detail="You can only update the item: plumbus"
        )
    return {"item_id": item_id, "name": "The great Plumbus"}

还支持扩展或重写,增加其他功能

但是我们仍然可以添加更多 tags 将应用于特定路径操作的内容,

注册 APIRouter

最后一个步骤就是要将我们的 APIRouter 注册到核心对象上去

和之前我们创建主文件一样导入 FastApi,以及声明的 APIRouter 实例

main.py文件

from fastapi import Depends, FastAPI
from .dependencies import get_query_token, get_token_header
from .internal import admin
from .routers import items, users
app = FastAPI(dependencies=[Depends(get_query_token)])
app.include_router(users.router)
app.include_router(items.router)
app.include_router(
    admin.router,
    prefix="/admin",
    tags=["admin"],
    dependencies=[Depends(get_token_header)],
    responses={418: {"description": "I'm a teapot"}},
)
@app.get("/")
async def root():
    return {"message": "Hello Bigger Applications!"}

其中 include_router() 函数就是上面说的注册。

这时候就完成了,使用该 app 来启动服务即可

启动命令如下:

uvicorn main:app --host=0.0.0.0 --port=8800

最后来验证下打开接口文档,查看接口

相关文章
|
6月前
|
存储 IDE API
最佳实践:通过 FastAPI APIRouter 提升开发效率
FastAPI 是一个现代的、高性能的 Python Web 框架,它提供了 APIRouter 来帮助组织和管理路由。APIRouter 是一个可用于组织和分组路由的类,使得代码结构更加清晰和可维护。本文将介绍 FastAPI APIRouter 的用法,包括实践案例以及在 IDE 编辑器中的运行步骤。
FastAPI 学习之路(三十六)引入APIRouter
FastAPI 学习之路(三十六)引入APIRouter
FastAPI 学习之路(三十六)引入APIRouter
|
JSON 算法 安全
fastapi 安全性 / APIRouter / BackgroundTasks / 元数据 / 测试调试
fastapi 安全性 / APIRouter / BackgroundTasks / 元数据 / 测试调试
253 0
fastapi 安全性 / APIRouter / BackgroundTasks / 元数据 / 测试调试
|
NoSQL 测试技术 Redis
FastAPI(八十四)实战开发《在线课程学习系统》--接口测试(下)
FastAPI(八十四)实战开发《在线课程学习系统》--接口测试(下)
FastAPI(八十四)实战开发《在线课程学习系统》--接口测试(下)
|
测试技术 数据安全/隐私保护
FastAPI(八十四)实战开发《在线课程学习系统》--接口测试(上)
FastAPI(八十四)实战开发《在线课程学习系统》--接口测试(上)
|
存储 测试技术 数据安全/隐私保护
FastAPI(八十三)实战开发《在线课程学习系统》--注册接口单元测试
FastAPI(八十三)实战开发《在线课程学习系统》--注册接口单元测试
FastAPI(八十三)实战开发《在线课程学习系统》--注册接口单元测试
FastAPI(八十二)实战开发《在线课程学习系统》接口开发-- 课程上架下架
FastAPI(八十二)实战开发《在线课程学习系统》接口开发-- 课程上架下架
|
NoSQL Redis 数据库
FastAPI(八十一)实战开发《在线课程学习系统》接口开发-- 推荐课程列表与课程点赞
FastAPI(八十一)实战开发《在线课程学习系统》接口开发-- 推荐课程列表与课程点赞
FastAPI(八十)实战开发《在线课程学习系统》接口开发-- 课程列表
FastAPI(八十)实战开发《在线课程学习系统》接口开发-- 课程列表
FastAPI(七十九)实战开发《在线课程学习系统》接口开发-- 加入课程和退出课程
FastAPI(七十九)实战开发《在线课程学习系统》接口开发-- 加入课程和退出课程