public
Created

Serialize GQL to json

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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.