当前位置:   article > 正文

FastAPI学习-10. 路由管理APIRouter

fastapi路由管理

前言

Flask 中,我们一般用蓝图 Blueprint 来处理多个模块的视图,在fastapi 中也有类似的功能通过APIRouter 来管理。

路由管理 APIRouter

如果你正在开发一个应用程序或 Web API,很少会将所有的内容都放在一个文件中。
FastAPI 提供了一个方便的工具,可以在保持所有灵活性的同时构建你的应用程序(如果你学过 Flask,那这将相当于 Flask 的 Blueprints)。

假设你的文件结构如下:

  1. ├── app
  2. │ ├── __init__.py
  3. │ ├── main.py
  4. │ └── routers
  5. │ │ ├── __init__.py
  6. │ │ ├── items.py
  7. │ │ └── users.py

app 目录包含了所有内容。并且它有一个空文件 app/__init__.py,它包含一个 app/main.py 文件。
routers 目录下有 items.pyusers.py 2个文件。

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

  1. from fastapi import APIRouter
  2. router = APIRouter()
  3. @router.get("/users/", tags=["users"])
  4. async def read_users():
  5. return [{"username": "Rick"}, {"username": "Morty"}]
  6. @router.get("/users/me", tags=["users"])
  7. async def read_user_me():
  8. return {"username": "fakecurrentuser"}
  9. @router.get("/users/{username}", tags=["users"])
  10. async def read_user(username: str):
  11. return {"username": username}

假设你在位于 app/routers/items.py 的模块中还有专门用于处理应用程序中「项目」的端点。
这和 app/routers/users.py 的结构完全相同。
我们知道此模块中的所有路径操作都有相同的:

  • 路径 prefix:路径前缀 /items。
  • tags:(仅有一个 items 标签)。
  • responses: 定义响应状态码
  • dependencies:依赖项。

因此,我们可以将其添加到 APIRouter 中,而不是将其添加到每个路径操作中。

  1. from fastapi import APIRouter, Depends, HTTPException
  2. router = APIRouter(
  3. prefix="/items",
  4. tags=["items"],
  5. responses={404: {"description": "Not found"}},
  6. )
  7. fake_items_db = {"plumbus": {"name": "Plumbus"}, "gun": {"name": "Portal Gun"}}
  8. @router.get("/")
  9. async def read_items():
  10. return fake_items_db
  11. @router.get("/{item_id}")
  12. async def read_item(item_id: str):
  13. if item_id not in fake_items_db:
  14. raise HTTPException(status_code=404, detail="Item not found")
  15. return {"name": fake_items_db[item_id]["name"], "item_id": item_id}
  16. @router.put(
  17. "/{item_id}",
  18. tags=["custom"],
  19. responses={403: {"description": "Operation forbidden"}},
  20. )
  21. async def update_item(item_id: str):
  22. if item_id != "plumbus":
  23. raise HTTPException(
  24. status_code=403, detail="You can only update the item: plumbus"
  25. )
  26. return {"item_id": item_id, "name": "The great Plumbus"}

FastAPI 主体

现在,让我们来看看位于 app/main.py 的模块。在这里你导入并使用 FastAPI 类。

  1. from fastapi import Depends, FastAPI
  2. from .routers import items, users
  3. app = FastAPI()
  4. app.include_router(users.router)
  5. app.include_router(items.router)
  6. @app.get("/")
  7. async def root():
  8. return {"message": "Hello Bigger Applications!"}
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/464692
推荐阅读
相关标签
  

闽ICP备14008679号