Spaces:
Sleeping
Sleeping
File size: 988 Bytes
3b45a26 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | from fastapi import HTTPException, status
from motor.motor_asyncio import AsyncIOMotorClient, AsyncIOMotorDatabase
from core.config import settings
client: AsyncIOMotorClient | None = None
db: AsyncIOMotorDatabase | None = None
async def connect_to_mongo():
"""Connect to MongoDB."""
global client, db
client = AsyncIOMotorClient(settings.MONGODB_URL)
db = client[settings.MONGODB_DB_NAME]
# Force an actual round-trip so startup fails fast on bad URI/network/auth.
await client.admin.command("ping")
print("Connected to MongoDB")
async def close_mongo_connection():
"""Close MongoDB connection."""
global client
if client:
client.close()
print("Closed MongoDB connection")
def get_db() -> AsyncIOMotorDatabase:
"""Get database instance."""
if db is None:
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="Database is not initialized",
)
return db
|