-
-
Notifications
You must be signed in to change notification settings - Fork 6.1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
✨ Add support for
lifespan
async context managers (superseding `sta…
…rtup` and `shutdown` events) (#2944) 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>
- Loading branch information
1 parent
66e03c8
commit cc9a73c
Showing
6 changed files
with
298 additions
and
44 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
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} |
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
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
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
Oops, something went wrong.