fastapi之APIRouter

fastapi提供APIRouter将不同功能模块的端点进行划分。这对大型程序的组织来说是非常有用的。

一、使用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}

二、使用依赖项:

from fastapi import Header, HTTPException, APIRouter


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")


async def get_query_token(token: str):
    if token != "jessica":
        raise HTTPException(status_code=400, detail="No Jessica token provided")

        
router = APIRouter(
    prefix="/items",1)
    tags=["items"],      
    dependencies=[Depends(get_token_header)],2)
    responses={404: {"description": "Not found"}},
) 

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

(1)声明路由前缀,所有router下的路由都将拥有/items前缀,如/items/{item_id}。

(2)创建APIRouter时指定依赖项,该router下的所有路由都将使用get_token_header。

三、在FastApi主体中导入路由

在主体程序中导入其他模块的路由。

from fastapi import Depends, FastAPI

from .dependencies import get_query_token, get_token_header  (1)
from .internal import admin   (2from .routers import items, users   (3)

app = FastAPI(dependencies=[Depends(get_query_token)])   (4)


app.include_router(users.router)    (5)
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"}},
)   (6)

@app.get("/")
async def root():
    return {"message": "Hello Bigger Applications!"}

(1)导入依赖项

(2)导入子模块

(3)导入其他模块路由

(4)创建FastAPI,同时指定全局依赖项。

(5)将用户模块路由导入FastApi全局对象中。

(6)将子模块的路由导入FastApi全局对象中,并且指定一个依赖项。

你可能感兴趣的:(python,fastapi,python,前端)