Hey I’m using Vercel right now to deploy my FastAPI app.
Locally, I was using the FastAPI lifespan
to connect to the DB and manage sessions.
In main.py
from db import get_driver()
drivers = {}
@asynccontextmanager
async def lifespan(app: FastAPI):
drivers["db"] = await get_driver()
yield
await drivers["db"].close()
In db.py
async def get_driver():
return MyDB.driver(URI, auth)
async def get_session():
from .main import drivers
driver = drivers["db"]
async with driver.session() as session:
yield session
Elsewhere in my app I would then import the get_session()
to perform operations. However, in Vercel I keep running into the issue KeyError drivers["db"]
in the get_session()
function as if the lifespan
function isn’t called on startup and the drivers
dictionary isn’t initialized properly
Am I doing something wrong or is this just a by-product of “serverless”? I’ve fixed the issue by creating a new driver & session at each request but I feel like this is not OK. Anybody got tips?