Coverage for serializer.py: 30%

1 import json

2 import logging

3 from base64 import b64decode, b64encode

4

5 try:

6 import msgpack

7

8 ISMSGPACK = True

9 except ImportError:

10 ISMSGPACK = False

11 import pickle

12

13 from nastranio import cards as cards_mod

14

15

16 class PythonObjectEncoder(json.JSONEncoder):

17 """encode sets to json"""

18

19 def default(self, obj):

20 if isinstance(obj, (list, dict, str, int, float, bool, type(None))):

21 return super().default(obj)

22 if hasattr(obj, "to_json"):

23 # serialize cards

24 return {"_nastran_card": obj.to_json()}

25 return {"_python_object": b64encode(pickle.dumps(obj)).decode("utf-8")}

26

27

28 def as_python_object(dct):

29 if "_python_object" in dct:

30 return pickle.loads(b64decode(dct["_python_object"].encode("utf-8")))

31 if "_nastran_card" in dct:

32 # resurrect nastran card

33 _data = json.loads(dct["_nastran_card"])

34 cardname = _data["card"]

35 card = cards_mod.__dict__.get(cardname, cards_mod.DefaultCard)(name=cardname)

36 card.resume(_data)

37 return card

38 return dct

39

40

41 def msgpack_encode(obj):

42 if isinstance(obj, set):

43 obj = {"__set__": True, "as_list": list(obj)}

44 elif hasattr(obj, "to_msgpack"):

45 # serialize cards

46 obj = {"__msgpack__": True, "as_msg": obj.to_msgpack()}

47 return obj

48

49

50 def msgpack_decode(obj):

51 if "__msgpack__" in obj:

52 _data = msgpack.unpackb(obj["as_msg"], raw=False, object_hook=msgpack_decode)

53 cardname = _data["card"]

54 card = cards_mod.__dict__.get(cardname, cards_mod.DefaultCard)(name=cardname)

55 card.resume(_data)

56 return card

57 elif "__set__" in obj:

58 obj = set(obj["as_list"])

59 return obj