|
|
@@ -3,27 +3,42 @@
|
|
|
|
|
|
@author: olivier.massot, févr. 2018
|
|
|
'''
|
|
|
+from datetime import datetime
|
|
|
import logging
|
|
|
|
|
|
-logger = logging.getLogger("model")
|
|
|
|
|
|
-class Model():
|
|
|
- """ Modèle de données d'un objet """
|
|
|
+logger = logging.getLogger("model")
|
|
|
|
|
|
- def __repr__(self):
|
|
|
- return "<{} => {}>".format(self.__class__.__name__, ",".join(["{}={}".format(field, getattr(self, field)) for field in self.__dict__]))
|
|
|
+def _sql_format(val):
|
|
|
+ """ pre-formatte une variable pour injection sql dans une base MS Access """
|
|
|
+ if val is None:
|
|
|
+ return "Null"
|
|
|
+ elif type(val) is int or type(val) is bool:
|
|
|
+ return "{}".format(val)
|
|
|
+ elif type(val) is str:
|
|
|
+ return "'{}'".format(val)
|
|
|
+ elif type(val) is datetime:
|
|
|
+ return "#{:%Y-%m-%d %H:%M:%S}#".format(val)
|
|
|
+ return "{}".format(val)
|
|
|
|
|
|
+class Model():
|
|
|
+ """ Modèle de données d'un objet
|
|
|
|
|
|
-class CsvModel(Model):
|
|
|
- """ Modèle de données d'un objet à stocker au format CSV """
|
|
|
- _FIELDS = []
|
|
|
+ """
|
|
|
+ _cnn = None
|
|
|
+ _tblname = ""
|
|
|
+ _fields = []
|
|
|
+ _identityfields = []
|
|
|
|
|
|
def __init__(self):
|
|
|
""" Génère un objet vide,
|
|
|
les propriétés de l'objet sont générées automatiquement à partir de la variable de classe _FIELDS"""
|
|
|
- for fld in self._FIELDS:
|
|
|
+ for fld in self._identityfields + self._fields:
|
|
|
setattr(self, fld, None)
|
|
|
|
|
|
+ def __repr__(self):
|
|
|
+ return "<{} => {}>".format(self.__class__.__name__, ",".join(["{}={}".format(field, getattr(self, field)) for field in self._identityfields + self._fields]))
|
|
|
+
|
|
|
@classmethod
|
|
|
def from_dict(cls, data):
|
|
|
""" Retourne un objet à partir d'un dictionnaire de données """
|
|
|
@@ -32,25 +47,61 @@ class CsvModel(Model):
|
|
|
setattr(facture, key, value)
|
|
|
return facture
|
|
|
|
|
|
+ ### Fonctions CSV ###
|
|
|
def to_csv(self):
|
|
|
""" Renvoie une chaine de caractère correspondant aux données de l'objet au format CSV
|
|
|
Séparateur = tabulation (car c'est un caractère interdit dans Access) """
|
|
|
- return "\t".join([str(getattr(self, field)).replace("\t", " ") for field in self._FIELDS] + ["\n"])
|
|
|
+ return "\t".join([str(getattr(self, field)).replace("\t", " ") for field in self._identityfields + self._fields] + ["\n"])
|
|
|
|
|
|
@classmethod
|
|
|
def from_csv(cls, line):
|
|
|
""" Retourne un objet Facture à partir d'une ligne de texte au format CSV
|
|
|
Séparateur = tabulation (car c'est un caractère interdit dans Access) """
|
|
|
- return cls.from_dict(dict(zip(cls._FIELDS, line.split("\t"))))
|
|
|
+ return cls.from_dict(dict(zip(cls._identityfields + cls._fields, line.split("\t"))))
|
|
|
|
|
|
def dump(self, path):
|
|
|
""" Ajoute les données du modèle au format CSV dans le fichier spécifié en paramètre.
|
|
|
Créé le fichier s'il n'existe pas, avec une ligne d'en-tête """
|
|
|
if not path.exists():
|
|
|
logger.debug("Génère le fichier %s", path)
|
|
|
- firstline = "\t".join(self._FIELDS + ["\n"])
|
|
|
+ firstline = "\t".join(self._identityfields + self._fields + ["\n"])
|
|
|
with open(path, 'w+') as f:
|
|
|
f.write(firstline)
|
|
|
|
|
|
with open(path, 'a') as f:
|
|
|
f.write(self.to_csv())
|
|
|
+
|
|
|
+ ### Fonctions Access ###
|
|
|
+ @classmethod
|
|
|
+ def select(cls, where=""):
|
|
|
+ sql = "SELECT * FROM {}".format(cls._tblname)
|
|
|
+ if where:
|
|
|
+ sql = "{} WHERE {}".format(sql, where)
|
|
|
+ logger.debug(sql)
|
|
|
+ for row in cls._cnn.read(sql):
|
|
|
+ yield cls.from_dict({f: getattr(row, f) for f in cls._identityfields + cls._fields})
|
|
|
+
|
|
|
+ @classmethod
|
|
|
+ def first(cls, where=""):
|
|
|
+ return next(cls.select(where))
|
|
|
+
|
|
|
+ def update(self):
|
|
|
+ sql = "UPDATE {} SET {} WHERE {}".format(self._tblname,
|
|
|
+ ",".join(["{} = {}".format(f, _sql_format(getattr(self, f))) for f in self._fields]),
|
|
|
+ " AND ".join(["{} = {}".format(k, _sql_format(getattr(self, k))) for k in self._identityfields]))
|
|
|
+ logger.debug(sql)
|
|
|
+ self._cnn.execute(sql)
|
|
|
+
|
|
|
+ def insert(self):
|
|
|
+ sql = "INSERT INTO {} ({}) VALUES ({})".format(self._tblname,
|
|
|
+ ",".join(self._fields),
|
|
|
+ ",".join([_sql_format(getattr(self, f)) for f in self._fields]))
|
|
|
+ logger.debug(sql)
|
|
|
+ print(sql)
|
|
|
+ self._cnn.execute(sql)
|
|
|
+
|
|
|
+ def delete(self):
|
|
|
+ sql = "DELETE * FROM {} WHERE {}".format(self._tblname,
|
|
|
+ " AND ".join(["{} = {}".format(k, _sql_format(getattr(self, k))) for k in self._identityfields]))
|
|
|
+ logger.debug(sql)
|
|
|
+ self._cnn.execute(sql)
|