mirror of
https://github.com/fastapi/fastapi.git
synced 2025-12-24 22:59:32 -05:00
Co-authored-by: Mike Shantz <mshantz@coldstorage.com> Co-authored-by: Jonathan Plasse <13716151+JonathanPlasse@users.noreply.github.com> Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
29 lines
569 B
Python
29 lines
569 B
Python
from contextlib import asynccontextmanager
|
|
|
|
from fastapi import FastAPI
|
|
|
|
|
|
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(lifespan=lifespan)
|
|
|
|
|
|
@app.get("/predict")
|
|
async def predict(x: float):
|
|
result = ml_models["answer_to_everything"](x)
|
|
return {"result": result}
|