Seongwon Lim

[FastAPI] Lifespan을 이용한 생명주기 관리 (Event Handler) 본문

Python

[FastAPI] Lifespan을 이용한 생명주기 관리 (Event Handler)

limsw 2024. 2. 26. 22:52
반응형

서론

이번 글에서는 FastAPI의 Lifespan을 이용하여 이벤트를 관리하는 방법을 알아보고자 한다.

 

이 글에서 말하는 이벤트 핸들링은 FastAPI 서비스가 시작 또는 종료될 때 특정 함수를 호출하는 등의 행위를 말한다.

본론

먼저 Lifespan이 생기기 이전에 FastAPI는 on_event를 이용하여 이벤트를 관리했다.

 

예를 들어, FastAPI가 시작(종료)될 때 특정한 함수를 실행시키기 위해서는 다음과 같이 코드를 작성할 수 있었다.

from fastapi import FastAPI

app = FastAPI()

@app.on_event("startup")
async def startup_event():
    print("service is started.")

@app.on_event("shutdown")
async def shutdown_event():
    print("service is stopped.")
  • startup : FastAPI가 시작될 때 호출되는 함수
  • shutdown : FastAPI가 종료될 때 호출되는 함수

위 코드를 실행/종료 했을 때의 결과는 다음과 같다.

 

Lifespan을 사용하여 생명주기 관리하기

하지만 최근에는 on_event 사용을 지양하고 lifespan을 이용하여 이벤트를 관리하는 방법을 권장하고 있다.

 

위에서 작성한 코드를 Lifespan을 사용하여 구현하면 다음과 같이 코드를 작성할 수 있다.

from contextlib import asynccontextmanager
from fastapi import FastAPI

def start():
    print("service is started.")
    
def shutdown():
    print("service is stopped.")    

@asynccontextmanager
async def lifespan(app: FastAPI):
    # When service starts.
    start()
    
    yield
    
    # When service is stopped.
    shutdown()

app = FastAPI(lifespan=lifespan)

 

  • app 객체를 선언할 때 인자로 lifespan을 정의한다.
  • yield를 기준으로 에 오는 코드는 서비스가 시작될 때 호출되는 함수(코드) 이다.
  • yield를 기준으로 에 오는 코드는 서비스가 종료될 때 호출되는 함수(코드) 이다.

코드 실행 시 결과는 다음과 같다.

 

 

결과는 동일하지만 on_event함수는 공식적으로 지원하지 않는다고 하니, Lifespan을 사용하는 것을 지향한다고 한다.

Comments