在 Google App Engine NDB 中,有一个属性类型 JsonProperty
,它采用 Python list
或字典并自动序列化它。
我的模型的结构取决于这个问题的答案,所以我想知道对象何时被反序列化?例如:
# 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']
最佳答案
ndb.JsonProperty
遵循 the docs其执行方式与定义自定义属性时相同:它定义 make_value_from_datastore
和 get_value_for_datastore
方法。
文档不会告诉您何时调用这些方法,因为由应用程序引擎内的数据库实现来决定何时调用这些方法。
但是,只要模型必须访问数据库,它们很可能就会被调用。例如,来自 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% 确定,则必须在每次升级时重新运行测试或重新阅读代码.
关于python - JsonProperty 是否仅在访问时反序列化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13464423/