ROUTER OF APP
https://fastapi.tiangolo.com/tutorial/first-steps/
如果应用比较简单,可以把所有的路径定义在app上。
如果应用非常庞大,有很多的逻辑,按照业务分为产生数十以上的路径,则需要用模块的方式拆分应用
路径也需要对应拆分,不能把所有的路径挂在app上。
from fastapi import FastAPI app = FastAPI() @app.get("/") async def root(): return {"message": "Hello World"}
APIRouter
https://fastapi.tiangolo.com/tutorial/bigger-applications/?h=apirouter#an-example-file-structure
对于模块内部使用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}
然后使用app的include_router方法,把模块定义的router挂在到app上
from fastapi import Depends, FastAPI from .dependencies import get_query_token, get_token_header from .internal import admin from .routers import items, users app = FastAPI(dependencies=[Depends(get_query_token)]) app.include_router(users.router) 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"}}, ) @app.get("/") async def root(): return {"message": "Hello Bigger Applications!"}
事实上APIRouter也有includ_router方法,挂载子router,实现路径的层级嵌套管理。
router.include_router(other_router)
应用实例
https://github.com/eightBEC/fastapi-ml-skeleton
子模块挂载路径
from fastapi import APIRouter from fastapi_skeleton.api.routes import heartbeat, prediction api_router = APIRouter() api_router.include_router(heartbeat.router, tags=["health"], prefix="/health") api_router.include_router(prediction.router, tags=[ "prediction"], prefix="/model")
应用挂载子模块路径
from fastapi import FastAPI from fastapi_skeleton.api.routes.router import api_router from fastapi_skeleton.core.config import (API_PREFIX, APP_NAME, APP_VERSION, IS_DEBUG) from fastapi_skeleton.core.event_handlers import (start_app_handler, stop_app_handler) def get_app() -> FastAPI: fast_app = FastAPI(title=APP_NAME, version=APP_VERSION, debug=IS_DEBUG) fast_app.include_router(api_router, prefix=API_PREFIX) fast_app.add_event_handler("startup", start_app_handler(fast_app)) fast_app.add_event_handler("shutdown", stop_app_handler(fast_app)) return fast_app app = get_app()
标签:APIRouter,get,fastapi,app,router,FASTAPI,import From: https://www.cnblogs.com/lightsong/p/16658630.html