model.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. '''
  2. @author: olivier.massot, févr. 2018
  3. '''
  4. import logging
  5. logger = logging.getLogger("model")
  6. class Model():
  7. _mapping = {}
  8. @property
  9. def _fields(self):
  10. return list(self.__dict__.keys())
  11. @property
  12. def data(self):
  13. return self.__dict__
  14. def __repr__(self):
  15. return "<{} => {}>".format(self.__class__.__name__, ",".join(["{}={}".format(field, value) for field, value in self.__dict__.items()]))
  16. @classmethod
  17. def from_dict(cls, data):
  18. """ Retourne un objet à partir d'un dictionnaire de données """
  19. model = cls()
  20. for key, value in data.items():
  21. setattr(model, key, value)
  22. return model
  23. @classmethod
  24. def _map_type(cls, field, value):
  25. try:
  26. return cls._mapping[field](value)
  27. except KeyError:
  28. return value
  29. # Fonctions CSV
  30. def dump_to_csv(self, path):
  31. """ Ajoute les données du modèle au format CSV dans le fichier spécifié en paramètre.
  32. Créé le fichier s'il n'existe pas, avec une ligne d'en-tête """
  33. if not path.exists():
  34. logger.debug("Génère le fichier %s", path)
  35. firstline = "\t".join(self._fields + ["\n"])
  36. with open(path, 'w+') as f:
  37. f.write(firstline)
  38. with open(path, 'a') as f:
  39. f.write("\t".join([str(getattr(self, field)).replace("\t", " ") for field in self._fields] + ["\n"]))
  40. @classmethod
  41. def load_csv(cls, path):
  42. """ parcourt les lignes du fichier csv et renvoie chaque ligne sous forme d'un objet Model
  43. ATTENTION: chaque propriété dont le type n'est pas précisé dans _mapping aura le type 'string'
  44. """
  45. with open(path) as f:
  46. fields = next(f).split("\t")
  47. for line in f:
  48. data = {key: cls._map_type(key, value) for key, value in zip(fields, line.split("\t"))}
  49. yield(cls.from_dict(data))