Recently I am facing the error
AttributeError: 'State' object has no attribute 'db'
and unable to store the DB connection in app.state.db and use it in different routes.
db.py
from motor.motor_asyncio import AsyncIOMotorClient
from decouple import config
async def get_mongo_connection():
client = AsyncIOMotorClient(config('MONGO_URL'))
db = client[config('MONGO_DB')]
return db
app.py
from utilities.conn.mongo import get_mongo_connection
@app.on_event("startup")
@version(1, 0)
async def startup_event():
app.state.db = await get_mongo_connection()
routes.py
from fastapi import APIRouter, Depends, HTTPException, Request
from fastapi_versioning import VersionedFastAPI, version
router = APIRouter(
tags=["Account"],
dependencies=[]
)
@router.post("/send-otp")
@version(1,0)
async def send_otp(request : Request, input : SendOTP):
print(request.app.state.db)
return {}
How do I fix it or is there a better way to use the connection in all my routes