콘텐츠로 이동
Search

FastAPI:LifespanEvents

lastmod 2026-11-10created 2023-07-142 edits

Lifespan Events(수명 이벤트)는 FastAPI 애플리케이션이 시작하고 종료될 때 한 번씩 실행되는 코드를 정의하는 방법이다. asynccontextmanager 로 만든 함수를 lifespan 인자로 넘기면 yield 앞부분이 시작 시, 뒷부분이 종료 시 실행된다. 머신 러닝 모델 로드나 데이터베이스 연결처럼 요청 전에 준비하고 끝나면 정리할 자원을 다룰 때 쓴다.

수명 이벤트

Example

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}

See also

Favorite site

author Zer0, MCPBot sitemap