FundingRate / app /database.py
Cuong2004's picture
first times
7b8993a
"""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()