File size: 3,161 Bytes
c58df45 |
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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
import os
import logging
from azure.cosmos import CosmosClient
from pymongo import MongoClient
import certifi
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
# Variables globales para Cosmos DB SQL API
cosmos_client = None
user_database = None
user_container = None
application_requests_container = None
user_feedback_container = None
# Variables globales para Cosmos DB MongoDB API
mongo_client = None
mongo_db = None
def initialize_cosmos_sql_connection():
global cosmos_client, user_database, user_container, application_requests_container, user_feedback_container
try:
cosmos_endpoint = os.environ.get("COSMOS_ENDPOINT")
cosmos_key = os.environ.get("COSMOS_KEY")
if not cosmos_endpoint or not cosmos_key:
raise ValueError("COSMOS_ENDPOINT and COSMOS_KEY environment variables must be set")
cosmos_client = CosmosClient(cosmos_endpoint, cosmos_key)
user_database = cosmos_client.get_database_client("user_database")
user_container = user_database.get_container_client("users")
application_requests_container = user_database.get_container_client("application_requests")
user_feedback_container = user_database.get_container_client("user_feedback")
logger.info("Conexión a Cosmos DB SQL API exitosa")
return True
except Exception as e:
logger.error(f"Error al conectar con Cosmos DB SQL API: {str(e)}", exc_info=True)
return False
def initialize_mongodb_connection():
global mongo_client, mongo_db
try:
cosmos_mongodb_connection_string = os.getenv("MONGODB_CONNECTION_STRING")
if not cosmos_mongodb_connection_string:
raise ValueError("MONGODB_CONNECTION_STRING environment variable is not set")
mongo_client = MongoClient(cosmos_mongodb_connection_string,
tls=True,
tlsCAFile=certifi.where(),
retryWrites=False,
serverSelectionTimeoutMS=5000,
connectTimeoutMS=10000,
socketTimeoutMS=10000)
mongo_client.admin.command('ping')
mongo_db = mongo_client['aideatext_db']
logger.info("Conexión a Cosmos DB MongoDB API exitosa")
return True
except Exception as e:
logger.error(f"Error al conectar con Cosmos DB MongoDB API: {str(e)}", exc_info=True)
return False
def initialize_database_connections():
sql_success = initialize_cosmos_sql_connection()
mongodb_success = initialize_mongodb_connection()
return sql_success and mongodb_success
def get_sql_containers():
if user_container is None or application_requests_container is None or user_feedback_container is None:
initialize_cosmos_sql_connection()
return user_container, application_requests_container, user_feedback_container
def get_mongodb():
if mongo_db is None:
initialize_mongodb_connection()
return mongo_db |