JSON serialization of Google App Engine models

后端 未结 14 2126
不知归路
不知归路 2020-12-04 04:59

I\'ve been searching for quite a while with no success. My project isn\'t using Django, is there a simple way to serialize App Engine models (google.appengine.ext.db.Model)

14条回答
  •  一个人的身影
    2020-12-04 05:41

    A simple recursive function can be used to convert an entity (and any referents) to a nested dictionary that can be passed to 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
    

提交回复
热议问题