mixins.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import yaml
  2. import uuid
  3. from planner import db, validator
  4. class SchemaMixin:
  5. @classmethod
  6. def class_name(cls):
  7. return cls.__qualname__.lower()
  8. @classmethod
  9. def schema(cls):
  10. return yaml.safe_load(cls.schema_yaml)
  11. @classmethod
  12. def validate(cls, data: dict):
  13. ok = validator.validate(data, cls.schema())
  14. return ok, validator.document if ok else validator.errors
  15. @classmethod
  16. def add_to_registry(cls, registry):
  17. registry.add(cls.class_name(), cls.schema())
  18. class DbMixin:
  19. cache = {}
  20. cache_keys = ()
  21. @classmethod
  22. def list(cls):
  23. return [cls.get(doc) for doc in db.table(cls.class_name()).all()]
  24. @classmethod
  25. def _get_cache_key(cls, document):
  26. return tuple([cls] + [document[k] for k in cls.cache_keys])
  27. def load_reverse(self):
  28. ...
  29. @classmethod
  30. def get(cls, document):
  31. key = cls._get_cache_key(document)
  32. if key in cls.cache:
  33. instance = cls.cache[key]
  34. else:
  35. instance = cls(document=document, **document)
  36. # The cache is updated a first time so that instances looking up
  37. # for this instance during the load_reverse can find it
  38. cls.cache[key] = instance
  39. instance.load_reverse()
  40. # The cache value is updated with its final value
  41. cls.cache[key] = instance
  42. return instance
  43. @classmethod
  44. def fetch(cls, doc_id=None):
  45. if doc_id:
  46. document = db.table(cls.class_name()).get(doc_id=doc_id)
  47. return cls.get(document)
  48. else:
  49. return None
  50. def save(self):
  51. self.document.update({'uuid': str(uuid.uuid4())})
  52. db.table(self.class_name()).insert(self.document)