File: json.py

package info (click to toggle)
python-mt-940 4.30.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,272 kB
  • sloc: python: 1,746; makefile: 201
file content (49 lines) | stat: -rw-r--r-- 1,396 bytes parent folder | download
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
from __future__ import absolute_import
import json
import decimal
import datetime


from . import models


class JSONEncoder(json.JSONEncoder):

    def default(self, value):
        # The following types should simply be cast to strings
        str_types = (
            datetime.date,
            datetime.datetime,
            datetime.timedelta,
            datetime.tzinfo,
            decimal.Decimal,
        )

        dict_types = (
            models.Balance,
            models.Amount,
        )

        # Handle native types that should be converted to strings
        if isinstance(value, str_types):
            return str(value)

        # Handling of the Transaction objects to include the actual
        # transactions
        elif isinstance(value, models.Transactions):
            data = value.data.copy()
            data['transactions'] = value.transactions
            return data

        # If an object has a `data` attribute, return that instead of the
        # `__dict__` ro prevent loops
        elif hasattr(value, 'data'):
            return value.data

        # Handle types that have a `__dict__` containing the data (doesn't work
        # for classes using `__slots__` such as `datetime`)
        elif isinstance(value, dict_types):
            return value.__dict__

        else:  # pragma: no cover
            return json.JSONEncoder.default(self, value)