from fastapi import FastAPI, Request
import uvicorn
from contextlib import asynccontextmanager
from dotenv import dotenv_values
from motor.motor_asyncio import AsyncIOMotorClient
from pymongo import MongoClient
from routes.api import router as api_router
import logging
# Configure logging
logging.basicConfig(level=logging.INFO)
config = dotenv_values(".env")
@asynccontextmanager
async def lifespan(app: FastAPI):
logging.info("Initializing MongoDB connection ...")
app.mongodb_client = AsyncIOMotorClient(config["ATLAS_URI"])
app.database = app.mongodb_client[config["DB_NAME"]]
logging.info("Project connected to MongoDB database!")
# dbHost = await connectToDatabase()
# app.database = dbHost.pymongo_tutorial
print("Project connected to the MongoDB database!")
yield
logging.info("Closing MongoDB connection ...")
await app.mongodb_client.close()
logging.info("Closed MongoDB connection")
app = FastAPI(lifespan=lifespan)
@app.middleware("http")
async def check_database_access(request: Request, call_next):
# Check if app.database is initialized
if not hasattr(request.app, "database"):
logging.warning("Attempted access to database before initialization")
else:
logging.info("Database access is safe")
response = await call_next(request)
return response
app.include_router(api_router)
if __name__ == '__main__': #this indicates that this a script to be run
uvicorn.run("main:app", host='127.0.0.1', port=8000, log_level="error", reload = True)
In the above code taken from a FastAPI tutorial, I am trying to set the “app.database” property via the asynccontextmanager and access it later in my route, but I getting this error:
File "C:UsersekojoGitCRUD_python_mongosrcrulesbooks.py", line 7, in get_collection_books
return request.app.database["books"]
^^^^^^^^^^^^^^^^^^^^
AttributeError: 'FastAPI' object has no attribute 'database'
and this is my code in the books.py file:
def get_collection_books(request: Request):
return request.app.database["books"]
In the original code this was the pattern used:
@app.on_event("startup")
def startup_db_client():
app.mongodb_client = MongoClient(config["ATLAS_URI"])
app.database = app.mongodb_client[config["DB_NAME"]]
print("Project connected to the MongoDB database!")
@app.on_event("shutdown")
def shutdown_db_client():
app.mongodb_client.close()
So basically I am try to modify the code to use the asyncontextmanager and getting the stated error and after looking at the logs, it says I am trying to access the database property before it is set. So, I have looked at my code, and I don’t see how I can identify where this is happening.