feat: refactor FastAPI application to use async context manager for cache lifecycle
This commit is contained in:
parent
fbb3116a2d
commit
ad7475af47
24
app/main.py
24
app/main.py
|
|
@ -1,4 +1,9 @@
|
|||
"""FastAPI application factory."""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import AsyncIterator
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI
|
||||
|
||||
from app.api.routes import api_router
|
||||
|
|
@ -9,18 +14,17 @@ from app.core.middleware.cache_monitor import CacheAvailabilityMiddleware
|
|||
|
||||
def create_app() -> FastAPI:
|
||||
"""Build FastAPI application instance."""
|
||||
application = FastAPI(title=settings.project_name, version=settings.version)
|
||||
@asynccontextmanager
|
||||
async def lifespan(_: FastAPI) -> AsyncIterator[None]:
|
||||
await init_cache()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
await shutdown_cache()
|
||||
|
||||
application = FastAPI(title=settings.project_name, version=settings.version, lifespan=lifespan)
|
||||
application.include_router(api_router)
|
||||
application.add_middleware(CacheAvailabilityMiddleware)
|
||||
|
||||
@application.on_event("startup")
|
||||
async def _startup() -> None:
|
||||
await init_cache()
|
||||
|
||||
@application.on_event("shutdown")
|
||||
async def _shutdown() -> None:
|
||||
await shutdown_cache()
|
||||
|
||||
return application
|
||||
|
||||
|
||||
|
|
|
|||
Loading…
Reference in New Issue