diff --git a/src/backend/app/main.py b/src/backend/app/main.py index d2ed050929..795b2f9de4 100644 --- a/src/backend/app/main.py +++ b/src/backend/app/main.py @@ -20,6 +20,7 @@ import logging import sys from typing import Optional +from contextlib import asynccontextmanager import sentry_sdk from fastapi import FastAPI, Request @@ -48,6 +49,20 @@ ) +@asynccontextmanager +async def lifespan(app: FastAPI): + # Startup events + log.debug("Starting up FastAPI server.") + log.debug("Reading XLSForms from DB.") + read_xlsforms(next(get_db()), xlsforms_path) + + yield + + # Shutdown events + ml_models.clear() + log.debug("Shutting down FastAPI server.") + + def get_application() -> FastAPI: """Get the FastAPI app instance, with settings.""" _app = FastAPI( @@ -59,6 +74,7 @@ def get_application() -> FastAPI: "url": "https://raw.githubusercontent.com/hotosm/fmtm/main/LICENSE", }, debug=settings.DEBUG, + lifespan=lifespan, root_path=settings.API_PREFIX, ) @@ -170,34 +186,20 @@ async def validation_exception_handler(request: Request, exc: RequestValidationE return JSONResponse(status_code=status_code, content={"errors": errors}) -@api.on_event("startup") -async def startup_event(): - """Commands to run on server startup.""" - log.debug("Starting up FastAPI server.") - log.debug("Reading XLSForms from DB.") - read_xlsforms(next(get_db()), xlsforms_path) - - -@api.on_event("shutdown") -async def shutdown_event(): - """Commands to run on server shutdown.""" - log.debug("Shutting down FastAPI server.") - - @api.get("/") -def home(): +async def home(): """Redirect home to docs.""" return RedirectResponse("/docs") @api.get("/items/{item_id}") -def read_item(item_id: int, q: Optional[str] = None): +async def read_item(item_id: int, q: Optional[str] = None): """Get item IDs.""" return {"item_id": item_id, "q": q} @api.get("/images/{image_filename}") -def get_images(image_filename: str): +async def get_images(image_filename: str): """Download image files.""" path = f"./app/images/{image_filename}" return FileResponse(path)