/appengine_django/serializer/json.py

http://google-app-engine-django.googlecode.com/ · Python · 48 lines · 21 code · 6 blank · 21 comment · 5 complexity · 250fbe6b2d3cc623a163fa4a008d1fbe MD5 · raw file

  1. #!/usr/bin/python2.4
  2. #
  3. # Copyright 2009 Google Inc.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. """
  17. Replacement for the Django JSON encoder that handles microseconds.
  18. """
  19. import datetime
  20. from django.utils import datetime_safe
  21. from django.utils import simplejson
  22. class DjangoJSONEncoder(simplejson.JSONEncoder):
  23. """
  24. JSONEncoder subclass that knows how to encode date/time with microseconds.
  25. """
  26. DATE_FORMAT = "%Y-%m-%d"
  27. TIME_FORMAT = "%H:%M:%S"
  28. def default(self, o):
  29. if isinstance(o, datetime.datetime):
  30. d = datetime_safe.new_datetime(o)
  31. output = d.strftime("%s %s" % (self.DATE_FORMAT, self.TIME_FORMAT))
  32. return "%s.%s" % (output, d.microsecond)
  33. elif isinstance(o, datetime.date):
  34. d = datetime_safe.new_date(o)
  35. return d.strftime(self.DATE_FORMAT)
  36. elif isinstance(o, datetime.time):
  37. output = o.strftime(self.TIME_FORMAT)
  38. return "%s.%s" % (output, o.microsecond)
  39. elif isinstance(o, decimal.Decimal):
  40. return str(o)
  41. else:
  42. return super(DjangoJSONEncoder, self).default(o)