mirror of
https://github.com/avatao-content/baseimage-tutorial-framework
synced 2024-11-22 13:01:32 +00:00
Rework serialization module to work regardless of message format
This commit is contained in:
parent
87fa86d314
commit
6113149c58
@ -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)
|
||||
|
Loading…
Reference in New Issue
Block a user