2006-06-30 00:42:49 +08:00
|
|
|
"""
|
|
|
|
Serialize data to/from JSON
|
|
|
|
"""
|
|
|
|
|
2012-04-30 01:58:00 +08:00
|
|
|
# Avoid shadowing the standard library json module
|
|
|
|
from __future__ import absolute_import
|
|
|
|
|
2006-06-30 00:42:49 +08:00
|
|
|
import datetime
|
2010-05-04 22:00:30 +08:00
|
|
|
import decimal
|
2012-04-30 01:58:00 +08:00
|
|
|
import json
|
2012-05-06 01:47:03 +08:00
|
|
|
from io import BytesIO
|
2008-07-30 18:40:37 +08:00
|
|
|
|
2012-02-10 02:56:58 +08:00
|
|
|
from django.core.serializers.base import DeserializationError
|
2006-06-30 00:42:49 +08:00
|
|
|
from django.core.serializers.python import Serializer as PythonSerializer
|
|
|
|
from django.core.serializers.python import Deserializer as PythonDeserializer
|
2012-06-08 00:08:47 +08:00
|
|
|
from django.utils.encoding import smart_str
|
2011-11-18 21:01:06 +08:00
|
|
|
from django.utils.timezone import is_aware
|
2008-07-30 18:40:37 +08:00
|
|
|
|
2006-06-30 00:42:49 +08:00
|
|
|
class Serializer(PythonSerializer):
|
|
|
|
"""
|
|
|
|
Convert a queryset to JSON.
|
|
|
|
"""
|
2007-12-17 14:53:15 +08:00
|
|
|
internal_use_only = False
|
2008-07-18 11:47:27 +08:00
|
|
|
|
2012-05-26 17:43:37 +08:00
|
|
|
def start_serialization(self):
|
2012-04-30 01:58:00 +08:00
|
|
|
if json.__version__.split('.') >= ['2', '1', '3']:
|
2011-12-18 07:00:41 +08:00
|
|
|
# Use JS strings to represent Python Decimal instances (ticket #16850)
|
|
|
|
self.options.update({'use_decimal': False})
|
2012-05-26 17:43:37 +08:00
|
|
|
self._current = None
|
|
|
|
self.json_kwargs = self.options.copy()
|
|
|
|
self.json_kwargs.pop('stream', None)
|
|
|
|
self.json_kwargs.pop('fields', None)
|
|
|
|
self.stream.write("[")
|
|
|
|
|
|
|
|
def end_serialization(self):
|
|
|
|
if self.options.get("indent"):
|
|
|
|
self.stream.write("\n")
|
|
|
|
self.stream.write("]")
|
|
|
|
if self.options.get("indent"):
|
|
|
|
self.stream.write("\n")
|
|
|
|
|
|
|
|
def end_object(self, obj):
|
|
|
|
# self._current has the field data
|
|
|
|
indent = self.options.get("indent")
|
|
|
|
if not self.first:
|
|
|
|
self.stream.write(",")
|
|
|
|
if not indent:
|
|
|
|
self.stream.write(" ")
|
|
|
|
if indent:
|
|
|
|
self.stream.write("\n")
|
|
|
|
json.dump(self.get_dump_object(obj), self.stream,
|
|
|
|
cls=DjangoJSONEncoder, **self.json_kwargs)
|
|
|
|
self._current = None
|
2007-04-25 18:12:05 +08:00
|
|
|
|
2006-06-30 00:42:49 +08:00
|
|
|
def getvalue(self):
|
2012-05-26 17:43:37 +08:00
|
|
|
# overwrite PythonSerializer.getvalue() with base Serializer.getvalue()
|
2007-04-25 18:12:05 +08:00
|
|
|
if callable(getattr(self.stream, 'getvalue', None)):
|
|
|
|
return self.stream.getvalue()
|
2006-06-30 00:42:49 +08:00
|
|
|
|
2012-02-10 02:56:58 +08:00
|
|
|
|
2006-06-30 00:42:49 +08:00
|
|
|
def Deserializer(stream_or_string, **options):
|
|
|
|
"""
|
|
|
|
Deserialize a stream or string of JSON data.
|
|
|
|
"""
|
2012-06-08 00:08:47 +08:00
|
|
|
if isinstance(stream_or_string, bytes):
|
2012-05-06 01:47:03 +08:00
|
|
|
stream = BytesIO(stream_or_string)
|
2012-06-08 00:08:47 +08:00
|
|
|
elif isinstance(stream_or_string, unicode):
|
|
|
|
stream = BytesIO(smart_str(stream_or_string))
|
2006-06-30 00:42:49 +08:00
|
|
|
else:
|
|
|
|
stream = stream_or_string
|
2012-02-10 02:56:58 +08:00
|
|
|
try:
|
2012-04-30 01:58:00 +08:00
|
|
|
for obj in PythonDeserializer(json.load(stream), **options):
|
2012-02-10 02:56:58 +08:00
|
|
|
yield obj
|
2012-02-10 09:13:38 +08:00
|
|
|
except GeneratorExit:
|
|
|
|
raise
|
2012-04-29 00:09:37 +08:00
|
|
|
except Exception as e:
|
2012-02-10 02:56:58 +08:00
|
|
|
# Map to deserializer error
|
|
|
|
raise DeserializationError(e)
|
|
|
|
|
2007-04-25 18:12:05 +08:00
|
|
|
|
2012-04-30 01:58:00 +08:00
|
|
|
class DjangoJSONEncoder(json.JSONEncoder):
|
2006-06-30 00:42:49 +08:00
|
|
|
"""
|
2007-05-21 09:29:58 +08:00
|
|
|
JSONEncoder subclass that knows how to encode date/time and decimal types.
|
2006-06-30 00:42:49 +08:00
|
|
|
"""
|
|
|
|
def default(self, o):
|
2011-11-18 21:01:06 +08:00
|
|
|
# See "Date Time String Format" in the ECMA-262 specification.
|
2006-07-31 22:59:53 +08:00
|
|
|
if isinstance(o, datetime.datetime):
|
2011-11-18 21:01:06 +08:00
|
|
|
r = o.isoformat()
|
|
|
|
if o.microsecond:
|
|
|
|
r = r[:23] + r[26:]
|
|
|
|
if r.endswith('+00:00'):
|
|
|
|
r = r[:-6] + 'Z'
|
|
|
|
return r
|
2006-07-31 22:59:53 +08:00
|
|
|
elif isinstance(o, datetime.date):
|
2011-11-18 21:01:06 +08:00
|
|
|
return o.isoformat()
|
2006-06-30 00:42:49 +08:00
|
|
|
elif isinstance(o, datetime.time):
|
2011-11-18 21:01:06 +08:00
|
|
|
if is_aware(o):
|
|
|
|
raise ValueError("JSON can't represent timezone-aware times.")
|
|
|
|
r = o.isoformat()
|
|
|
|
if o.microsecond:
|
|
|
|
r = r[:12]
|
|
|
|
return r
|
2007-05-21 09:29:58 +08:00
|
|
|
elif isinstance(o, decimal.Decimal):
|
|
|
|
return str(o)
|
2006-06-30 00:42:49 +08:00
|
|
|
else:
|
2007-05-21 09:29:58 +08:00
|
|
|
return super(DjangoJSONEncoder, self).default(o)
|
|
|
|
|
|
|
|
# Older, deprecated class name (for backwards compatibility purposes).
|
|
|
|
DateTimeAwareJSONEncoder = DjangoJSONEncoder
|
|
|
|
|