From 4ff7e4aab0af9b06dd6814a1c4df690e1ed7e063 Mon Sep 17 00:00:00 2001 From: Marc Bonnici Date: Fri, 16 Nov 2018 17:17:38 +0000 Subject: [PATCH] utils/serializer: Add Podable Mix-in class Add a new mix-in class for classes that are serialized to PODs, the aim of this class is to provide a way to ensure that both the original data version and the current serialization version are known. When attempting to de-serialize a POD the serialization version will be compared to the latest version in WA if not matching will call the appropriate method to upgrade the pod to a known structure state populating any missing fields with a sensible default or converting the existing data to the new format. --- wa/utils/serializer.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/wa/utils/serializer.py b/wa/utils/serializer.py index e3b3b548..0ca7fe64 100644 --- a/wa/utils/serializer.py +++ b/wa/utils/serializer.py @@ -361,3 +361,33 @@ def is_pod(obj): if not is_pod(v): return False return True + + +class Podable(object): + + _pod_serialization_version = 0 + + @classmethod + def from_pod(cls, pod): + pod = cls._upgrade_pod(pod) + instance = cls() + instance._pod_version = pod.pop('_pod_version') # pylint: disable=protected-access + return instance + + @classmethod + def _upgrade_pod(cls, pod): + _pod_serialization_version = pod.pop('_pod_serialization_version', None) or 0 + while _pod_serialization_version < cls._pod_serialization_version: + _pod_serialization_version += 1 + upgrade = getattr(cls, '_pod_upgrade_v{}'.format(_pod_serialization_version)) + pod = upgrade(pod) + return pod + + def __init__(self): + self._pod_version = self._pod_serialization_version + + def to_pod(self): + pod = {} + pod['_pod_version'] = self._pod_version + pod['_pod_serialization_version'] = self._pod_serialization_version + return pod