python – Google App Engine模型的JSON序列化

我一直在寻找一段时间没有成功。我的项目没有使用Django,有没有一个简单的方法将App Engine模型(google.appengine.ext.db.Model)序列化为JSON或者我需要编写自己的序列化程序?

模型:

class Photo(db.Model):
    filename = db.StringProperty()
    title = db.StringProperty()
    description = db.StringProperty(multiline=True)
    date_taken = db.DateTimeProperty()
    date_uploaded = db.DateTimeProperty(auto_now_add=True)
    album = db.ReferenceProperty(Album, collection_name='photo')
一个简单的递归函数可以用来将一个实体(和任何指向对象)转换为可以传递给simplejson的嵌套字典:

import datetime
import time

SIMPLE_TYPES = (int, long, float, bool, dict, basestring, list)

def to_dict(model):
    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):
            # Convert date/datetime to MILLISECONDS-since-epoch (JS "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] = to_dict(value)
        else:
            raise ValueError('cannot encode ' + repr(prop))

    return output
http://stackoverflow.com/questions/1531501/json-serialization-of-google-app-engine-models

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:python – Google App Engine模型的JSON序列化