0

GAE db.Model 无法存储元组列表。因此,当我将列表从实体中拉出时,我需要将列表保存为 json.dumps 字符串和 json.loads 字符串。我想自动化这个。这是我的尝试:

class example(db.Model):
    someAttr = db.StringListProperty()
    A = db.StringProperty()
    B = db.StringProperty()
    C = db.StringProperty()

    def __setattr__(self, name, value):
        #convert json to string for storage
        if name in ("A", "B", "C"):
            value = json.dumps(value)
        #call default set method
        return super(Quote, self).__setattr__(name, value)

    def __getattribute__(self, name):
        #convert string to json for retrieval
        if name in ("A", "B", "C"):
            val = super(Quote, self).__getattribute__(name)
            return json.loads(val)
        else: 
            # default get behavior
            return super(Quote, self).__getattribute__(name)

当我尝试设置实体的 A、B、C 属性时,我得到:

BadValueError: Property C must be a str or unicode instance, not a list
4

1 回答 1

3

如果您不需要存储非常大的 JSON,我建议您查看 NDB。它具有内置的 JsonProperty:https ://developers.google.com/appengine/docs/python/ndb/properties#types 。

我还在 App Engine Googl Group 中看到了一篇有趣的帖子,其中讨论了一种更有效的存储大型 JSON 的方法:https://groups.google.com/forum/#!msg/google-appengine/WPfAvHDGNjQ/ XfakEMm1qzoJ

于 2012-07-10T03:54:27.177 回答