-
Notifications
You must be signed in to change notification settings - Fork 2
/
__init__.py
281 lines (224 loc) · 7.99 KB
/
__init__.py
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
# coding: utf-8
"""
Base para desarrollo de modulos externos.
Para obtener el modulo/Funcion que se esta llamando:
GetParams("module")
Para obtener las variables enviadas desde formulario/comando Rocketbot:
var = GetParams(variable)
Las "variable" se define en forms del archivo package.json
Para modificar la variable de Rocketbot:
SetVar(Variable_Rocketbot, "dato")
Para obtener una variable de Rocketbot:
var = GetVar(Variable_Rocketbot)
Para obtener la Opcion seleccionada:
opcion = GetParams("option")
Para instalar librerias se debe ingresar por terminal a la carpeta "libs"
pip install <package> -t .
"""
import os
import sys
import pymysql
import pandas as pd
import datetime
from decimal import Decimal
# Add modules libraries to Rocektbot
# -----------------------------------
base_path = tmp_global_obj["basepath"]
cur_path = os.path.join(base_path, 'modules', 'mysql', 'libs')
cur_path_x64 = os.path.join(cur_path, 'Windows' + os.sep + 'x64' + os.sep)
cur_path_x86 = os.path.join(cur_path, 'Windows' + os.sep + 'x86' + os.sep)
if sys.maxsize >= 2**32 and cur_path_x64 not in sys.path:
sys.path.append(cur_path_x64)
if sys.maxsize < 2**32 and cur_path_x86 not in sys.path:
sys.path.append(cur_path_x86)
def import_lib(relative_path, name, class_name=None):
"""
- relative_path: library path from the module's libs folder
- name: library name
- class_name: class name to be imported. As 'from name import class_name'
"""
import importlib.util
cur_path = base_path + 'modules' + os.sep + \
'mysql' + os.sep + 'libs' + os.sep
spec = importlib.util.spec_from_file_location(
name, cur_path + relative_path)
foo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foo)
if class_name is not None:
return getattr(foo, class_name)
return foo
global mysql_module
# Globals declared here
global mod_mysql_sessions
# Default declared here
SESSION_DEFAULT = "default"
# Initialize settings for the module here
try:
if not mod_mysql_sessions:
mod_mysql_sessions = {SESSION_DEFAULT: {}}
except NameError:
mod_mysql_sessions = {SESSION_DEFAULT: {}}
module = GetParams("module")
if module == "connect":
host = GetParams("host")
port = GetParams("port")
user = GetParams("user")
password = GetParams("pass")
database = GetParams("db")
session = GetParams('session')
var_ = GetParams("result")
try:
if sys.maxsize > 2**32:
create_engine = import_lib(f"Windows{os.sep}x64{os.sep}sqlalchemy{os.sep}__init__.py", "sqlalchemy", "create_engine") # from sqlalchemy import create_engine
if sys.maxsize > 32:
create_engine = import_lib(f"Windows{os.sep}x86{os.sep}sqlalchemy{os.sep}__init__.py", "sqlalchemy", "create_engine") #
if not port or port == "":
port = 3306
port = int(port)
if not session:
session = SESSION_DEFAULT
r = pymysql.connect(host=host, port=port, user=user, password=password, database=database)
res = r.open
mysql_module = {
'port': port,
'host': host,
'user': user,
'password': password,
'database': database,
'autocommit': True
}
conn = pymysql.connect(**mysql_module)
cursor = conn.cursor(pymysql.cursors.DictCursor)
mod_mysql_sessions[session] = {
"connection": r,
"cursor": cursor,
"engine": None
}
engine = create_engine(
f"mysql+pymysql://{user}:{password}@{host}:{port}/{database}",
echo=False
)
mod_mysql_sessions[session]["engine"] = engine
#r.close()
SetVar( var_, res)
except Exception as e:
PrintException()
raise Exception(e)
if module =="query":
query = GetParams("query")
session = GetParams('session')
var_ = GetParams("result")
try:
if not session:
session = SESSION_DEFAULT
cursor = mod_mysql_sessions[session]["cursor"]
conn = mod_mysql_sessions[session]["connection"]
cursor.execute(query)
if query.upper().startswith('SELECT'):
data_ = cursor.fetchall() # Traer los resultados de un select
for r in data_:
for d in r:
if isinstance(r[d], datetime.date):
r[d] = r[d].strftime("%d-%m-%Y %H:%M:%S")
if isinstance(r[d], Decimal):
r[d] = float(r[d])
data = data_
else:
conn.commit()
# Hacer efectiva la escritura de datos
data = True
#conn.close()
SetVar(var_, data)
except Exception as e:
print("\x1B[" + "31;40mAn error occurred\u2193\x1B[" + "0m")
PrintException()
conn.close()
raise Exception(e)
if module =="manyUpdates":
session = GetParams("session")
query = GetParams("table")
colum_values = GetParams("list1")
clausulas_values = GetParams("list2")
oneTable = GetParams("onetable")
var_ = GetParams("result1")
try:
if not session:
session = SESSION_DEFAULT
cursor = mod_mysql_sessions[session]["cursor"]
conn = mod_mysql_sessions[session]["connection"]
colum_values = eval(colum_values)
clausulas_values = eval(clausulas_values)
if oneTable:
data = list(zip(colum_values, clausulas_values))
else:
data = list(zip(*colum_values, clausulas_values))
cursor.executemany(query, data)
conn.commit()
data = True
SetVar(var_, data)
except Exception as e:
print("\x1B[" + "31;40mAn error occurred\u2193\x1B[" + "0m")
PrintException()
conn.close()
raise Exception(e)
if module =="importData":
session = GetParams('session')
hoja = GetParams('hoja')
schema = GetParams('schema')
tabla = GetParams('tabla')
path_file = GetParams('path_file')
chunk = GetParams('chunk')
method = GetParams('method')
try:
if not session:
session = SESSION_DEFAULT
if chunk:
chunk = int(chunk)
else:
chunk = None
if not method or method == "None":
method = None
if not tabla:
raise Exception("Debe Escribir el nombre de la tabla")
engine = mod_mysql_sessions[session]["engine"]
if hoja:
df = pd.read_excel(path_file, sheet_name=hoja, engine='openpyxl')
else:
df = pd.read_excel(path_file, engine='openpyxl')
df.to_sql(tabla, con=engine, schema=schema, if_exists='replace', index=False, chunksize=chunk, method=method)
except Exception as e:
print("\x1B[" + "31;40mAn error occurred\u2193\x1B[" + "0m")
PrintException()
raise e
if module == "close":
session = GetParams('session')
if not session:
session = SESSION_DEFAULT
cursor = mod_mysql_sessions[session]["cursor"]
con = mod_mysql_sessions[session]["connection"]
try:
cursor.close()
con.close()
except Exception as e:
PrintException()
raise e
if module == "getLastInsertedId":
session = GetParams('session')
var_ = GetParams("result")
if not session:
session = SESSION_DEFAULT
cursor = mod_mysql_sessions[session]["cursor"]
conn = mod_mysql_sessions[session]["connection"]
table = GetParams("table")
primaryKey = GetParams("primaryKey")
if not primaryKey:
primaryKey = "id"
query = f"SELECT * FROM {table} WHERE {primaryKey}=(SELECT LAST_INSERT_ID())"
cursor.execute(query)
data_ = cursor.fetchall() # Traer los resultados de un select
for r in data_:
for d in r:
if isinstance(r[d], datetime.date):
r[d] = r[d].strftime("%d-%m-%Y %H:%M:%S")
data = data_
SetVar(var_, data)