changeset 2697:fcc945537d5f

tools (common/data_format): serialise now check types and return a default value when empty string is parsed.
author Goffi <goffi@goffi.org>
date Sat, 01 Dec 2018 09:59:48 +0100
parents 5849dcaab99d
children 5060cbeec01e
files sat/tools/common/data_format.py
diffstat 1 files changed, 11 insertions(+), 2 deletions(-) [+]
line wrap: on
line diff
--- a/sat/tools/common/data_format.py	Sat Dec 01 09:57:25 2018 +0100
+++ b/sat/tools/common/data_format.py	Sat Dec 01 09:59:48 2018 +0100
@@ -133,10 +133,19 @@
     """
     return json.dumps(data, ensure_ascii=False)
 
-def deserialise(serialised_data):
+def deserialise(serialised_data, default=None, type_check=dict):
     """Deserialize data from bridge
 
     @param serialised_data(unicode): data to deserialise
+    @default (object): value to use when serialised data is empty string
+    @param type_check(type): if not None, the deserialised data must be of this type
     @return(object): deserialised data
+    @raise ValueError: serialised_data is of wrong type
     """
-    return json.loads(serialised_data)
+    if serialised_data == u"":
+        return default
+    ret = json.loads(serialised_data)
+    if type_check is not None and not isinstance(ret, type_check):
+        raise ValueError(u"Bad data type, was expecting {type_check}, got {real_type}"
+            .format(type_check=type_check, real_type=type(ret)))
+    return ret