1 | import datetime |
---|
2 | import decimal |
---|
3 | import json as jsonlib |
---|
4 | from .._compat import PY2, integer_types |
---|
5 | |
---|
6 | long = integer_types[-1] |
---|
7 | |
---|
8 | |
---|
9 | class Serializers(object): |
---|
10 | _custom_ = {} |
---|
11 | |
---|
12 | def _json_parse(self, o): |
---|
13 | if hasattr(o, "custom_json") and callable(o.custom_json): |
---|
14 | return o.custom_json() |
---|
15 | if isinstance(o, (datetime.date, datetime.datetime, datetime.time)): |
---|
16 | return o.isoformat()[:19].replace("T", " ") |
---|
17 | elif isinstance(o, long): |
---|
18 | return int(o) |
---|
19 | elif isinstance(o, decimal.Decimal): |
---|
20 | return str(o) |
---|
21 | elif isinstance(o, set): |
---|
22 | return list(o) |
---|
23 | elif hasattr(o, "as_list") and callable(o.as_list): |
---|
24 | return o.as_list() |
---|
25 | elif hasattr(o, "as_dict") and callable(o.as_dict): |
---|
26 | return o.as_dict() |
---|
27 | if self._custom_.get("json") is not None: |
---|
28 | return self._custom_["json"](o) |
---|
29 | raise TypeError(repr(o) + " is not JSON serializable") |
---|
30 | |
---|
31 | def __getattr__(self, name): |
---|
32 | if self._custom_.get(name) is not None: |
---|
33 | return self._custom_[name] |
---|
34 | raise NotImplementedError("No " + str(name) + " serializer available.") |
---|
35 | |
---|
36 | def json(self, value): |
---|
37 | value = jsonlib.dumps(value, default=self._json_parse) |
---|
38 | rep28 = r"\u2028" |
---|
39 | rep29 = r"\2029" |
---|
40 | if PY2: |
---|
41 | rep28 = rep28.decode("raw_unicode_escape") |
---|
42 | rep29 = rep29.decode("raw_unicode_escape") |
---|
43 | return value.replace(rep28, "\\u2028").replace(rep29, "\\u2029") |
---|
44 | |
---|
45 | def yaml(self, value): |
---|
46 | if self._custom_.get("yaml") is not None: |
---|
47 | return self._custom_.get("yaml")(value) |
---|
48 | try: |
---|
49 | from yaml import dump |
---|
50 | except ImportError: |
---|
51 | raise NotImplementedError("No yaml serializer available.") |
---|
52 | return dump(value) |
---|
53 | |
---|
54 | |
---|
55 | serializers = Serializers() |
---|