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
8 # http://www.apache.org/licenses/LICENSE-2.0
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.
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.
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
):
54 elif isinstance(obj
, db
.Model
):
55 properties
= obj
.properties().items()
57 for field
, value
in properties
:
58 output
[field
] = getattr(obj
, field
)
61 elif isinstance(obj
, datetime
.datetime
):
63 fields
= ['day', 'hour', 'microsecond', 'minute', 'month', 'second',
65 methods
= ['ctime', 'isocalendar', 'isoformat', 'isoweekday',
68 output
[field
] = getattr(obj
, field
)
69 for method
in methods
:
70 output
[method
] = getattr(obj
, method
)()
71 output
['epoch'] = time
.mktime(obj
.timetuple())
74 elif isinstance(obj
, time
.struct_time
):
77 elif isinstance(obj
, users
.User
):
79 methods
= ['nickname', 'email', 'auth_domain']
80 for method
in methods
:
81 output
[method
] = getattr(obj
, method
)()
84 return simplejson
.JSONEncoder
.default(self
, obj
)
88 """Encode an input GQL object as JSON
91 input: A GQL object or DB property.
94 A JSON string based on the input object.
97 TypeError: Typically occurs when an input object contains an unsupported
100 return GqlEncoder().encode(input)