PageRenderTime 9ms CodeModel.GetById 1ms app.highlight 5ms RepoModel.GetById 1ms app.codeStats 0ms

/appengine_django/serializer/json.py

http://google-app-engine-django.googlecode.com/
Python | 48 lines | 21 code | 6 blank | 21 comment | 1 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"""
18Replacement for the Django JSON encoder that handles microseconds.
19"""
20import datetime
21
22from django.utils import datetime_safe
23from django.utils import simplejson
24
25
26class DjangoJSONEncoder(simplejson.JSONEncoder):
27    """
28    JSONEncoder subclass that knows how to encode date/time with microseconds.
29    """
30
31    DATE_FORMAT = "%Y-%m-%d"
32    TIME_FORMAT = "%H:%M:%S"
33
34    def default(self, o):
35        if isinstance(o, datetime.datetime):
36            d = datetime_safe.new_datetime(o)
37            output = d.strftime("%s %s" % (self.DATE_FORMAT, self.TIME_FORMAT))
38            return "%s.%s" % (output, d.microsecond)
39        elif isinstance(o, datetime.date):
40            d = datetime_safe.new_date(o)
41            return d.strftime(self.DATE_FORMAT)
42        elif isinstance(o, datetime.time):
43            output = o.strftime(self.TIME_FORMAT)
44            return "%s.%s" % (output, o.microsecond)
45        elif isinstance(o, decimal.Decimal):
46            return str(o)
47        else:
48            return super(DjangoJSONEncoder, self).default(o)