def csv2db_equipement(update):
    '''
    Le paramètre d'override update permet d'activer ou non l'écrasement du contenu actuel de la base de donnée par celui du fichier CSV
    Mettre à True pour mettre-à-jour
    '''

    if update:
        #get le CSV
        file_full_name = 'equipements.csv'
        file_path = PROJECT_ROOT + os.path.sep + 'data' + os.path.sep + 'csv' + os.path.sep + file_full_name
        file_E = open(file_path, 'r', encoding="utf8")
        read = csv.DictReader(file_E)

        tab_equipements = []
        # foreach sur le CSV et ajout dans un tableau pour ajout dans bdd
        for row in read:
            tab_equipements.append(
                (row['EquipementId'], row['EquNom'], row['InsNumeroInstall'],
                 row['EquGpsY'], row['EquGpsX']))

        try:
            conn = sqlite3.connect(DB_FULLPATH)
            cursor = conn.cursor()

            # DELETE les données afin d'éviter les doublons
            cursor.execute("""DELETE FROM equipement;""")

            # add les data du tableau tab_equipements dans la bdd
            cursor.executemany('INSERT INTO equipement VALUES (?,?,?,?,?)',
                               tab_equipements)

            conn.commit()
            printerr(
                file_full_name + ' dumped successfully into database ' +
                DB_FULL_NAME +
                ' (feel free to set `BOOL_IMPORT_CSV_ON_LAUNCH` to `False` in "src/server/config.py" to disable this behaviour)'
            )
        except Exception as e:
            conn.rollback()
            printerr(type(e))
            printerr('exception occured while attempted to store ' +
                     file_full_name + ' into database ' + DB_FULL_NAME)
            printerr('==============')
            printerr(e)
        finally:
            conn.close()
Exemplo n.º 2
0
def csv2db_installation(update):
    '''
    Le paramètre d'override update permet d'activer ou non l'écrasement du contenu actuel de la base de donnée par celui du fichier CSV
    Mettre à True pour mettre-à-jour
    '''

    if update:
        #get le CSV
        file_full_name = 'installations.csv'
        file_path = PROJECT_ROOT + os.path.sep + 'data' + os.path.sep + 'csv' + os.path.sep + file_full_name
        file_I = open(file_path,'r', encoding="utf8")
        read = csv.DictReader(file_I)

        tab_installation = []
        tab_addr = []

        # foreach sur le CSV et ajout dans un tableau pour ajout dans bdd
        for row in read:
            tab_installation.append((row["Numéro de l\'installation"]
                ,row['Nom usuel de l\'installation']
                ));

            tab_addr.append((
                row["Numéro de l\'installation"]
                ,row['Nom du lieu dit']+','+row['Numero de la voie']+','+row['Nom de la voie']
                ,row['Code postal']
                ,row['Nom de la commune']
            ))

        try:
            conn = sqlite3.connect(DB_FULLPATH)
            cursor = conn.cursor()

            # DELETE les donnees pour éviter les doublon
            cursor.execute("""DELETE FROM installation;""")
            cursor.execute("""DELETE FROM adresse;""")

            # add les data du tableau tab_installation et tab_addr dans la bdd
            cursor.executemany('INSERT INTO installation VALUES (?,?)', tab_installation)
            cursor.executemany('INSERT INTO adresse VALUES (?,?,?,?)', tab_addr)

            conn.commit()
            printerr(file_full_name + ' dumped successfully into database ' + DB_FULL_NAME + ' (feel free to set `BOOL_IMPORT_CSV_ON_LAUNCH` to `False` in "src/server/config.py" to disable this behaviour)')
        except Exception as e:
            conn.rollback()
            printerr(type(e))
            printerr('exception occured while attempted to store ' + file_full_name + ' into database ' + DB_FULL_NAME)
            printerr('==============')
        finally:
        	conn.close()
Exemplo n.º 3
0
def clear_db():
    '''
    Purge entièrement la base de données
    '''

    if os.path.exists(DB_FULLPATH):
        try:
            printerr('starting database emptying')
            conn = sqlite3.connect(DB_FULLPATH)
            cursor = conn.cursor()

            cursor.execute("""
                DROP TABLE IF EXISTS installation;
            """)
            cursor.execute("""
                DROP TABLE IF EXISTS adresse;
            """)
            cursor.execute("""
                DROP TABLE IF EXISTS equipements;
            """)
            cursor.execute("""
                DROP TABLE IF EXISTS activites;
            """)
            conn.commit()
            printerr('database emptied successfully')
        except Exception as e:
            conn.rollback()
            printerr('exception occurred while emptying database')
            printex(e)
        finally:
            conn.close()
Exemplo n.º 4
0
def create_db():
    '''
	Crée la base de données
    '''
    if not os.path.exists(DB_FULLPATH):
        path1 = PROJECT_ROOT + os.path.sep + 'data'

        # on crée le dossier s'il n'existe pas
        if not os.path.exists(path1):
            os.mkdir(path1)
            printerr('directory created : "' + path1 + '"')

        # on crée le dossier s'il n'existe pas
        if not os.path.exists(DB_DIR):
            os.mkdir(DB_DIR)
            printerr('directory created : "' + path1 + '"')

        try:
            printerr('starting database creation')
            conn = sqlite3.connect(DB_FULLPATH)
            cursor = conn.cursor()

            #numero== id instal
            cursor.execute("""CREATE TABLE IF NOT EXISTS installation(
                numero INTEGER PRIMARY KEY UNIQUE,
                nom TEXT
                )
            """)

            #numero == a numero dans installation
            cursor.execute("""CREATE TABLE IF NOT EXISTS adresse(
                numero INTEGER PRIMARY KEY UNIQUE,
                adresse TEXT,
                code_postal INTEGER,
                ville TEXT,
                FOREIGN KEY (numero) REFERENCES installation(numero)
                )
            """)

            #numero_equipements==EquipementId
            cursor.execute("""CREATE TABLE IF NOT EXISTS equipement(
                numero_equipements INTEGER PRIMARY KEY UNIQUE,
                nom TEXT,
                numero_installation INTEGER,
                latitude REAL,
                longitude REAL,
                FOREIGN KEY (numero_installation) REFERENCES installation(numero)
                )
            """)

            cursor.execute("""CREATE TABLE IF NOT EXISTS activite(
            
                id INTEGER PRIMARY KEY,
                numero_activites INTEGER,
                numero_equipements INTEGER,
                desc_act TEXT,
                nom TEXT,
                FOREIGN KEY (numero_equipements) REFERENCES equipements(numero_equipements)
                )
            """)

            conn.commit()
            printerr('table "adresse" successfully created')
            printerr('table "installation" successfully created')
            printerr('table "equipement" successfully created')
            printerr('table "activite" successfully created')
            printerr('database successfully created')
        except Exception as e:
            printerr('exception ocurred while creating database')
            printex(e)
            conn.rollback()
        finally:
            conn.close()
def dl_data(override = False):
	'''
	Le paramètre override permet d'activer ou non l'écrasement des CSV
	Activer pour les télécharger à nouveau les CSV même si les fichiers existent
	'''

	path1 = PROJECT_ROOT + os.path.sep + 'data'
	path2 = path1 + os.path.sep + 'csv'
	
	i_path = path2 + os.path.sep + 'installations.csv'
	i_url = 'http://data.paysdelaloire.fr/api/publication/23440003400026_J335/installations_table/content/?format=csv'
	
	e_path = path2 + os.path.sep + 'equipements.csv'
	e_url = 'http://data.paysdelaloire.fr/fileadmin/data/datastore/rpdl/sport/23440003400026_J336/equipements.csv'

	a_path = path2 + os.path.sep + 'activites.csv'
	a_url = 'http://data.paysdelaloire.fr/fileadmin/data/datastore/pdl/PLUS15000/J334_equipements_activites.csv'



	# ----------------- on crée l'arborescence si elle n'existe pas
	if not os.path.exists(path1):
		os.mkdir(path1);
		printerr('directory created : "' + path1 + '"')

	if not os.path.exists(path2):
		os.mkdir(path2);
		printerr('directory created : "' + path2 + '"')

	# ----------------- on y télécharge les fichiers CSV s'ils ny sont pas présents ou que l'écrasement a été spécifié
	if override or not os.path.isfile(i_path):
		printerr('fetching "installations" data from "' + i_url + '"')
		urllib.request.urlretrieve(i_url, i_path)
		printerr('file "installations.csv" created as "' + i_path + '"')

	if override or not os.path.isfile(e_path):
		printerr('fetching "equipements" data from "' + e_url + '"')
		urllib.request.urlretrieve(e_url, e_path)
		printerr('file "equipements.csv" created as "' + e_path + '"')
	
	if override or not os.path.isfile(a_path):
		printerr('fetching "activites" data from "' + a_url + '"')
		urllib.request.urlretrieve(a_url, a_path)
		printerr('file "activites.csv" created as "' + a_path + '"')