Spaces:
Sleeping
Sleeping
| from motor.motor_asyncio import AsyncIOMotorClient | |
| from config import settings | |
| import logging | |
| logger = logging.getLogger(__name__) | |
| class MongoDB: | |
| client: AsyncIOMotorClient = None | |
| db = None | |
| async def connect(self): | |
| """Establish MongoDB connection.""" | |
| logger.info(f"Attempting to connect to MongoDB: {settings.MONGODB_DB_NAME}") | |
| self.client = AsyncIOMotorClient( | |
| settings.MONGODB_URL, | |
| serverSelectionTimeoutMS=10000, | |
| connectTimeoutMS=20000, | |
| tlsAllowInvalidCertificates=True # Helps in environments with strict firewalls or old CA certs | |
| ) | |
| self.db = self.client[settings.MONGODB_DB_NAME] | |
| # Verify connection immediately | |
| await self.client.admin.command('ping') | |
| logger.info(f"Connected to MongoDB: {settings.MONGODB_DB_NAME}") | |
| async def close(self): | |
| """Close MongoDB connection.""" | |
| if self.client: | |
| self.client.close() | |
| logger.info("Closed MongoDB connection") | |
| # Singleton instance | |
| db = MongoDB() | |