61 lines
1.5 KiB
Python
61 lines
1.5 KiB
Python
"""
|
|
Database connection and management for sensor service
|
|
"""
|
|
|
|
import asyncio
|
|
import logging
|
|
from motor.motor_asyncio import AsyncIOMotorClient
|
|
import redis.asyncio as redis
|
|
from typing import Optional
|
|
import os
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# Global database connections
|
|
mongo_client: Optional[AsyncIOMotorClient] = None
|
|
redis_client: Optional[redis.Redis] = None
|
|
database = None
|
|
|
|
async def connect_to_mongo():
|
|
global mongo_client, database
|
|
|
|
try:
|
|
mongo_url = os.getenv("MONGO_URL", "mongodb://admin:password123@mongodb:27017/energy_dashboard_sensors?authSource=admin")
|
|
|
|
mongo_client = AsyncIOMotorClient(mongo_url)
|
|
database = mongo_client.energy_dashboard_sensors
|
|
|
|
await mongo_client.admin.command('ping')
|
|
logger.info("Connected to MongoDB successfully")
|
|
|
|
except Exception as e:
|
|
logger.error(f"Failed to connect to MongoDB: {e}")
|
|
raise
|
|
|
|
async def close_mongo_connection():
|
|
global mongo_client
|
|
if mongo_client:
|
|
mongo_client.close()
|
|
logger.info("Closed MongoDB connection")
|
|
|
|
async def connect_to_redis():
|
|
global redis_client
|
|
|
|
try:
|
|
redis_url = os.getenv("REDIS_URL", "redis://redis:6379")
|
|
redis_client = redis.from_url(redis_url, decode_responses=True)
|
|
|
|
# Test connection
|
|
await redis_client.ping()
|
|
logger.info("Connected to Redis successfully")
|
|
|
|
except Exception as e:
|
|
logger.error(f"Failed to connect to Redis: {e}")
|
|
raise
|
|
|
|
async def get_database():
|
|
return database
|
|
|
|
async def get_redis():
|
|
return redis_client
|