|
1
|
|
|
from typing import Optional, Callable |
|
2
|
|
|
from jsons._common_impl import get_class_name |
|
3
|
|
|
from jsons._dump_impl import dump |
|
4
|
|
|
from jsons.exceptions import RecursionDetectedError, SerializationError |
|
5
|
|
|
|
|
6
|
|
|
|
|
7
|
|
|
def default_dict_serializer( |
|
8
|
|
|
obj: dict, |
|
9
|
|
|
cls: Optional[type] = None, |
|
10
|
|
|
*, |
|
11
|
|
|
strict: bool = False, |
|
12
|
|
|
strip_nulls: bool = False, |
|
13
|
|
|
key_transformer: Optional[Callable[[str], str]] = None, |
|
14
|
|
|
**kwargs) -> dict: |
|
15
|
|
|
""" |
|
16
|
|
|
Serialize the given ``obj`` to a dict of serialized objects. |
|
17
|
|
|
:param obj: the dict that is to be serialized. |
|
18
|
|
|
:param cls: the type of ``obj``; ``obj`` is dumped as if of that type. |
|
19
|
|
|
:param strict: if ``True`` the serialization will raise upon any the |
|
20
|
|
|
failure of any attribute. Otherwise it continues with a warning. |
|
21
|
|
|
:param strip_nulls: if ``True`` the resulting dict will not contain null |
|
22
|
|
|
values. |
|
23
|
|
|
:param key_transformer: a function that will be applied to all keys in the |
|
24
|
|
|
resulting dict. |
|
25
|
|
|
:param kwargs: any keyword arguments that may be given to the serialization |
|
26
|
|
|
process. |
|
27
|
|
|
:return: a dict of which all elements are serialized. |
|
28
|
|
|
""" |
|
29
|
|
|
result = dict() |
|
30
|
|
|
fork_inst = kwargs['fork_inst'] |
|
31
|
|
|
for key in obj: |
|
32
|
|
|
dumped_elem = None |
|
33
|
|
|
try: |
|
34
|
|
|
dumped_elem = dump(obj[key], key_transformer=key_transformer, |
|
35
|
|
|
strip_nulls=strip_nulls, **kwargs) |
|
36
|
|
|
except RecursionDetectedError: |
|
37
|
|
|
fork_inst._warn('Recursive structure detected in attribute "{}" ' |
|
38
|
|
|
'of object of type "{}", ignoring the attribute.' |
|
39
|
|
|
.format(key, get_class_name(cls))) |
|
40
|
|
|
except SerializationError as err: |
|
41
|
|
|
if strict: |
|
42
|
|
|
raise |
|
43
|
|
|
else: |
|
44
|
|
|
fork_inst._warn('Failed to dump attribute "{}" of object of type ' |
|
45
|
|
|
'"{}". Reason: {}. Ignoring the attribute.' |
|
46
|
|
|
.format(key, get_class_name(cls), err.message)) |
|
47
|
|
|
break |
|
48
|
|
|
if not (strip_nulls and dumped_elem is None): |
|
49
|
|
|
if key_transformer: |
|
50
|
|
|
key = key_transformer(key) |
|
51
|
|
|
result[key] = dumped_elem |
|
52
|
|
|
return result |
|
53
|
|
|
|