└── importar.py /importar.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | import os 5 | import psycopg2 6 | import psycopg2.extensions 7 | 8 | pasta = '/tmp/importacao' 9 | arquivos = os.listdir(pasta) 10 | 11 | try: 12 | conn = psycopg2.connect("dbname='fotosensores' user='fotosensores' host='localhost' password='1234'") 13 | conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT) 14 | except: 15 | print "Erro ao conectar ao banco de dados" 16 | exit() 17 | 18 | c = conn.cursor() 19 | c.execute("set client_encoding to latin1") 20 | 21 | for a in arquivos: 22 | nome_tabela = a.split(".")[0] 23 | try: 24 | c.execute("""select * from log_importacao where tabela = '%s'""" % (nome_tabela)) 25 | dados_tabela = c.fetchone() 26 | if dados_tabela == None or dados_tabela[5] == False: 27 | c.execute("""alter table %s disable trigger all""" % (nome_tabela)) 28 | c.execute("""insert into log_importacao(tabela,inicio) values ('%s',current_timestamp)""" % (nome_tabela)) 29 | c.execute("""copy %s from '%s/%s' csv""" % (nome_tabela,pasta,a) ) 30 | c.execute("""select count(*) from %s""" % (nome_tabela)) 31 | num_linhas = int(c.fetchone()[0]) 32 | c.execute("""update log_importacao set linhas = %d, sucesso = true, fim = current_timestamp where tabela = '%s'""" % (num_linhas,nome_tabela)) 33 | except psycopg2.Error as erro: 34 | print """Erro co copiar tabela %s""" % (nome_tabela) 35 | c.execute("""update log_importacao set fim = current_timestamp, erro = '%s' where tabela = '%s' """ % (erro, nome_tabela)) 36 | finally: 37 | c.execute("""alter table %s enable trigger all""" % (nome_tabela)) 38 | 39 | --------------------------------------------------------------------------------