Skip to content

Instantly share code, notes, and snippets.

@tylertreat
Last active December 28, 2015 04:18
Show Gist options
  • Save tylertreat/7440983 to your computer and use it in GitHub Desktop.
Save tylertreat/7440983 to your computer and use it in GitHub Desktop.
ndb/db to dict
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