1
|
|
|
from datetime import datetime |
|
|
|
|
2
|
|
|
from enum import EnumMeta |
3
|
|
|
from typing import Callable |
4
|
|
|
from jsons import dump_impl |
5
|
|
|
from jsons._common_impl import RFC3339_DATETIME_PATTERN, snakecase, camelcase, \ |
6
|
|
|
pascalcase, lispcase |
7
|
|
|
|
8
|
|
|
|
9
|
|
|
def default_list_serializer(obj: list, **kwargs) -> dict: |
|
|
|
|
10
|
|
|
return [dump_impl(elem, **kwargs) for elem in obj] |
11
|
|
|
|
12
|
|
|
|
13
|
|
|
def default_enum_serializer(obj: EnumMeta, **_) -> dict: |
|
|
|
|
14
|
|
|
return obj.name |
15
|
|
|
|
16
|
|
|
|
17
|
|
|
def default_datetime_serializer(obj: datetime, **_) -> dict: |
|
|
|
|
18
|
|
|
timezone = obj.tzinfo |
19
|
|
|
offset = 'Z' |
20
|
|
|
pattern = RFC3339_DATETIME_PATTERN |
21
|
|
|
if timezone: |
22
|
|
|
if timezone.tzname(None) != 'UTC': |
23
|
|
|
offset = timezone.tzname(None).split('UTC')[1] |
24
|
|
|
if obj.microsecond: |
25
|
|
|
pattern += '.%f' |
26
|
|
|
return obj.strftime("{}{}".format(pattern, offset)) |
27
|
|
|
|
28
|
|
|
|
29
|
|
|
def default_primitive_serializer(obj, **_) -> dict: |
|
|
|
|
30
|
|
|
return obj |
31
|
|
|
|
32
|
|
|
|
33
|
|
|
def default_object_serializer(obj: object, |
|
|
|
|
34
|
|
|
key_transformer: Callable[[str], str] = None, |
35
|
|
|
**kwargs) -> dict: |
36
|
|
|
d = obj.__dict__ |
|
|
|
|
37
|
|
|
key_transformer_ = key_transformer or (lambda key: key) |
38
|
|
|
return {key_transformer_(key): dump_impl(d[key], |
39
|
|
|
key_transformer=key_transformer, |
40
|
|
|
**kwargs) for key in d} |
41
|
|
|
|
42
|
|
|
|
43
|
|
|
# The following default key transformers can be used with the |
44
|
|
|
# default_object_serializer. |
45
|
|
|
KEY_TRANSFORMER_SNAKECASE = snakecase |
46
|
|
|
KEY_TRANSFORMER_CAMELCASE = camelcase |
47
|
|
|
KEY_TRANSFORMER_PASCALCASE = pascalcase |
48
|
|
|
KEY_TRANSFORMER_LISPCASE = lispcase |
49
|
|
|
|
The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:
If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.