Last active
December 28, 2015 04:18
-
-
Save tylertreat/7440983 to your computer and use it in GitHub Desktop.
ndb/db to dict
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
import datetime | |
import time | |
from google.appengine.ext import db | |
from google.appengine.ext import ndb | |
def to_dict(model): | |
"""Convert a db or ndb entity to a json-serializable dict.""" | |
output = {} | |
for key, prop in model._properties.iteritems(): | |
value = getattr(model, key) | |
if value is None or isinstance(value, SERIALIZABLE_TYPES): | |
output[key] = value | |
elif isinstance(value, datetime.date): | |
# Convert date/datetime to unix timestamp | |
output[key] = time.mktime(value.utctimetuple()) | |
elif isinstance(value, (db.Key, ndb.Key)): | |
output[key] = value.id() | |
elif isinstance(value, (db.Model, ndb.Model)): | |
output[key] = to_dict(value) | |
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