| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- import yaml
- import uuid
- from planner import db, validator
- class SchemaMixin:
- @classmethod
- def class_name(cls):
- return cls.__qualname__.lower()
- @classmethod
- def schema(cls):
- return yaml.safe_load(cls.schema_yaml)
- @classmethod
- def validate(cls, data: dict):
- ok = validator.validate(data, cls.schema())
- return ok, validator.document if ok else validator.errors
- @classmethod
- def add_to_registry(cls, registry):
- registry.add(cls.class_name(), cls.schema())
- class DbMixin:
- cache = {}
- cache_keys = ()
- @classmethod
- def list(cls):
- return [cls.get(doc) for doc in db.table(cls.class_name()).all()]
- @classmethod
- def _get_cache_key(cls, document):
- return tuple([cls] + [document[k] for k in cls.cache_keys])
- def load_reverse(self):
- ...
- @classmethod
- def get(cls, document):
- key = cls._get_cache_key(document)
- if key in cls.cache:
- instance = cls.cache[key]
- else:
- instance = cls(document=document, **document)
- # The cache is updated a first time so that instances looking up
- # for this instance during the load_reverse can find it
- cls.cache[key] = instance
- instance.load_reverse()
- # The cache value is updated with its final value
- cls.cache[key] = instance
- return instance
- @classmethod
- def fetch(cls, doc_id=None):
- if doc_id:
- document = db.table(cls.class_name()).get(doc_id=doc_id)
- return cls.get(document)
- else:
- return None
- def save(self):
- self.document.update({'uuid': str(uuid.uuid4())})
- db.table(self.class_name()).insert(self.document)
|