Skip to content

Commit a7f1284

Browse files
committed
Refactor serialization functions by consolidating and removing deprecated methods for improved clarity and maintainability
1 parent 6569748 commit a7f1284

File tree

3 files changed

+13
-126
lines changed

3 files changed

+13
-126
lines changed

src/iop/_dispatch.py

Lines changed: 1 addition & 115 deletions
Original file line numberDiff line numberDiff line change
@@ -6,34 +6,12 @@
66
from typing import Any, Dict, List, Type
77

88
import iris
9-
from dacite import Config, from_dict
109
from pydantic import BaseModel
1110

1211
from iop._utils import _Utils
13-
from iop._serialization import IrisJSONEncoder, IrisJSONDecoder
12+
from iop._serialization import IrisJSONEncoder, IrisJSONDecoder, serialize_message, serialize_pickle_message, deserialize_message, deserialize_pickle_message
1413
from iop._message_validator import is_message_instance, is_pickle_message_instance, is_iris_object_instance
1514

16-
def serialize_pickle_message(message: Any) -> iris.cls:
17-
"""Converts a python dataclass message into an iris iop.message.
18-
19-
Args:
20-
message: The message to serialize, an instance of a class that is a subclass of Message.
21-
22-
Returns:
23-
The message in json format.
24-
"""
25-
pickle_string = codecs.encode(pickle.dumps(message), "base64").decode()
26-
module = message.__class__.__module__
27-
classname = message.__class__.__name__
28-
29-
msg = iris.cls('IOP.PickleMessage')._New()
30-
msg.classname = module + "." + classname
31-
32-
stream = _Utils.string_to_stream(pickle_string)
33-
msg.jstr = stream
34-
35-
return msg
36-
3715
def dispatch_serializer(message: Any) -> Any:
3816
"""Serializes the message based on its type.
3917
@@ -59,42 +37,6 @@ def dispatch_serializer(message: Any) -> Any:
5937

6038
raise TypeError("The message must be an instance of a class that is a subclass of Message or IRISObject %Persistent class.")
6139

62-
def serialize_message(message: Any) -> iris.cls:
63-
"""Converts a python dataclass message into an iris iop.message.
64-
65-
Args:
66-
message: The message to serialize, an instance of a class that is a subclass of Message.
67-
68-
Returns:
69-
The message in json format.
70-
"""
71-
json_string = json.dumps(message, cls=IrisJSONEncoder, ensure_ascii=False)
72-
module = message.__class__.__module__
73-
classname = message.__class__.__name__
74-
75-
msg = iris.cls('IOP.Message')._New()
76-
msg.classname = module + "." + classname
77-
78-
if hasattr(msg, 'buffer') and len(json_string) > msg.buffer:
79-
msg.json = _Utils.string_to_stream(json_string, msg.buffer)
80-
else:
81-
msg.json = json_string
82-
83-
return msg
84-
85-
def deserialize_pickle_message(serial: iris.cls) -> Any:
86-
"""Converts an iris iop.message into a python dataclass message.
87-
88-
Args:
89-
serial: The serialized message
90-
91-
Returns:
92-
The deserialized message
93-
"""
94-
string = _Utils.stream_to_string(serial.jstr)
95-
msg = pickle.loads(codecs.decode(string.encode(), "base64"))
96-
return msg
97-
9840
def dispatch_deserializer(serial: Any) -> Any:
9941
"""Deserializes the message based on its type.
10042
@@ -125,62 +67,6 @@ def dispatch_deserializer(serial: Any) -> Any:
12567
else:
12668
return serial
12769

128-
def deserialize_message(serial: iris.cls) -> Any:
129-
"""Converts an iris iop.message into a python dataclass message.
130-
131-
Args:
132-
serial: The serialized message
133-
134-
Returns:
135-
The deserialized message
136-
"""
137-
if (serial.classname is None):
138-
raise ValueError("JSON message malformed, must include classname")
139-
classname = serial.classname
140-
141-
j = classname.rindex(".")
142-
if (j <= 0):
143-
raise ValueError("Classname must include a module: " + classname)
144-
try:
145-
module = importlib.import_module(classname[:j])
146-
msg = getattr(module, classname[j+1:])
147-
except Exception:
148-
raise ImportError("Class not found: " + classname)
149-
150-
string = ""
151-
if (serial.type == 'Stream'):
152-
string = _Utils.stream_to_string(serial.json)
153-
else:
154-
string = serial.json
155-
156-
jdict = json.loads(string, cls=IrisJSONDecoder)
157-
return dataclass_from_dict(msg, jdict)
158-
159-
def dataclass_from_dict(klass: Type, dikt: Dict) -> Any:
160-
"""Converts a dictionary to a dataclass instance.
161-
162-
Args:
163-
klass: The dataclass to convert to
164-
dikt: The dictionary to convert to a dataclass
165-
166-
Returns:
167-
A dataclass object with the fields of the dataclass and the fields of the dictionary.
168-
"""
169-
if issubclass(klass, BaseModel):
170-
return klass.model_validate(dikt)
171-
else:
172-
ret = from_dict(klass, dikt, Config(check_types=False))
173-
174-
try:
175-
fieldtypes = klass.__annotations__
176-
except Exception as e:
177-
fieldtypes = []
178-
179-
for key, val in dikt.items():
180-
if key not in fieldtypes:
181-
setattr(ret, key, val)
182-
return ret
183-
18470
def dispach_message(host, request: Any) -> Any:
18571
"""Dispatches the message to the appropriate method.
18672

src/iop/_serialization.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,7 @@
77
import json
88
import pickle
99
import uuid
10-
from abc import ABC, abstractmethod
11-
from dataclasses import is_dataclass
12-
from typing import Any, Dict, Type, Optional
10+
from typing import Any, Dict, Type
1311

1412
from dacite import Config, from_dict
1513
import iris

src/tests/test_dispatch.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,20 @@
33
import decimal
44
import uuid
55
from dataclasses import dataclass
6-
import iris
76

87
from iop._dispatch import (
9-
serialize_message,
10-
deserialize_message,
11-
serialize_pickle_message,
12-
deserialize_pickle_message,
138
dispatch_serializer,
14-
dispatch_deserializer,
15-
dataclass_from_dict
16-
)
9+
dispatch_deserializer
10+
)
11+
12+
from iop._serialization import (
13+
dataclass_from_dict,
14+
serialize_message,
15+
deserialize_message,
16+
serialize_pickle_message,
17+
deserialize_pickle_message
18+
)
19+
1720
from iop._message import _Message as Message
1821
from iop._message import _PydanticMessage as PydanticMessage
1922

0 commit comments

Comments
 (0)