From a25b4be4418a2a94e38a77b13cc234ca68e8322c Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 3 Sep 2012 13:30:20 +0100 Subject: Support generators --- djangorestframework/utils/encoders.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 djangorestframework/utils/encoders.py (limited to 'djangorestframework/utils/encoders.py') diff --git a/djangorestframework/utils/encoders.py b/djangorestframework/utils/encoders.py new file mode 100644 index 00000000..3cd2e8e1 --- /dev/null +++ b/djangorestframework/utils/encoders.py @@ -0,0 +1,33 @@ +import datetime +import decimal +from django.utils import timezone +from django.utils import simplejson as json + + +class JSONEncoder(json.JSONEncoder): + """ + JSONEncoder subclass that knows how to encode date/time and decimal types. + """ + def default(self, o): + # See "Date Time String Format" in the ECMA-262 specification. + if isinstance(o, datetime.datetime): + r = o.isoformat() + if o.microsecond: + r = r[:23] + r[26:] + if r.endswith('+00:00'): + r = r[:-6] + 'Z' + return r + elif isinstance(o, datetime.date): + return o.isoformat() + elif isinstance(o, datetime.time): + if timezone.is_aware(o): + raise ValueError("JSON can't represent timezone-aware times.") + r = o.isoformat() + if o.microsecond: + r = r[:12] + return r + elif isinstance(o, decimal.Decimal): + return str(o) + elif hasattr(o, '__iter__'): + return [i for i in o] + return super(JSONEncoder, self).default(o) -- cgit v1.2.3