1
0

FastAPI on_eventがlifespanに変更

Last updated at Posted at 2024-02-17

こんばんは、最近FastAPI触ることあったので備忘です。

これまで起動時と終了時の処理はon_eventを使用していましたが、最新バージョンではなくなってしまいました。

旧コード:

@app.on_event("startup")
async def startup_event():
    print("startup event")
    
@app.on_event("shutdown")
async def shutdown_event():
    print("shutdown event")

新コード:

from contextlib import asynccontextmanager

from fastapi import FastAPI

@asynccontextmanager
async def lifespan(app: FastAPI):
    print("startup event")
    yield
    print("shutdown event")
    
app = FastAPI(lifespan=lifespan)

以上、簡単な備忘でした。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0