Skip to content

Instantly share code, notes, and snippets.

@tempredirect
Created March 6, 2011 10:36
Show Gist options
  • Save tempredirect/857190 to your computer and use it in GitHub Desktop.
Save tempredirect/857190 to your computer and use it in GitHub Desktop.
DictModel
from google.appengine.ext import db
import datetime
import time
SIMPLE_TYPES = (int, long, float, bool, dict, basestring, list)
# taken from http://stackoverflow.com/questions/1531501/json-serialization-of-google-app-engine-models/1532035#1532035
class DictModel(db.Model):
def to_dict(self):
output = {}
for key, prop in self.properties().iteritems():
value = getattr(self, key)
if value is None or isinstance(value, SIMPLE_TYPES):
output[key] = value
elif isinstance(value, datetime.date):
# Convert date/datetime to ms-since-epoch ("new Date()").
ms = time.mktime(value.utctimetuple()) * 1000
ms += getattr(value, 'microseconds', 0) / 1000
output[key] = int(ms)
elif isinstance(value, db.GeoPt):
output[key] = {'lat': value.lat, 'lon': value.lon}
elif isinstance(value, db.Model):
output[key] = value.to_dict()
else:
raise ValueError('cannot encode ' + repr(prop))
return output
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment