CoolFace
Apppublic

Rsmkrishna/ac-user-auth

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
database.py68 linesDownload Raw Back to app
1import os2import motor.motor_asyncio3import redis.asyncio as redis4from redis.exceptions import RedisError5 6 7from dotenv import load_dotenv8import logging9 10# Configure logging11logging.basicConfig(12    level=logging.INFO,13    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",14)15logger = logging.getLogger(__name__)16 17# Load environment variables from .env file18 19# Explicitly load the .env file from the current project directory20ENV_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "../.env")21load_dotenv(dotenv_path=ENV_PATH)22 23# Load MongoDB configuration24MONGO_URI = os.getenv('MONGO_URI')25DB_NAME="ac-user-auth"26 27CACHE_URI=os.getenv('CACHE_URI') 28CACHE_K = os.getenv('CACHE_K')29 30if not MONGO_URI or not DB_NAME:31    raise ValueError("MongoDB URI or Database Name is not set in the environment variables.")32else:33    print("DB", DB_NAME)34 35 36if not CACHE_URI or not CACHE_K:37    raise ValueError("MongoDB URI or Database Name is not set in the environment variables.")38 39# Parse Redis host and port40CACHE_HOST, CACHE_PORT = CACHE_URI.split(":")41CACHE_PORT = int(CACHE_PORT)42 43# Initialize MongoDB client44try:45    client = motor.motor_asyncio.AsyncIOMotorClient(MONGO_URI)46    db = client[DB_NAME]47    logger.info(f"Connected to MongoDB database: {DB_NAME}")48except Exception as e:49    logger.error(f"Failed to connect to MongoDB: {e}")50    raise51 52 53 54# Initialize Redis client55try:56    redis_client = redis.Redis(57            host=CACHE_HOST,58            port=CACHE_PORT,59            password=CACHE_K,60            decode_responses=True61        )62  63    logger.info("Connected to Redis.")64except Exception as e:65    logger.error(f"Failed to connect to Redis: {e}")66    raise67 68