Debian Codegraph @

docs_src/events/tutorial003_py310.py

raw
1 from contextlib import asynccontextmanager
2
3 from fastapi import FastAPI
4
5
6 def fake_answer_to_everything_ml_model(x: float):
7 return x * 42
8
9
10 ml_models = {}
11
12
13 @asynccontextmanager
14 async def lifespan(app: FastAPI):
15 # Load the ML model
16 ml_models["answer_to_everything"] = fake_answer_to_everything_ml_model
17 yield
18 # Clean up the ML models and release the resources
19 ml_models.clear()
20
21
22 app = FastAPI(lifespan=lifespan)
23
24
25 @app.get("/predict")
26 async def predict(x: float):
27 result = ml_models["answer_to_everything"](x)
28 return {"result": result}