from google.appengine.ext import db
from google.appengine.ext.db import BadValueError
import datetime, time
from google.appengine.api import users
SIMPLE_TYPES = (int, long, float, bool, dict, basestring, list)
def to_dict(model):
output = {}
if isinstance(model, db.Query):
output = []
for v in model:
output.append(to_dict(v))
return output
elif isinstance(model, list):
output = []
for v in model:
output.append(to_dict(v))
return output
for key, prop in model.properties().iteritems():
value = getattr(model, key)
if value is None or isinstance(value, SIMPLE_TYPES):
output[key] = value
elif isinstance(value, datetime.date):
output[key] = value.strftime("%Y/%m/%d %H:%M")
elif isinstance(value, db.GeoPt):
output[key] = {'lat': value.lat, 'lon': value.lon}
elif isinstance(value, db.Model):
output[key] = to_dict(value)
elif isinstance(value, users.User):
output = {}
methods = ['nickname', 'email', 'auth_domain']
for method in methods:
output[method] = getattr(value, method)()
return output
else:
raise ValueError('cannot encode ' + repr(prop))
return output
使用範例
import model
rooms= model.Room.all()
self.response.out.write(model.to_dict(rooms))
參考資料
GAE返回JSON数据
How to serialize db.Model objects to json
JSON serialization of Google App Engine models
沒有留言:
張貼留言