Spaces:
Running
Running
File size: 1,763 Bytes
7b8993a |
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 52 53 54 55 |
"""MongoDB database connection and collections."""
from motor.motor_asyncio import AsyncIOMotorClient, AsyncIOMotorDatabase
from typing import Optional
from app.config import get_settings
class Database:
"""MongoDB database manager."""
client: Optional[AsyncIOMotorClient] = None
db: Optional[AsyncIOMotorDatabase] = None
@classmethod
async def connect(cls):
"""Connect to MongoDB."""
settings = get_settings()
if not settings.mongodb_url:
print("Warning: MongoDB URL not configured")
return
try:
# Add tlsAllowInvalidCertificates for macOS SSL issues
cls.client = AsyncIOMotorClient(
settings.mongodb_url,
tlsAllowInvalidCertificates=True,
serverSelectionTimeoutMS=5000,
)
cls.db = cls.client[settings.mongodb_db_name]
# Create indexes
await cls.db.watchlist.create_index("symbol", unique=True)
await cls.db.fr_history.create_index([("symbol", 1), ("recorded_at", -1)])
print(f"Connected to MongoDB: {settings.mongodb_db_name}")
except Exception as e:
print(f"Error connecting to MongoDB: {e}")
@classmethod
async def disconnect(cls):
"""Disconnect from MongoDB."""
if cls.client:
cls.client.close()
print("Disconnected from MongoDB")
@classmethod
def get_db(cls) -> Optional[AsyncIOMotorDatabase]:
"""Get database instance."""
return cls.db
# Convenience function to get db
def get_database() -> Optional[AsyncIOMotorDatabase]:
"""Get database instance."""
return Database.get_db()
|