feat: refactor FastAPI application to use async context manager for cache lifecycle
Test / test (push) Successful in 16s Details
Test / test (pull_request) Successful in 15s Details

This commit is contained in:
k1nq 2025-11-29 09:46:42 +05:00
parent fbb3116a2d
commit ad7475af47
1 changed files with 14 additions and 10 deletions

View File

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