Skip to content

Instantly share code, notes, and snippets.

@noirbizarre
Created June 22, 2023 12:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noirbizarre/a6028f561adb5949c7f21471b9b02032 to your computer and use it in GitHub Desktop.
Save noirbizarre/a6028f561adb5949c7f21471b9b02032 to your computer and use it in GitHub Desktop.
A minimal example showing that APIRouter does not support `lifespan`
from contextlib import asynccontextmanager
from fastapi import FastAPI, APIRouter
def fake_answer_to_everything_ml_model(x: float):
return x * 42
ml_models = {}
@asynccontextmanager
async def lifespan(app: FastAPI):
# Load the ML model
ml_models["answer_to_everything"] = fake_answer_to_everything_ml_model
yield
# Clean up the ML models and release the resources
ml_models.clear()
app = FastAPI()
router = APIRouter(lifespan=lifespan)
@router.get("/predict")
async def predict(x: float):
result = ml_models["answer_to_everything"](x)
return {"result": result}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment