File size: 1,537 Bytes
00cf2e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
56
57
58
59
60
61
62
63
64
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
load_dotenv()

# Load MongoDB configuration
MONGO_URI = os.getenv('MONGO_URI')
DB_NAME = os.getenv('DB_NAME')

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.")


if not CACHE_URI or not CACHE_K:
    raise ValueError("Redis 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,
            username="default",
            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