Python StructuredProperty 到字典

标签 python google-app-engine

我的模型都有一个将模型转换为字典的方法:

def to_dict(model):
    output = {}
    SIMPLE_TYPES = (int, long, float, bool, dict, basestring, list)
    for key, prop in model._properties.iteritems():
        value = getattr(model, key)

        if value is None:
            continue
        if isinstance(value, SIMPLE_TYPES):
            output[key] = value
        elif isinstance(value, datetime.date):
            dateString = value.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
            output[key] = dateString
        elif isinstance(value, ndb.Model):
            output[key] = to_dict(value)
        else:
            raise ValueError('cannot encode ' + repr(prop))
    return output

现在,我的模型之一 X 有一个 LocalStructuredProperty:

metaData = ndb.LocalStructuredProperty(MetaData, repeated=True)

因此,repeated=True 意味着这将是元数据对象的列表。 MetaData 是另一种模型,它也具有相同的 to_dict 方法。

但是,当我调用 json.dumps(xInstance.to_dict()) 时,出现异常:

raise TypeError(repr(o) + " is not JSON serializable")
TypeError: MetaData(count=0, date=datetime.datetime(2012, 9, 19, 2, 46, 56, 660000), unique_id=u'8E2C3B07A06547C78AB00DD73B574B8C') is not JSON serializable

我该如何处理这个问题?

最佳答案

如果您想在 to_dict() 中以及在序列化为 JSON 之前处理此问题,您只需要在 to_dict() 中添加一些案例即可。首先,你说上面的 to_dict 定义是一个方法。我会将其委托(delegate)给函数或静态方法,这样您就可以在 ints 上调用某些东西,而无需先检查类型。这样代码会变得更好。

def coerce(value):
    SIMPLE_TYPES = (int, long, float, bool, basestring)
    if value is None or isinstance(value, SIMPLE_TYPES):
        return value
    elif isinstance(value, datetime.date):
        return value.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
    elif hasattr(value, 'to_dict'):    # hooray for duck typing!
        return value.to_dict()
    elif isinstance(value, dict):
        return dict((coerce(k), coerce(v)) for (k, v) in value.items())
    elif hasattr(value, '__iter__'):    # iterable, not string
        return map(coerce, value)
    else:
        raise ValueError('cannot encode %r' % value)

然后只需将其插入到您的 to_dict 方法本身中即可:

def to_dict(model):
    output = {}
    for key, prop in model._properties.iteritems():
        value = coerce(getattr(model, key))
        if value is not None:
            output[key] = value
    return output

关于Python StructuredProperty 到字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12488001/

相关文章:

python - 访问当前包的类

google-app-engine - 在 GCP(应用程序引擎)上运行 python Flask Restplus API 的问题

google-app-engine - 请求特定网址时 App Engine 中的 DownloadError

python appengine unicodeencodeerror on search api snippeted results

python - Selenium 网格 - Python 文件路径

python - 检查Python代码是否仍在VM上运行

python - 如何在 Flask/SQLAlchemy 中选择_rel​​ated()?

python - 重新分类 Pandas 数据框中的列

java - 我想开源我的 Google App Engine Java 项目,Eclipse 项目中有授权信息吗?

google-app-engine - 为什么我需要增强数据类?