Working with async databases

Database connection with lifespan events in FastAPI

Want more?

This lesson for enrolled students only. Join the course to unlock it!

You can see the code changes implemented in this lecture below.

If you have purchased the course in a different platform, you still have access to the code changes per lecture here on Teclado. The lecture video and lecture notes remain locked.
Join course for $30

Modified files

storeapi/main.py
--- 
+++ 
@@ -1,5 +1,16 @@
+from contextlib import asynccontextmanager
+
 from fastapi import FastAPI
+from storeapi.database import database
 from storeapi.routers.posts import router as posts_router

-app = FastAPI()
+
+@asynccontextmanager
+async def lifespan(app: FastAPI):
+    await database.connect()
+    yield
+    await database.disconnect()
+
+app = FastAPI(lifespan=lifespan)
 app.include_router(posts_router)
+