2 # -*- coding: utf-8 -*-
3 __licence__ = "GNU/GPLv3"
4 __author__ = "Marcelo Zunino (InfoPrimo SL) 2015-2017"
6 # from datetime import date, datetime
13 from time import strftime
14 from util import config
19 # logfile = './log/spn2json_chk.log'
20 # os.path.isdir('./log') or os.mkdir('./log')
21 # os.path.isfile(logfile) or os.system("touch %s" % logfile)
22 # logging.basicConfig(format='%(asctime)s %(message)s', filename=logfile, level=logging.INFO)
24 # iPath = "/admi/informes/"
25 # oPath = "/admi/pazos4/"
26 # iPrefijo = "Salidapazosnuevo-1-201"
28 iPrefijo = config.iPrefijo
31 dbpath = oPath + '.spazos_tck.db'
32 tablename = config.tableName
37 msg = msg or "\n\tAlgo salió mal... FIN\n"
38 sys.stdout.write("\n\t%s\n\n" % (msg,))
41 def pick_input(iPath=iPath, iPrefijo=iPrefijo):
43 Lee el contenido del directorio de salidapazos (filtra prfijo del nombre de archivo/informe)
45 :param iPath: path al directorio de informes
46 :param iPrefijo: "Salidapazosnuevo-1-20*"
47 :return: Lista de archivos candidatos a ser porcesados para generar el json.
49 # import ipdb; ipdb.set_trace()
51 if not iPrefijo or not iPath:
52 print("algo salió muy mal en %s " % (ns,))
56 digitos = re.compile('[0-9]{3,4}$') # no menos de 3 dígitos y mas de 4 dígitos
58 file_list = glob(iPath)
59 except Exception as err_msg:
60 logging.error(err_msg)
61 msg = " [ Warninig ] : No se leyó nungún informe. "
62 logging.warn(" %s %s " % (ns, msg))
67 if len(file_list) > 0:
69 for info_file in file_list:
70 if digitos.match(info_file[info_file.index('.') + 1:]):
71 res.update({int(info_file[info_file.index('.') + 1:]): info_file})
73 msg = " %s No se leyó nungún informe. info_list está vacía!!" % ns
81 class SqliteTckJson(object):
83 def __init__(self, db_path=dbpath, table_name=tablename, force=False):
86 msg = " %s Falta el path para la db" % ns
90 if not os.path.isdir(config.oPath):
91 msg = " %s : %s El directorio no exixte." % (ns, config.oPath)
96 msg = " %s : Falta en nombre de la tabla." % (ns, )
101 self.db_path = db_path
102 self.table_name = table_name
103 if not os.path.isfile(db_path) or force:
104 #import ipdb;ipdb.set_trace()
105 db_con = sqlite3.connect(db_path)
113 :return: una concexión sqlite3
116 # dbpath = self.dbpath or None
118 res = sqlite3.connect(self.db_path, detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES,
119 isolation_level=None)
122 print("No hay CONEXION")
124 except Exception as err_msg:
125 logging.error(err_msg)
126 msg = ' %s Imposible conectar a %s.' % (ns, self.db_path,)
132 def close(self, cr, db):
134 bueno, eso, cierra la conexión a la db
137 :return: True or exit con mensaje
142 except Exception as err_msg:
143 msg = ' %s No se pudo cerrar la db.' % ns
144 logging.error(err_msg)
152 Crear db sqlite3 en `db_path`
156 # dbpath = self.dbpath or None
158 # if not os.path.isfile(dbpath) or force:
159 init = '''CREATE TABLE if not exists spazosjson(id INTEGER PRIMARY KEY AUTOINCREMENT, origen TEXT NOT
160 NULL UNIQUE, cod_inifin TEXT NOT NULL UNIQUE, fecha_opera DATE NOT NULL UNIQUE, fecha_lectura DATE NOT
161 NULL, destino TEXT NOT NULL UNIQUE); '''
167 except Exception as err_msg:
168 logging.error(err_msg)
169 msg = ' %s No se pudo crear la db.' % ns
175 def test_table(self):
177 Verifica existencia db y tabla necesarias.
179 :return: True o exit con aviso
182 table_name = self.table_name
185 sql = """SELECT 1 FROM sqlite_master WHERE type='table' AND name='%s';""" % (table_name,)
193 if not (isinstance(test, tuple) and test[0] == table_name):
196 except Exception as info_msg:
197 msg = '%s %s No existe %s. Fallo al intentar crear la tabla.' % (info_msg, ns, table_name)
199 print msg, ' test_table'
204 def refresh_db(self):
208 # si se reinstala : "CREATE TABLE spazosbak AS SELECT * FROM spazosjson;"
209 cr.execute("insert into spazosbak select * from spazosjson;")
210 cr.execute("delete from spazosjson;")
211 # create table spazosbak AS select * from spazosjson;
213 def json_a_procesar(self):
215 Filtra la lista de informes disponibles contra el historial de informes procesados.
216 retornando la lista de aquellos que no encuentra en el historial.
218 :param db_path: ubicación de la db del historial
226 cr.execute('''SELECT cod_inifin FROM spazosjson ORDER BY id;''')
229 except Exception as err_msg:
230 logging.error(err_msg)
231 msg = " %s : [ Error ] : No se leyó nungún informe. " % (ns,)
232 print msg, ns, ' json_a_procesar'
236 _inifin_done = [int(i[0].encode('utf-8')) for i in proc if isinstance(proc, list)]
239 # se lee la carpeta de informes disponibles.
240 candidatos = pick_input()
241 result = [] # candidatos[i] for i in candidatos if i not in _inifin_done ]
243 if i not in _inifin_done:
244 result.append(candidatos[i])
250 def resgister_json_history_db(self, info, fecha, jsonfile):
252 Crea el registo para el historial/control
267 cod_inifin = info[info.index('.') + 1:]
268 fecha_opera = fecha[:4] + '-' + fecha[4:6] + '-' + fecha[6:8]
269 fecha_lectura = strftime("%0Y.%0m.%0d %0H:%M:%0S")
272 sql0 = "INSERT INTO spazosjson(origen,cod_inifin,fecha_opera,fecha_lectura,destino) VALUES("
273 sql1 = "'%s','%s','%s','%s','%s');" % (origen, cod_inifin, fecha_opera, fecha_lectura, destino)
275 except Exception as err_msg:
276 logging.error(err_msg)
277 msg = " %s : [ Error ] : No se leyó nungún informe. " % (ns,)
278 print msg, ns, ' json_a_procesar'
282 cr.execute(sql0 + sql1)
285 # import ipdb;ipdb.set_trace()
286 if __name__ == '__main__':
288 db_obj = SqliteTckJson()
293 cr.execute('''SELECT * FROM spazosjson''')
304 if len(rows) >= 1825: