Google App Engine模型的JSON序列化 [英] JSON serialization of Google App Engine models

查看:104
本文介绍了Google App Engine模型的JSON序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

模特:

  class照片(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

 导入日期时间
导入时间

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

def to_dict(模型):
output = {}
$ b $如果value为None或isinstance(value,SIMPLE_TYPES):$ b,则为model.properties()中的key,prop中的iteritems():
value = getattr(model,key)

$ b output [key] = value
elif isinstance(value,datetime.date):
#将date / datetime转换为MILLISECONDS-since-epoch(JSnew 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('can not encode'+ repr(prop))

return output


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) into JSON or do I need to write my own serializer?

Model:

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')

解决方案

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

这篇关于Google App Engine模型的JSON序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆