mise-en-production
[auf_framonde.git] / project / cmsplugin_contact_plus / jsonfield / encoder.py
1 from django.db.models.query import QuerySet
2 from django.utils import six, timezone
3 from django.utils.encoding import force_text
4 from django.utils.functional import Promise
5 import datetime
6 import decimal
7 import types
8 import json
9 import uuid
10
11
12 class JSONEncoder(json.JSONEncoder):
13 """
14 JSONEncoder subclass that knows how to encode date/time/timedelta,
15 decimal types, generators and other basic python objects.
16
17 Taken from https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/utils/encoders.py
18 """
19 def default(self, obj):
20 # For Date Time string spec, see ECMA 262
21 # http://ecma-international.org/ecma-262/5.1/#sec-15.9.1.15
22 if isinstance(obj, Promise):
23 return force_text(obj)
24 elif isinstance(obj, datetime.datetime):
25 representation = obj.isoformat()
26 if obj.microsecond:
27 representation = representation[:23] + representation[26:]
28 if representation.endswith('+00:00'):
29 representation = representation[:-6] + 'Z'
30 return representation
31 elif isinstance(obj, datetime.date):
32 return obj.isoformat()
33 elif isinstance(obj, datetime.time):
34 if timezone and timezone.is_aware(obj):
35 raise ValueError("JSON can't represent timezone-aware times.")
36 representation = obj.isoformat()
37 if obj.microsecond:
38 representation = representation[:12]
39 return representation
40 elif isinstance(obj, datetime.timedelta):
41 return six.text_type(total_seconds(obj))
42 elif isinstance(obj, decimal.Decimal):
43 # Serializers will coerce decimals to strings by default.
44 return float(obj)
45 elif isinstance(obj, uuid.UUID):
46 return six.text_type(obj)
47 elif isinstance(obj, QuerySet):
48 return tuple(obj)
49 elif hasattr(obj, 'tolist'):
50 # Numpy arrays and array scalars.
51 return obj.tolist()
52 elif hasattr(obj, '__getitem__'):
53 try:
54 return dict(obj)
55 except:
56 pass
57 elif hasattr(obj, '__iter__'):
58 return tuple(item for item in obj)
59 return super(JSONEncoder, self).default(obj)