OSDN Git Service

[REM] inout
[iphwproject/opentck3.git] / chk_json.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 __licence__ = "GNU/GPLv3"
4 __author__ = "Marcelo Zunino (InfoPrimo SL) 2015-2017"
5
6 # from datetime import date, datetime
7 import sys
8 import os.path
9
10 import sqlite3
11 import re
12 import logging
13 from time import strftime
14 from util import config
15 from glob import glob
16
17
18
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)
23
24 #  iPath = "/admi/informes/"
25 #  oPath = "/admi/pazos4/"
26 #  iPrefijo = "Salidapazosnuevo-1-201"
27
28 iPrefijo = config.iPrefijo
29 iPath = config.iPath
30 oPath = config.oPath
31 dbpath = oPath + '.spazos_tck.db'
32 tablename = config.tableName
33 ns = __name__
34
35
36 def end(msg=None):
37     msg = msg or "\n\tAlgo salió mal... FIN\n"
38     sys.stdout.write("\n\t%s\n\n" % (msg,))
39
40
41 def pick_input(iPath=iPath, iPrefijo=iPrefijo):
42     """
43     Lee el contenido del directorio de salidapazos (filtra prfijo del nombre de archivo/informe)
44
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.
48     """
49     # import ipdb; ipdb.set_trace()
50
51     if not iPrefijo or not iPath:
52         print("algo salió muy mal en %s " % (ns,))
53         sys.exit(1)
54
55     iPath += iPrefijo
56     digitos = re.compile('[0-9]{3,4}$')  # no menos de 3 dígitos y mas de 4 dígitos
57     try:
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))
63         end(msg)
64         sys.exit(0)
65
66     file_list.sort()
67     if len(file_list) > 0:
68         res = {}
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})
72     else:
73         msg = " %s No se leyó nungún informe. info_list está vacía!!" % ns
74         logging.error(msg)
75         end(msg)
76         sys.exit(1)
77
78     return res
79
80
81 class SqliteTckJson(object):
82
83     def __init__(self, db_path=dbpath, table_name=tablename, force=False):
84
85         if not db_path:
86             msg = " %s Falta el path para la db" % ns
87             logging.error(msg)
88             end(msg)
89             sys.exit(1)
90         if not os.path.isdir(config.oPath):
91             msg = " %s : %s El directorio no exixte." % (ns, config.oPath)
92             logging.error(msg)
93             end(msg)
94             sys.exit(1)
95         if not table_name:
96             msg = " %s : Falta en nombre de la tabla." % (ns, )
97             logging.error(msg)
98             end(msg)
99             sys.exit(1)
100
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)
106             db_con.close()
107             self.install()
108
109
110     def conn(self):
111         """
112             Conexión a la db
113             :return:        una concexión sqlite3
114         """
115
116         # dbpath = self.dbpath or None
117         try:
118             res = sqlite3.connect(self.db_path, detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES,
119                                   isolation_level=None)
120             # print res
121             if not res:
122                 print("No hay CONEXION")
123                 raise Exception
124         except Exception as err_msg:
125             logging.error(err_msg)
126             msg = ' %s Imposible conectar a %s.' % (ns, self.db_path,)
127             logging.warn(msg)
128             end(msg)
129             sys.exit(1)
130         return res
131
132     def close(self, cr, db):
133         """
134             bueno, eso, cierra la conexión a la db
135             :param cr:
136             :param db:
137             :return:  True or exit con mensaje
138         """
139         try:
140             cr.close()
141             db.close()
142         except Exception as err_msg:
143             msg = ' %s No se pudo cerrar la db.' % ns
144             logging.error(err_msg)
145             logging.warn(msg)
146             end(msg)
147             sys.exit(1)
148         return True
149
150     def install(self):
151         """
152             Crear db sqlite3 en `db_path`
153             :param db_path:
154             :return:
155         """
156         # dbpath = self.dbpath or None
157         # ipdb.set_trace()
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); '''
162         try:
163             db = self.conn()
164             cr = db.cursor()
165             cr.execute(init)
166             cr.close()
167         except Exception as err_msg:
168             logging.error(err_msg)
169             msg = ' %s No se pudo crear la db.' % ns
170             logging.warn(msg)
171             end(msg)
172             sys.exit(1)
173         return True
174
175     def test_table(self):
176         """
177             Verifica existencia db y tabla necesarias.
178             :param db_path:
179             :return: True o exit con aviso
180         """
181
182         table_name = self.table_name
183         res = False
184
185         sql = """SELECT 1 FROM sqlite_master WHERE type='table' AND name='%s';""" % (table_name,)
186         try:
187             db = self.conn()
188             cr = db.cursor()
189             cr.execute(sql)
190             test = cr.fetchone()
191             cr.close()
192
193             if not (isinstance(test, tuple) and test[0] == table_name):
194                 self.install()
195             res = True
196         except Exception as info_msg:
197             msg = '%s %s No existe %s. Fallo al intentar crear la tabla.' % (info_msg, ns, table_name)
198             logging.error(msg)
199             print msg, ' test_table'
200             sys.exit(1)
201
202         return res
203
204     def refresh_db(self):
205
206         db = self.conn()
207         cr = db.cursor()
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;
212
213     def json_a_procesar(self):
214         """
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.
217
218         :param db_path:  ubicación de la db del historial
219         :return:
220         """
221
222         self.test_table()
223         try:
224             db = self.conn()
225             cr = db.cursor()
226             cr.execute('''SELECT cod_inifin FROM spazosjson ORDER BY id;''')
227             proc = cr.fetchall()
228             self.close(cr, db)
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'
233             logging.warn(msg)
234             sys.exit(1)
235
236         _inifin_done = [int(i[0].encode('utf-8')) for i in proc if isinstance(proc, list)]
237         _inifin_done.sort()
238
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 ]
242         for i in candidatos:
243             if i not in _inifin_done:
244                 result.append(candidatos[i])
245
246         result.sort()
247
248         return result
249
250     def resgister_json_history_db(self, info, fecha, jsonfile):
251         """
252             Crea el registo para el historial/control
253
254             :param info:
255             :param fecha:
256             :param jsonfile:
257             :param db_path:
258             :return:
259         """
260
261         try:
262
263             db = self.conn()
264             cr = db.cursor()
265
266             origen = info
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")
270             destino = jsonfile
271
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)
274
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'
279             logging.warn(msg)
280             sys.exit(1)
281
282         cr.execute(sql0 + sql1)
283
284
285 # import ipdb;ipdb.set_trace()
286 if __name__ == '__main__':
287
288     db_obj = SqliteTckJson()
289     db_obj.test_table()
290
291     db = db_obj.conn()
292     cr = db.cursor()
293     cr.execute('''SELECT * FROM spazosjson''')
294     rows = cr.fetchall()
295
296     db_obj.close(cr, db)
297
298     if rows:
299         for row in rows:
300             print row
301     else:
302         print 'foi'
303
304     if len(rows) >= 1825:
305         db_obj.refresh_db()