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。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM