1 """ |
1 """ |
2 Serialize data to/from JSON |
2 Serialize data to/from JSON |
3 """ |
3 """ |
4 |
4 |
5 import datetime |
5 import datetime |
6 from django.utils import simplejson |
6 from StringIO import StringIO |
|
7 |
7 from django.core.serializers.python import Serializer as PythonSerializer |
8 from django.core.serializers.python import Serializer as PythonSerializer |
8 from django.core.serializers.python import Deserializer as PythonDeserializer |
9 from django.core.serializers.python import Deserializer as PythonDeserializer |
9 try: |
10 from django.utils import datetime_safe |
10 from cStringIO import StringIO |
11 from django.utils import simplejson |
11 except ImportError: |
12 |
12 from StringIO import StringIO |
|
13 try: |
13 try: |
14 import decimal |
14 import decimal |
15 except ImportError: |
15 except ImportError: |
16 from django.utils import _decimal as decimal # Python 2.3 fallback |
16 from django.utils import _decimal as decimal # Python 2.3 fallback |
17 |
17 |
18 class Serializer(PythonSerializer): |
18 class Serializer(PythonSerializer): |
19 """ |
19 """ |
20 Convert a queryset to JSON. |
20 Convert a queryset to JSON. |
21 """ |
21 """ |
22 internal_use_only = False |
22 internal_use_only = False |
23 |
23 |
24 def end_serialization(self): |
24 def end_serialization(self): |
25 self.options.pop('stream', None) |
25 self.options.pop('stream', None) |
26 self.options.pop('fields', None) |
26 self.options.pop('fields', None) |
27 simplejson.dump(self.objects, self.stream, cls=DjangoJSONEncoder, **self.options) |
27 simplejson.dump(self.objects, self.stream, cls=DjangoJSONEncoder, **self.options) |
28 |
28 |
49 DATE_FORMAT = "%Y-%m-%d" |
49 DATE_FORMAT = "%Y-%m-%d" |
50 TIME_FORMAT = "%H:%M:%S" |
50 TIME_FORMAT = "%H:%M:%S" |
51 |
51 |
52 def default(self, o): |
52 def default(self, o): |
53 if isinstance(o, datetime.datetime): |
53 if isinstance(o, datetime.datetime): |
54 return o.strftime("%s %s" % (self.DATE_FORMAT, self.TIME_FORMAT)) |
54 d = datetime_safe.new_datetime(o) |
|
55 return d.strftime("%s %s" % (self.DATE_FORMAT, self.TIME_FORMAT)) |
55 elif isinstance(o, datetime.date): |
56 elif isinstance(o, datetime.date): |
56 return o.strftime(self.DATE_FORMAT) |
57 d = datetime_safe.new_date(o) |
|
58 return d.strftime(self.DATE_FORMAT) |
57 elif isinstance(o, datetime.time): |
59 elif isinstance(o, datetime.time): |
58 return o.strftime(self.TIME_FORMAT) |
60 return o.strftime(self.TIME_FORMAT) |
59 elif isinstance(o, decimal.Decimal): |
61 elif isinstance(o, decimal.Decimal): |
60 return str(o) |
62 return str(o) |
61 else: |
63 else: |