Comment out the 'loadtest' backend in the 'counter' backend sample so that it does...
[gae-samples.git] / geochat / json.py
blob594a79428e6d9b0beb7894d88f791e3576b0bdb9
2 # Copyright 2008 Google Inc.
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
16 """Utility classes and methods for use with simplejson and appengine.
18 Provides both a specialized simplejson encoder, GqlEncoder, designed to simplify
19 encoding directly from GQL results to JSON. A helper function, encode, is also
20 provided to further simplify usage.
22 GqlEncoder: Adds support for GQL results and properties to simplejson.
23 encode(input): Direct method to encode GQL objects as JSON.
24 """
26 import datetime
27 import simplejson
28 import time
30 from google.appengine.api import users
31 from google.appengine.ext import db
34 class GqlEncoder(simplejson.JSONEncoder):
36 """Extends JSONEncoder to add support for GQL results and properties.
38 Adds support to simplejson JSONEncoders for GQL results and properties by
39 overriding JSONEncoder's default method.
40 """
42 # TODO Improve coverage for all of App Engine's Property types.
44 def default(self, obj):
46 """Tests the input object, obj, to encode as JSON."""
48 if hasattr(obj, '__json__'):
49 return getattr(obj, '__json__')()
51 if isinstance(obj, db.GqlQuery):
52 return list(obj)
54 elif isinstance(obj, db.Model):
55 properties = obj.properties().items()
56 output = {}
57 for field, value in properties:
58 output[field] = getattr(obj, field)
59 return output
61 elif isinstance(obj, datetime.datetime):
62 output = {}
63 fields = ['day', 'hour', 'microsecond', 'minute', 'month', 'second',
64 'year']
65 methods = ['ctime', 'isocalendar', 'isoformat', 'isoweekday',
66 'timetuple']
67 for field in fields:
68 output[field] = getattr(obj, field)
69 for method in methods:
70 output[method] = getattr(obj, method)()
71 output['epoch'] = time.mktime(obj.timetuple())
72 return output
74 elif isinstance(obj, time.struct_time):
75 return list(obj)
77 elif isinstance(obj, users.User):
78 output = {}
79 methods = ['nickname', 'email', 'auth_domain']
80 for method in methods:
81 output[method] = getattr(obj, method)()
82 return output
84 return simplejson.JSONEncoder.default(self, obj)
87 def encode(input):
88 """Encode an input GQL object as JSON
90 Args:
91 input: A GQL object or DB property.
93 Returns:
94 A JSON string based on the input object.
96 Raises:
97 TypeError: Typically occurs when an input object contains an unsupported
98 type.
99 """
100 return GqlEncoder().encode(input)