Exemplo n.º 1
0
    def to_string(self, d, attr=None, ret=False):

        try:
            out_json = JsonHelper().to_json(d, attr)
            texto = json.dumps(out_json, indent=4, sort_keys=True)
        except Exception as exc:
            IOSistema().PrintLine('(X) [to_string] ERROR: %s' % (str(exc)))
            texto = str(d)
        finally:
            if ret:
                return texto
            else:
                IOSistema().PrintLine(texto)
Exemplo n.º 2
0
    def __init__(self, nombre, claves):

        self.io_nul = IOEscritor(IOSistema().DevNull())
        self.nombre = nombre
        self._contadores = dict()
        for clave in claves:
            self._contadores[clave] = {'ini': 0, 'fin': 0, 'tot': 0}
Exemplo n.º 3
0
    def Finalizar(self):

        self.tiempo_fin = self.FechaAGMT(Fecha.Ahora().get_val())

        IOSistema().PrintLine(
            '(t) [%s] FIN %s (%s)' %
            (self._msg, self.FechaAString(self.tiempo_fin),
             self.TimespanAString(self.tiempo_fin - self.tiempo_ini)))
Exemplo n.º 4
0
    def ExportarCSV(self,
                    archivo_csv_output,
                    tabla='',
                    gen_script=False,
                    archivo_sql_output='',
                    append=False):

        query_select = self.ArmarSelect(tabla)
        [columnas, datos, result] = self.RealizarQuery(query_select)

        if columnas is None or datos is None:
            IOSistema().PrintLine(
                '[ConexionBases] Warning: (%s) El query no arrojo ningun resultado'
                % (archivo_csv_output))
            IOSistema().PrintLine('[Result]: %s' % (result))
            columnas = []
            datos = []

        headerstruc = [DatoStr(c, True) for c in columnas]
        csvw = CSVEscritor(archivo_csv_output, headerstruc)
        csvw.EscribirDatos(datos)

        def format_comillas(nombre):
            if ' ' in nombre or '/' in nombre or nombre[
                    0] in '1234567890-' or nombre.lower() in ['any']:
                return '"%s"' % (nombre)
            else:
                return nombre

        if gen_script:
            com_tabla = format_comillas(tabla)
            if archivo_sql_output == '':
                archivo_sql_output = '%s.sql' % (archivo_csv_output)
            f = open(archivo_sql_output, 'a+' if append else 'w+')
            f.write('\n---------- %s ----------";' % (com_tabla))
            f.write('\nDROP TABLE IF EXISTS %s;' % (com_tabla))
            f.write('\nCREATE TABLE %s ();' % (com_tabla))
            for columna in columnas:
                com_columna = format_comillas(columna)
                f.write('\nALTER TABLE %s ADD COLUMN %s VARCHAR;' %
                        (com_tabla, com_columna))
            f.write('\nSET CLIENT_ENCODING=\'LATIN1\';')
            f.write('\nCOPY %s FROM \'%s\' WITH DELIMITER \',\' CSV HEADER;' %
                    (com_tabla, os.path.abspath(archivo_csv_output).replace(
                        '\\', '/')))
            f.close()
Exemplo n.º 5
0
    def Incrementar(self):

        self._contador = self._contador + 1
        self._porc_nue = int(self._contador * 100 / self._total)
        if self._porc_nue % self._avance == 0 and self._porc_nue != self._porc_ult:
            IOSistema().Print('%s%% ' % (self._porc_nue))
            self._porc_ult = self._porc_nue
        if self._porc_ult >= 100:
            self.Finalizar()
Exemplo n.º 6
0
    def XPathSafeProp(self, elem, path, prop, default=''):

        try:
            res = elem.xpath(path)
            if not res: return default
            txt = Encoding().NormalizarTexto(res[0].get(prop))
            return txt
        except Exception as e:
            IOSistema().PrintLine(e)
            return '[ERROR-xpathprop]'
Exemplo n.º 7
0
Arquivo: CSV.py Projeto: alejsch/horno
    def __init__(self, archivo_csv_output='nul', headerstruc=None, escribir_header=True, delim=',', quote='"', quoting=csv.QUOTE_ALL):
        
        self._nombre = archivo_csv_output
        self._archivo = archivo_csv_output
        self._headerstruc = headerstruc
        self._escribir_header = escribir_header
        self._delim = delim
        self._quote = quote
        self._quoting = quoting

        if archivo_csv_output.Existe():
            IOSistema().PrintLine('[ %s ] Warning: El archivo ya existe' % (archivo_csv_output))
        if not archivo_csv_output.CarpetaPadre().Existe():
            IOSistema().PrintLine('[ %s ] Warning: La carpeta no existe, creando..' % (archivo_csv_output))
            archivo_csv_output.CarpetaPadre().Crear()

        self._writer = csv.writer(open(archivo_csv_output.Ruta(), 'wb'), delimiter=self._delim, quotechar=self._quote, quoting=self._quoting)
        
        if self._escribir_header:
            self.EscribirHeader()
Exemplo n.º 8
0
    def to_markdown(self, d, ret=False, nivel=0, lista=False):

        try:
            texto = ''
            espacios_gap = 2
            if isinstance(d, str):
                texto += '%s%s\n' % (' ' * (nivel), d)
            elif isinstance(d, list):
                for e in d:
                    texto += JsonHelper().to_markdown(e, ret, nivel+espacios_gap, lista=True)
            elif isinstance(d, dict):
                for (dic_k, dic_v) in d.items():
                    espacios = len(dic_k) - len(dic_k.lstrip())
                    texto += '%s%s: %s' % (' ' * (nivel), dic_k, '' if isinstance(dic_v, str) else '\n')
                    texto += JsonHelper().to_markdown(dic_v, ret, (nivel+espacios)+espacios_gap)
        except Exception as exc:
            IOSistema().PrintLine('(X) [to_markdown] ERROR: %s' % (str(exc)))
        finally:
            if ret:
                return texto
            else:
                IOSistema().PrintLine(texto)
Exemplo n.º 9
0
    def log(self, log_file_rel, texto):

        log_file = self.get_log_file(log_file_rel)
        with IOEscritor.DeRuta(log_file).Abrir(append=True,
                                               binario=False) as iow:
            if self.timestamp:
                fecha_ahora = Fecha.Ahora()
                sep = '-' * self.sep_len + '\n'
                iow.Escribir(sep +
                             ('%s' %
                              (fecha_ahora.to_human("%Y-%m-%d %H:%M:%S"))) +
                             '\n')
            iow.Escribir(str(texto) + '\n')

        if self.printear:
            IOSistema().PrintLine(str(texto))
Exemplo n.º 10
0
    def XPathSafeText(self, elem, paths, default=''):

        try:
            if type(elem) in [str, bytes] or any([
                    t in str(type(elem))
                    for t in ['_ElementStringResult', '_ElementUnicodeResult']
            ]):
                return Encoding().NormalizarTexto(elem)
            if not type(paths) == list:
                paths = [paths]
            for path in paths:
                res = elem.xpath(path)
                if not res: continue
                txt = Encoding().NormalizarTexto(res[0]).strip()
                if not txt: continue
                return txt
            return default
        except Exception as e:
            IOSistema().PrintLine(e)
            return '[ERROR-xpathtext]'
Exemplo n.º 11
0
Arquivo: CSV.py Projeto: alejsch/horno
    def LeerRegistros(self):

        info = {'reg_repetidos':[], 'reg_erroneos':[], 'info_repetidos':[], 'info_erroneos':[], }

        if not self._archivo.Existe():
            IOSistema().PrintLine('[ %s ] Error: El archivo no existe' % (self._archivo))
            exit()

        self._datos.clear()
        self._archivo.RepararEncoding()

        progreso = Progreso(5, self.ContarRegistros(), '[ %s ] Leyendo' % (self._archivo))

        with IOLector(self._archivo).Abrir(binario=True) as ior:
        
            self._reader = csv.reader(ior.Stream(), delimiter=self._delim, quotechar=self._quote)
    
            for hdr in self._reader:
                self._header = Encoding().NormalizarLista([h.lower() for h in hdr]) 
                break
    
            for dato in self._reader:
                try:
                    progreso.Incrementar()

                    reg = self.RegistroUsandoDato(dato)
                    key = self._func_reg_id(reg)
                    if key not in self._datos:
                        self._datos[key] = []
                    else:
                        info['reg_repetidos'].append(reg)
                        info['info_repetidos'].append(key)
                    self._datos[key].append(Encoding().NormalizarLista(dato))
                    
                except Exception as e:
                    info['reg_erroneos'].append(reg)
                    info['info_erroneos'].append(e)
    
        self._inicializado = True
        
        return info
Exemplo n.º 12
0
    def to_json(self, d, attr=None):

        try:

            if attr and hasattr(d, attr):
                d = getattr(d, attr)
            if not d:
                return {} 
            if isinstance(d, dict):
                return d
            if isinstance(d, str):
                return json.loads(d)
            if isinstance(d, bytes):
                return json.loads(d.decode('utf-8'))
            
            raise Exception('input invalido: %s' % (d))

        except Exception as exc:
            
            err = str(exc)
            IOSistema().PrintLine('(X) [to_json] ERROR: %s' % (err))
            return {}
Exemplo n.º 13
0
    def PrintLine(self, texto):

        self.Print(texto + IOSistema().NewLine())
Exemplo n.º 14
0
    def Iniciar(self):

        self.tiempo_ini = self.FechaAGMT(Fecha.Ahora().get_val())
        IOSistema().PrintLine('(t) [%s] INI %s' %
                              (self._msg, self.FechaAString(self.tiempo_ini)))
Exemplo n.º 15
0
    def Finalizar(self):

        if not self._finalizado:
            self._finalizado = True
            IOSistema().PrintLine('[OK]')
Exemplo n.º 16
0
    def Mostrar(self):

        IOSistema().PrintLine(
            'Hola, soy una VistaConsolaBase y me estoy mostrando')
Exemplo n.º 17
0
    def Iniciar(self):

        IOSistema().Print('%s (%s).. ' % (self._mensaje, self._total))

        if self._porc_ult >= 100 or self._total <= 0:
            self.Finalizar()
Exemplo n.º 18
0
    def Testear(self, texto):

        h = self.Encriptar(texto)
        IOSistema().PrintLine('Test de [ %s ]: texto = [ %s ] -> hash = [ %s ]; igual? = %s' % (self.Nombre(), texto, h, self.Comparar(texto, h)))