File size: 1,244 Bytes
bf5067d | 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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | import os
from motor.motor_asyncio import AsyncIOMotorClient
from dotenv import load_dotenv
load_dotenv()
# MongoDB connection settings
MONGODB_URL = os.getenv("MONGODB_URL", "mongodb://localhost:27017")
DATABASE_NAME = os.getenv("DATABASE_NAME", "fake_news_detector")
# Global database client
client: AsyncIOMotorClient = None
db = None
async def connect_to_mongodb():
"""Connect to MongoDB database"""
global client, db
try:
client = AsyncIOMotorClient(MONGODB_URL)
db = client[DATABASE_NAME]
# Verify connection
await client.admin.command('ping')
print(f"✅ Connected to MongoDB: {DATABASE_NAME}")
except Exception as e:
print(f"❌ Failed to connect to MongoDB: {e}")
raise e
async def close_mongodb_connection():
"""Close MongoDB connection"""
global client
if client:
client.close()
print("MongoDB connection closed")
def get_database():
"""Get database instance"""
return db
def get_users_collection():
"""Get users collection"""
return db["users"]
def get_predictions_collection():
"""Get predictions history collection"""
return db["predictions"]
|