Skip to content

Instantly share code, notes, and snippets.

@andreagrandi
Created August 6, 2013 11:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andreagrandi/6163724 to your computer and use it in GitHub Desktop.
Save andreagrandi/6163724 to your computer and use it in GitHub Desktop.
Custom JSONRenderer for DjangoRestFramework
from __future__ import unicode_literals
from django.utils.functional import Promise
from rest_framework.compat import timezone, force_text
from django.utils.encoding import smart_unicode
from rest_framework import renderers
import datetime
import decimal
import types
import json
from bson import ObjectId
class FbxJSONEncoder(json.JSONEncoder):
"""
FbxJSONEncoder subclass that knows how to encode date/time/timedelta,
decimal types, generators and Mongo ObjectId.
"""
def default(self, o):
# For Date Time string spec, see ECMA 262
# http://ecma-international.org/ecma-262/5.1/#sec-15.9.1.15
if isinstance(o, Promise):
return force_text(o)
elif 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 and 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, datetime.timedelta):
return str(o.total_seconds())
elif isinstance(o, decimal.Decimal):
return str(o)
elif hasattr(o, '__iter__'):
return [i for i in o]
elif isinstance(o, ObjectId):
return str(o)
return super(JSONEncoder, self).default(o)
class FbxRenderer(renderers.JSONRenderer):
encoder_class = FbxJSONEncoder
def render(self, data, media_type=None, renderer_context=None):
return data.encode(self.charset)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment