FastAPI 工程管理(一) 工程目录管理

作者:麦克煎蛋   出处:https://www.cnblogs.com/mazhiyong/ 转载请保留这段声明,谢谢!

 

我们在构建复杂应用的时候,通常会对工程目录进行合理组织。

FastAPI提供了便利的工具来对应用进行结构化管理,这基本等同于Flask的Blueprints功能。

一、文件结构示例

.
├── app
│   ├── __init__.py
│   ├── main.py
│   └── routers
│       ├── __init__.py
│       ├── items.py
│       └── users.py

二、APIRouter

FastAPI可以基于APIRouter功能对子模块进行组织和管理。

(一)、管理users模块

1、在模块中创建APIRouter的实例。

from fastapi import APIRouter

router = APIRouter()

2、利用APIRouter的实例声明路径操作

我们可以把APIRouter看做一个"小型FastAPI",他们的使用方式完全一样,他们都支持同样的选项和附件操作。

@router.get("/users/", tags=["users"])
async def read_users():
    return [{"username": "Foo"}, {"username": "Bar"}]


@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}

(二)、管理items模块

这里我们省略了路径前缀、tags等信息。

from fastapi import APIRouter, HTTPException

router = APIRouter()


@router.get("/")
async def read_items():
    return [{"name": "Item Foo"}, {"name": "item Bar"}]


@router.get("/{item_id}")
async def read_item(item_id: str):
    return {"name": "Fake Specific Item", "item_id": item_id}


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

(三)、应用入口管理

我们在应用入口文件中将各个模块组织起来。

1、实例主应用

from fastapi import Depends, FastAPI, Header, HTTPException

app = FastAPI()

2、导入各个子模块

from .routers import items, users

我们也可以使用绝对路径的方式导入子模块

from app.routers import items, users

3、导入router

从各个子模块中导入router:

app.include_router(users.router)

在导入items.router的时候,添加了更多设置信息:

async def get_token_header(x_token: str = Header(...)):
    if x_token != "fake-super-secret-token":
        raise HTTPException(status_code=400, detail="X-Token header invalid")

app.include_router(
    items.router,
    prefix="/items",
    tags=["items"],
    dependencies=[Depends(get_token_header)],
    responses={404: {"description": "Not found"}},
)

在导入router的时候,可以重复导入同样的router多次,每次前缀不同。这样可以实现在不同的前缀下暴露同样的API。

 

posted on 2020-07-27 11:12  麦克煎蛋  阅读(3302)  评论(0编辑  收藏  举报