Created
June 22, 2023 12:20
-
-
Save noirbizarre/a6028f561adb5949c7f21471b9b02032 to your computer and use it in GitHub Desktop.
A minimal example showing that APIRouter does not support `lifespan`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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