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