diff --git a/main.py b/main.py index 7879ac6..c939efa 100644 --- a/main.py +++ b/main.py @@ -1,3 +1,4 @@ +from contextlib import asynccontextmanager from fastapi import FastAPI from dotenv import dotenv_values from pymongo import MongoClient @@ -5,16 +6,13 @@ config = dotenv_values(".env") -app = FastAPI() - -@app.on_event("startup") -def startup_db_client(): +@asynccontextmanager +async def lifespan(app: FastAPI): app.mongodb_client = MongoClient(config["ATLAS_URI"]) app.database = app.mongodb_client[config["DB_NAME"]] - -@app.on_event("shutdown") -def shutdown_db_client(): + yield app.mongodb_client.close() -app.include_router(book_router, tags=["books"], prefix="/book") +app = FastAPI(lifespan=lifespan) +app.include_router(book_router, tags=["books"], prefix="/book")