Update modules/database/database_init.py
Browse files- modules/database/database_init.py +104 -19
modules/database/database_init.py
CHANGED
@@ -1,31 +1,116 @@
|
|
1 |
-
#modules/database/database_init.py
|
|
|
2 |
import os
|
3 |
-
from azure.cosmos import CosmosClient
|
4 |
import logging
|
|
|
|
|
|
|
5 |
|
|
|
6 |
logger = logging.getLogger(__name__)
|
7 |
|
8 |
-
#
|
9 |
-
|
|
|
|
|
|
|
|
|
|
|
10 |
|
11 |
-
|
12 |
-
|
13 |
-
|
|
|
|
|
|
|
|
|
14 |
try:
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
19 |
|
20 |
-
|
21 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
22 |
return True
|
23 |
except Exception as e:
|
24 |
-
logger.error(f"Error
|
25 |
return False
|
26 |
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# 1. modules/database/database_init.py
|
2 |
+
|
3 |
import os
|
|
|
4 |
import logging
|
5 |
+
from azure.cosmos import CosmosClient
|
6 |
+
from pymongo import MongoClient
|
7 |
+
import certifi
|
8 |
|
9 |
+
logging.basicConfig(level=logging.DEBUG)
|
10 |
logger = logging.getLogger(__name__)
|
11 |
|
12 |
+
# Variables globales para Cosmos DB SQL API
|
13 |
+
cosmos_client = None
|
14 |
+
user_database = None
|
15 |
+
user_container = None
|
16 |
+
application_requests_container = None
|
17 |
+
user_feedback_container = None
|
18 |
+
user_sessions_container = None
|
19 |
|
20 |
+
# Variables globales para Cosmos DB MongoDB API
|
21 |
+
mongo_client = None
|
22 |
+
mongo_db = None
|
23 |
+
|
24 |
+
###################################################################
|
25 |
+
def verify_container_partition_key(container, expected_path):
|
26 |
+
"""Verifica la configuraci贸n de partition key de un contenedor"""
|
27 |
try:
|
28 |
+
container_props = container.read()
|
29 |
+
partition_key_paths = container_props['partitionKey']['paths']
|
30 |
+
logger.info(f"Container: {container.id}, Partition Key Paths: {partition_key_paths}")
|
31 |
+
return expected_path in partition_key_paths
|
32 |
+
except Exception as e:
|
33 |
+
logger.error(f"Error verificando partition key en {container.id}: {str(e)}")
|
34 |
+
return False
|
35 |
+
|
36 |
+
###################################################################
|
37 |
+
def get_container(container_name):
|
38 |
+
"""Obtiene un contenedor espec铆fico"""
|
39 |
+
global user_container, user_sessions_container
|
40 |
+
|
41 |
+
if not initialize_cosmos_sql_connection():
|
42 |
+
logger.error("No se pudo inicializar la conexi贸n")
|
43 |
+
return None
|
44 |
+
|
45 |
+
containers = {
|
46 |
+
"users": user_container,
|
47 |
+
"users_sessions": user_sessions_container
|
48 |
+
}
|
49 |
+
|
50 |
+
return containers.get(container_name)
|
51 |
+
|
52 |
+
###################################################################
|
53 |
+
def initialize_cosmos_sql_connection():
|
54 |
+
"""Inicializa la conexi贸n a Cosmos DB SQL API"""
|
55 |
+
global cosmos_client, user_database, user_container, user_sessions_container
|
56 |
+
|
57 |
+
try:
|
58 |
+
if cosmos_client and user_database and user_container and user_sessions_container:
|
59 |
+
return True
|
60 |
+
|
61 |
+
cosmos_endpoint = os.environ.get("COSMOS_ENDPOINT")
|
62 |
+
cosmos_key = os.environ.get("COSMOS_KEY")
|
63 |
|
64 |
+
if not cosmos_endpoint or not cosmos_key:
|
65 |
+
raise ValueError("COSMOS_ENDPOINT y COSMOS_KEY deben estar configurados")
|
66 |
+
|
67 |
+
cosmos_client = CosmosClient(cosmos_endpoint, cosmos_key)
|
68 |
+
user_database = cosmos_client.get_database_client("user_database")
|
69 |
+
|
70 |
+
# Inicializar contenedores manteniendo la estructura existente
|
71 |
+
user_container = user_database.get_container_client("users")
|
72 |
+
user_sessions_container = user_database.get_container_client("users_sessions")
|
73 |
+
|
74 |
+
logger.info("Conexi贸n a Cosmos DB SQL API exitosa")
|
75 |
+
return True
|
76 |
+
|
77 |
+
except Exception as e:
|
78 |
+
logger.error(f"Error al conectar con Cosmos DB SQL API: {str(e)}")
|
79 |
+
return False
|
80 |
+
|
81 |
+
###################################################################
|
82 |
+
def initialize_mongodb_connection():
|
83 |
+
"""Inicializa la conexi贸n a MongoDB"""
|
84 |
+
global mongo_client, mongo_db
|
85 |
+
try:
|
86 |
+
connection_string = os.getenv("MONGODB_CONNECTION_STRING")
|
87 |
+
if not connection_string:
|
88 |
+
raise ValueError("MONGODB_CONNECTION_STRING debe estar configurado")
|
89 |
+
|
90 |
+
mongo_client = MongoClient(
|
91 |
+
connection_string,
|
92 |
+
tls=True,
|
93 |
+
tlsCAFile=certifi.where(),
|
94 |
+
retryWrites=False,
|
95 |
+
serverSelectionTimeoutMS=5000,
|
96 |
+
connectTimeoutMS=10000,
|
97 |
+
socketTimeoutMS=10000
|
98 |
+
)
|
99 |
+
|
100 |
+
mongo_db = mongo_client['aideatext_db']
|
101 |
return True
|
102 |
except Exception as e:
|
103 |
+
logger.error(f"Error conectando a MongoDB: {str(e)}")
|
104 |
return False
|
105 |
|
106 |
+
###################################################################
|
107 |
+
def initialize_database_connections():
|
108 |
+
"""Inicializa todas las conexiones"""
|
109 |
+
return initialize_cosmos_sql_connection() and initialize_mongodb_connection()
|
110 |
+
|
111 |
+
###################################################################
|
112 |
+
def get_mongodb():
|
113 |
+
"""Obtiene la conexi贸n MongoDB"""
|
114 |
+
if mongo_db is None:
|
115 |
+
initialize_mongodb_connection()
|
116 |
+
return mongo_db
|