-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathdecoder.py
416 lines (373 loc) · 13.9 KB
/
decoder.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
# (c) Copyright 2018 Palantir Technologies Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from .._lib import (
ConjureBeanType,
ConjureEnumType,
ConjureUnionType,
DecodableType,
BinaryType,
OptionalTypeWrapper,
DictType,
ListType,
OptionalType,
)
from typing import Optional, Type, Union, get_origin, get_args
from typing import Dict, Any, List
import inspect
import json
NoneType = type(None)
class ConjureDecoder(object):
"""Decodes json into a conjure object"""
@classmethod
def decode_conjure_bean_type(
cls, obj, conjure_type, return_none_for_unknown_union_types=False
):
"""Decodes json into a conjure bean type (a plain bean, not enum
or union).
Args:
obj: the json object to decode
conjure_type: a class object which is the bean type
we're decoding into
return_none_for_unknown_union_types: if set to True, returns None
instead of raising an exception when an unknown union type is
encountered
Returns:
A instance of a bean of type conjure_type.
"""
deserialized: Dict[str, Any] = {}
for (
python_arg_name,
field_definition,
) in conjure_type._fields().items():
field_identifier = field_definition.identifier
if field_identifier not in obj or obj[field_identifier] is None:
cls.check_null_field(
obj, deserialized, python_arg_name, field_definition
)
else:
value = obj[field_identifier]
field_type = field_definition.field_type
deserialized[python_arg_name] = cls.do_decode(
value, field_type, return_none_for_unknown_union_types
)
return conjure_type(**deserialized)
@classmethod
def check_null_field(
cls, obj, deserialized, python_arg_name, field_definition
):
type_origin = get_origin(field_definition.field_type)
if isinstance(field_definition.field_type, ListType):
deserialized[python_arg_name] = []
elif isinstance(field_definition.field_type, DictType):
deserialized[python_arg_name] = {}
elif isinstance(field_definition.field_type, OptionalType):
deserialized[python_arg_name] = None
elif type_origin is OptionalTypeWrapper:
deserialized[python_arg_name] = None
elif type_origin is list:
deserialized[python_arg_name] = []
elif type_origin is dict:
deserialized[python_arg_name] = {}
else:
raise Exception(
"field {} not found in object {}".format(
field_definition.identifier, obj
)
)
@classmethod
def decode_conjure_union_type(
cls, obj, conjure_type, return_none_for_unknown_union_types=False
):
"""Decodes json into a conjure union type.
Args:
obj: the json object to decode
conjure_type: a class object which is the union type
we're decoding into
return_none_for_unknown_union_types: if set to True, returns None
instead of raising an exception when an unknown union type is
encountered
Returns:
An instance of type conjure_type.
"""
type_of_union: str = obj["type"]
for attr, conjure_field in conjure_type._options().items():
if conjure_field.identifier == type_of_union:
attribute = attr
conjure_field_definition = conjure_field
break
else:
if return_none_for_unknown_union_types:
return None
else:
raise ValueError(
"unknown union type {0} for {1}".format(
type_of_union, conjure_type
)
)
deserialized: Dict[str, Any] = {}
if type_of_union not in obj or obj[type_of_union] is None:
cls.check_null_field(
obj, deserialized, attribute, conjure_field_definition
)
else:
value = obj[type_of_union]
field_type = conjure_field_definition.field_type
deserialized[attribute] = cls.do_decode(
value, field_type, return_none_for_unknown_union_types
)
# for backwards compatibility with conjure-python,
# only pass in arg type_of_union if it is expected
param_dict = inspect.signature(conjure_type.__init__).parameters
if "type_of_union" in param_dict:
deserialized["type_of_union"] = type_of_union
return conjure_type(**deserialized)
@classmethod
def decode_conjure_enum_type(cls, obj, conjure_type):
"""Decodes json into a conjure enum type.
Args:
obj: the json object to decode
conjure_type: a class object which is the enum type
we're decoding into.
Returns:
An instance of enum of type conjure_type.
"""
if not (isinstance(obj, str) or str(type(obj)) == "<type 'unicode'>"):
raise Exception(
"Expected to find str type but found {} instead".format(
type(obj)
)
)
if obj in conjure_type.__members__:
return conjure_type[obj]
else:
return conjure_type["UNKNOWN"]
@classmethod
def decode_dict(
cls,
obj: Dict[Any, Any],
key_type: Type[DecodableType],
item_type: Type[DecodableType],
return_none_for_unknown_union_types: bool = False,
) -> Dict[Any, Any]:
"""Decodes json into a dictionary, handling conversion of the
keys/values (the keys/values may themselves require conversion).
Args:
obj: the json object to decode
key_type: a class object which is the conjure type
of the keys in this dict
item_type: a class object which is the conjure type
of the values in this dict
return_none_for_unknown_union_types: if set to True, returns None
instead of raising an exception when an unknown union type is
encountered
Returns:
A python dictionary, where the keys are instances of type key_type
and the values are of type value_type.
"""
if not isinstance(obj, dict):
raise Exception("expected a python dict")
if (
key_type is str
or isinstance(key_type, BinaryType)
or key_type is BinaryType
or (
inspect.isclass(key_type)
and issubclass(key_type, ConjureEnumType)
)
):
return dict(
(
(
cls.do_decode(
x[0], key_type, return_none_for_unknown_union_types
),
cls.do_decode(
x[1],
item_type,
return_none_for_unknown_union_types,
),
)
for x in obj.items()
)
)
return dict(
(
(
cls.do_decode(
json.loads(x[0]),
key_type,
return_none_for_unknown_union_types,
),
cls.do_decode(
x[1], item_type, return_none_for_unknown_union_types
),
)
for x in obj.items()
)
)
@classmethod
def decode_list(
cls,
obj: List[Any],
element_type: Type[DecodableType],
return_none_for_unknown_union_types: bool = False,
) -> List[Any]:
"""Decodes json into a list, handling conversion of the elements.
Args:
obj: the json object to decode
element_type: a class object which is the conjure type of
the elements in this list.
return_none_for_unknown_union_types: if set to True, returns None
instead of raising an exception when an unknown union type is
encountered
Returns:
A python list where the elements are instances of type
element_type.
"""
if not isinstance(obj, list):
raise Exception("expected a python list")
return list(
map(
lambda x: cls.do_decode(
x, element_type, return_none_for_unknown_union_types
),
obj,
)
)
@classmethod
def decode_optional(
cls,
obj: Optional[Any],
object_type: Type[DecodableType],
return_none_for_unknown_union_types: bool = False,
) -> Optional[Any]:
"""Decodes json into an element, returning None if the provided object
is None.
Args:
obj: the json object to decode
object_type: a class object which is the conjure type of
the object if present.
return_none_for_unknown_union_types: if set to True, returns None
instead of raising an exception when an unknown union type is
encountered
Returns:
The decoded obj or None if no obj is provided.
"""
if obj is None:
return None
return cls.do_decode(
obj, object_type, return_none_for_unknown_union_types
)
@classmethod
def decode_primitive(cls, obj, object_type):
def raise_mismatch():
raise Exception(
"Expected to find {} type but found {} instead".format(
object_type, type(obj)
)
)
if object_type is float:
return float(obj)
elif (
object_type is str
or object_type is BinaryType
or isinstance(object_type, BinaryType)
):
# Python 2/3 compatible way of checking string
if not (
isinstance(obj, str) or str(type(obj)) == "<type 'unicode'>"
):
raise_mismatch()
elif not isinstance(obj, object_type):
raise_mismatch()
return obj
@classmethod
def do_decode(
cls,
obj: Any,
obj_type: Type[DecodableType],
return_none_for_unknown_union_types: bool = False,
) -> Any:
"""Decodes json into the specified type
Args:
obj: the json object to decode
obj_type: a class object which is the type we're decoding into.
return_none_for_unknown_union_types: if set to True, returns None
instead of raising an exception when an unknown union type is
encountered
"""
type_origin = get_origin(obj_type)
type_args = get_args(obj_type)
if inspect.isclass(obj_type) and issubclass(obj_type, ConjureBeanType):
return cls.decode_conjure_bean_type(
obj, obj_type, return_none_for_unknown_union_types
)
elif inspect.isclass(obj_type) and issubclass(
obj_type, ConjureUnionType
):
return cls.decode_conjure_union_type(
obj, obj_type, return_none_for_unknown_union_types
)
elif inspect.isclass(obj_type) and issubclass(
obj_type, ConjureEnumType
):
return cls.decode_conjure_enum_type(obj, obj_type)
elif isinstance(obj_type, DictType):
return cls.decode_dict(
obj,
obj_type.key_type,
obj_type.value_type,
return_none_for_unknown_union_types,
)
elif isinstance(obj_type, ListType):
return cls.decode_list(
obj, obj_type.item_type, return_none_for_unknown_union_types
)
elif isinstance(obj_type, OptionalType):
return cls.decode_optional(
obj, obj_type.item_type, return_none_for_unknown_union_types
)
elif type_origin is OptionalTypeWrapper:
return cls.decode_optional(
obj, type_args[0], return_none_for_unknown_union_types
)
elif type_origin is dict:
(key_type, value_type) = type_args
return cls.decode_dict(
obj, key_type, value_type, return_none_for_unknown_union_types
)
elif type_origin is list:
return cls.decode_list(
obj, type_args[0], return_none_for_unknown_union_types
)
return cls.decode_primitive(obj, obj_type)
def decode(
self,
obj: Any,
obj_type: Type[DecodableType],
return_none_for_unknown_union_types: bool = False,
) -> Any:
return self.do_decode(
obj, obj_type, return_none_for_unknown_union_types
)
def read_from_string(
self,
string_value: str,
obj_type: Type[DecodableType],
return_none_for_unknown_union_types: bool = False,
) -> Any:
deserialized = json.loads(string_value)
return self.decode(
deserialized, obj_type, return_none_for_unknown_union_types
)