Created
March 6, 2011 10:36
-
-
Save tempredirect/857190 to your computer and use it in GitHub Desktop.
DictModel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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