diff --git a/PC/FileToSql.py b/PC/FileToSql.py index a73adb47da83ece4b14fc8b33e921a9f7fad3992..c1a1b8fd46e14d9a11a5875d7f1125ce2ebc186f 100644 --- a/PC/FileToSql.py +++ b/PC/FileToSql.py @@ -5,6 +5,8 @@ import os import csv import shutil from datetime import datetime +import magic +from zipfile import ZipFile def formatLigneCorrect(row): try : @@ -73,6 +75,7 @@ def recuperationId(db): log = open("logBDD.txt", "w") FOLDER = "./data/" TRAITEES = "./traitees/" +TRASH = "./corrompu/" # ================ CONNECTION BDD ================== # db = initBDD() @@ -84,9 +87,6 @@ while(True): topics = [] tabId = {} - DIR = os.listdir(FOLDER) - DIR.sort() - try : # ================ RECUPERATION TOPIC ================= # topics = recuperationTopic(db) @@ -101,11 +101,31 @@ while(True): continue cursor = db.cursor(); + + # Extraction des archives dans un dossier temporaire puis suppression de l'archive + DIR = os.listdir(FOLDER) - #--- Parcours les fichiers, ajoute les valeurs en base et supprime le fichier for f in DIR: print(FOLDER+f) - with open(FOLDER+f,'r') as csvfile: + if not os.path.isdir(FOLDER+f): + s = magic.from_file(FOLDER+f, mime=True) + if s == "application/zip": + try: + ZipFile.extractall(ZipFile(FOLDER+f, 'r'), FOLDER+"temp") + os.remove(FOLDER+f) + except: + shutil.move(FOLDER+f, TRASH+f) + else: + shutil.move(FOLDER+f, TRASH+f) + + #--- Parcours les fichiers, ajoute les valeurs en base et deplace le fichier + DIR = os.listdir(FOLDER+"temp") + DIR.sort() + + for f in DIR: + print(FOLDER+"temp/"+f) + + with open(FOLDER+"temp/"+f,'r') as csvfile: try: #--- Recupere la source du fichier id = csvfile.readline().strip().split(":")[1] @@ -122,7 +142,8 @@ while(True): t = topic.split("/") source = str(t[0]) col = int(t[1]) - if id == source : + if id == source : + # Ne pas inserer les doublons (date/idCapteur) requete = "INSERT INTO `valeur` (`temps`, `valeur`, `idCapteur`) VALUES ('"+str(date).strip()+"', '"+str(row[col+1]).strip()+"', '"+str(tabId[topic])+"')" cursor.execute(requete) @@ -143,7 +164,7 @@ while(True): print(ex); db.commit(); #os.remove(FOLDER+f) - shutil.move(FOLDER+f, TRAITEES+f) + shutil.move(FOLDER+"temp/"+f, TRAITEES+f) try: print("============= Fin de cycle ============") time.sleep(300) # Ajout des nouveaux fichiers en base toutes les 5 minutes