Rework serialization module to work regardless of message format

This commit is contained in:
Kristóf Tóth 2018-04-10 13:42:51 +02:00
parent 87fa86d314
commit 6113149c58

View File

@ -4,6 +4,27 @@
import json
def serialize_all(*args):
return tuple(_serialize_single(arg) for arg in args)
def deserialize_all(*args):
return tuple(_deserialize_single(arg) for arg in args)
def _serialize_single(data):
if not isinstance(data, str):
data = json.dumps(data)
return encode_if_needed(data)
def _deserialize_single(data):
try:
return json.loads(data)
except ValueError:
return decode_if_needed(data)
def encode_if_needed(value):
if isinstance(value, str):
value = value.encode('utf-8')
@ -14,11 +35,3 @@ def decode_if_needed(value):
if isinstance(value, (bytes, bytearray)):
value = value.decode('utf-8')
return value
def serialize_all(key, data):
return [encode_if_needed(frame) for frame in (key, json.dumps(data))]
def deserialize_all(key, data):
return decode_if_needed(key), json.loads(data)