0

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

  • did you try follow mongodb fastapi example project ? https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi/ – Bastien B May 29 '23 at 14:31
  • @BastienB The example doesnt show how to pass db connection to all routers – harsh_jain100 May 30 '23 at 04:47
  • fastapi support dependency injection https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#dependencies-with-yield you can check the fastapi official documentationan example here with sql db depends https://fastapi.tiangolo.com/tutorial/sql-databases/#main-fastapi-app – Bastien B May 30 '23 at 12:54

0 Answers0