2006-06-30 00:42:49 +08:00
|
|
|
"""
|
|
|
|
Serialize data to/from JSON
|
|
|
|
"""
|
|
|
|
|
|
|
|
import datetime
|
2010-05-04 22:00:30 +08:00
|
|
|
import decimal
|
2012-04-30 01:58:00 +08:00
|
|
|
import json
|
2013-03-19 13:04:59 +08:00
|
|
|
import sys
|
2015-06-25 00:45:46 +08:00
|
|
|
import uuid
|
2008-07-30 18:40:37 +08:00
|
|
|
|
2012-02-10 02:56:58 +08:00
|
|
|
from django.core.serializers.base import DeserializationError
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.core.serializers.python import (
|
|
|
|
Deserializer as PythonDeserializer, Serializer as PythonSerializer,
|
|
|
|
)
|
2012-07-20 20:22:00 +08:00
|
|
|
from django.utils import six
|
2016-05-26 20:48:36 +08:00
|
|
|
from django.utils.duration import duration_iso_string
|
2015-09-27 02:15:26 +08:00
|
|
|
from django.utils.functional import Promise
|
2011-11-18 21:01:06 +08:00
|
|
|
from django.utils.timezone import is_aware
|
2008-07-30 18:40:37 +08:00
|
|
|
|
2013-11-03 04:12:09 +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
|
|
|
|
2014-11-09 00:08:12 +08:00
|
|
|
def _init_options(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)
|
2013-08-31 21:05:17 +08:00
|
|
|
if self.options.get('indent'):
|
|
|
|
# Prevent trailing spaces
|
|
|
|
self.json_kwargs['separators'] = (',', ': ')
|
2016-06-28 19:48:19 +08:00
|
|
|
self.json_kwargs.setdefault('cls', DjangoJSONEncoder)
|
2014-11-09 00:08:12 +08:00
|
|
|
|
|
|
|
def start_serialization(self):
|
|
|
|
self._init_options()
|
2012-05-26 17:43:37 +08:00
|
|
|
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")
|
2016-06-28 19:48:19 +08:00
|
|
|
json.dump(self.get_dump_object(obj), self.stream, **self.json_kwargs)
|
2012-05-26 17:43:37 +08:00
|
|
|
self._current = None
|
2007-04-25 18:12:05 +08:00
|
|
|
|
2006-06-30 00:42:49 +08:00
|
|
|
def getvalue(self):
|
2012-06-28 22:28:25 +08:00
|
|
|
# Grand-parent super
|
|
|
|
return super(PythonSerializer, self).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.
|
|
|
|
"""
|
2016-12-29 23:27:49 +08:00
|
|
|
if not isinstance(stream_or_string, (bytes, str)):
|
2012-08-12 02:58:45 +08:00
|
|
|
stream_or_string = stream_or_string.read()
|
2012-06-08 00:08:47 +08:00
|
|
|
if isinstance(stream_or_string, bytes):
|
2012-06-15 20:41:16 +08:00
|
|
|
stream_or_string = stream_or_string.decode('utf-8')
|
2012-02-10 02:56:58 +08:00
|
|
|
try:
|
2012-08-12 02:58:45 +08:00
|
|
|
objects = json.loads(stream_or_string)
|
2012-06-15 20:41:16 +08:00
|
|
|
for obj in PythonDeserializer(objects, **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
|
2013-03-19 13:04:59 +08:00
|
|
|
six.reraise(DeserializationError, DeserializationError(e), sys.exc_info()[2])
|
2012-02-10 02:56:58 +08:00
|
|
|
|
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
|
|
|
"""
|
2015-06-24 04:56:22 +08:00
|
|
|
JSONEncoder subclass that knows how to encode date/time, decimal types and UUIDs.
|
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
|
2016-05-26 20:48:36 +08:00
|
|
|
elif isinstance(o, datetime.timedelta):
|
|
|
|
return duration_iso_string(o)
|
2016-12-29 23:27:49 +08:00
|
|
|
elif isinstance(o, (decimal.Decimal, uuid.UUID, Promise)):
|
2007-05-21 09:29:58 +08:00
|
|
|
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)
|