Skip to content

Commit

Permalink
refactor: replace deprecated on_event with lifespan event
Browse files Browse the repository at this point in the history
  • Loading branch information
spwoodcock committed Nov 21, 2023
1 parent 77233bd commit ab332b6
Showing 1 changed file with 19 additions and 17 deletions.
36 changes: 19 additions & 17 deletions src/backend/app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import logging
import sys
from typing import Optional
from contextlib import asynccontextmanager

import sentry_sdk
from fastapi import FastAPI, Request
Expand Down Expand Up @@ -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(
Expand All @@ -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,
)

Expand Down Expand Up @@ -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)

0 comments on commit ab332b6

Please sign in to comment.