2021-11-02 15:21:34 +01:00
import sqlite3
2021-11-10 23:22:46 +01:00
import sys
2021-11-02 15:21:34 +01:00
import json
from . model import Commune , FantoirVoie
# DB with addresses info
DB_ADDRESSES_PATH_ENV = " DB_ADDRESSES_PATH "
DB_ADDRESSES_DEFAULT_PATH = " /etc/fantoir.sqlite "
# Table for insee codes
DB_TABLE_INSEE_NAME = " insee "
DB_COL_COMMUNE_INSEE = " Code_commune_INSEE "
DB_COL_COMMUNE_NAME = " Nom_commune "
DB_COL_COMMUNE_POSTE = " Code_postal "
# Table for Fantoir voies (code Rivoli)
DB_TABLE_FANTOIR_NAME = " keyv "
DB_COL_FANTOIR_INSEE = " key "
DB_FANTOIR_INSEE_KEY_SUFFIX = " keyv: "
# Utility to find an address
class AddressFinder :
def __init__ ( self , db_addresses_sqlite_path : str ) :
self . dbPath = db_addresses_sqlite_path
print ( " DB addresses Path : " + self . dbPath )
2021-11-10 23:22:46 +01:00
def getCommunesFromNameOrZip ( self , communeNameOrZip : str ) - > list [ Commune ] :
2021-11-02 15:21:34 +01:00
con = sqlite3 . connect ( self . dbPath )
con . row_factory = sqlite3 . Row
cur = con . cursor ( )
communes : list [ Commune ] = [ ]
2021-11-10 23:22:46 +01:00
try :
if communeNameOrZip is None :
cur . execute ( f " SELECT * from \" { DB_TABLE_INSEE_NAME } \" " )
else :
cur . execute ( f " SELECT * from \" { DB_TABLE_INSEE_NAME } \" WHERE { DB_COL_COMMUNE_NAME } = \" { communeNameOrZip } \" COLLATE nocase OR { DB_COL_COMMUNE_POSTE } = \" { communeNameOrZip } \" " )
except sqlite3 . OperationalError as err :
print ( " Error querying DB : {0} " . format ( err ) , file = sys . stderr )
return [ ]
2021-11-02 15:21:34 +01:00
rows = [ dict ( row ) for row in cur . fetchall ( ) ]
con . close ( )
for row in rows :
commune = Commune (
codeInsee = row [ DB_COL_COMMUNE_INSEE ] ,
nom = row [ DB_COL_COMMUNE_NAME ] ,
codeZip = row [ DB_COL_COMMUNE_POSTE ] )
communes . append ( commune )
return communes
2021-11-10 23:22:46 +01:00
def getCommuneFantoirVoies ( self , communeInseeCode : str ) - > list [ FantoirVoie ] :
2021-11-02 15:21:34 +01:00
# Extract data from DB
con = sqlite3 . connect ( self . dbPath )
con . row_factory = sqlite3 . Row
cur = con . cursor ( )
2021-11-10 23:22:46 +01:00
try :
cur . execute ( f " SELECT value from \" { DB_TABLE_FANTOIR_NAME } \" WHERE { DB_COL_FANTOIR_INSEE } = \" { DB_FANTOIR_INSEE_KEY_SUFFIX } { communeInseeCode } \" " )
except sqlite3 . OperationalError as err :
print ( " Error querying DB : {0} " . format ( err ) , file = sys . stderr )
return [ ]
2021-11-02 15:21:34 +01:00
data_raw = cur . fetchone ( )
con . close ( )
## Get JSON payload
fantoir_dict = [ ]
# Check if data where found
if data_raw is not None :
data = dict ( data_raw )
# Extract the data behind "value" which is a JSON structure
data_dict = json . loads ( data . get ( " value " ) )
# In extracted JSON data, the interesting payload is behind "value" key
fantoir_dict = data_dict . get ( " value " )
else :
print ( " Did not found any data matching Insee code " + str ( communeInseeCode ) )
# Return the json dump
return fantoir_dict