FastAPI 工程管理(一) 工程目錄管理
阿新 • • 發佈:2020-07-27
作者:麥克煎蛋 出處: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。