import os import motor.motor_asyncio import redis.asyncio as redis from redis.exceptions import RedisError from dotenv import load_dotenv import logging # Configure logging logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", ) logger = logging.getLogger(__name__) # Load environment variables from .env file # Explicitly load the .env file from the current project directory ENV_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "../.env") load_dotenv(dotenv_path=ENV_PATH) # Load MongoDB configuration MONGO_URI = os.getenv('MONGO_URI') DB_NAME="ac-user-auth" CACHE_URI=os.getenv('CACHE_URI') CACHE_K = os.getenv('CACHE_K') if not MONGO_URI or not DB_NAME: raise ValueError("MongoDB URI or Database Name is not set in the environment variables.") else: print("DB", DB_NAME) if not CACHE_URI or not CACHE_K: raise ValueError("MongoDB URI or Database Name is not set in the environment variables.") # Parse Redis host and port CACHE_HOST, CACHE_PORT = CACHE_URI.split(":") CACHE_PORT = int(CACHE_PORT) # Initialize MongoDB client try: client = motor.motor_asyncio.AsyncIOMotorClient(MONGO_URI) db = client[DB_NAME] logger.info(f"Connected to MongoDB database: {DB_NAME}") except Exception as e: logger.error(f"Failed to connect to MongoDB: {e}") raise # Initialize Redis client try: redis_client = redis.Redis( host=CACHE_HOST, port=CACHE_PORT, password=CACHE_K, decode_responses=True ) logger.info("Connected to Redis.") except Exception as e: logger.error(f"Failed to connect to Redis: {e}") raise