JsonProperty是否仅在访问时反序列化?

2024-10-03 02:38:55 发布

您现在位置:Python中文网/ 问答频道 /正文

在googleappenginendb中,有一个属性类型JsonProperty,它接受Pythonlist或字典并自动序列化。在

模型的结构取决于这个问题的答案,所以我想知道一个对象何时被反序列化?例如:

# a User model has a property "dictionary" which is of type JsonProperty

# will the following deserialize the dictionary?

object = User.get_by_id(someid)

# or will it not get deserialized until I actually access the dictionary?

val = object.dictionary['value']

Tags: the模型类型getdictionary字典属性序列化
2条回答

ndb.JsonProperty遵循the docs并以与定义自定义属性相同的方式执行操作:它定义make_value_from_datastore和{}方法。在

文档不会告诉您何时调用这些方法,因为何时调用这些方法取决于appengine中的db实现。在

然而,当模型需要访问数据库时,它们很可能会被调用。例如,在get_value_for_datastore的文档中:

A property class can override this to use a different data type for the datastore than for the model instance, or to perform other data conversion just prior to storing the model instance.

如果您真的需要验证发生了什么,可以提供您自己的JsonProperty子类,如下所示:

class LoggingJsonProperty(ndb.JsonProperty):
    def make_value_from_datastore(self, value):
        with open('~/test.log', 'a') as logfile:
            logfile.write('make_value_from_datastore called\n')
        return super(LoggingJson, self).make_value_from_datastore(value)

如果需要,可以记录JSON字符串、回溯等。显然,您可以使用一个标准的日志记录功能,而不是把东西放在单独的日志中。但这足以让我们看到发生了什么。在

当然,另一个选择是阅读代码,我相信它在appengine/ext/db/__init__.py中。在

由于它没有文档记录,因此每个版本的详细信息可能会发生变化,因此每次升级时都必须重新运行测试或重新读取代码(如果需要100%确定的话)。在

正确的答案是,它确实会在访问时延迟加载项:

https://groups.google.com/forum/?fromgroups=#!topic/appengine-ndb-discuss/GaUSM7y4XhQ

相关问题 更多 >