python - ComputedProperty 仅在第二次 put() 时更新

标签 python google-app-engine google-cloud-datastore app-engine-ndb google-app-engine-python

我在 StructuredProperty 中有一个 ComputedProperty,它在首次创建对象时不会更新。

当我创建对象时 address_components_ascii 没有被保存。该字段在数据存储查看器中根本不可见。但是,如果我 get() 然后立即再次 put()(即使没有更改任何内容),ComputedProperty 也会按预期工作。 address_components 字段工作正常。

我已经尝试清除数据库,并删除整个数据库文件夹,但没有成功。

我在 Windows 7 上使用本地开发服务器。我没有在 GAE 上测试过它。


代码如下:

class Item(ndb.Model):
    location = ndb.StructuredProperty(Location)

内部 Location 类:

class Location(ndb.Model):
    address_components = ndb.StringProperty(repeated=True)  # array of names of parent areas, from smallest to largest
    address_components_ascii = ndb.ComputedProperty(lambda self: [normalize(part) for part in self.address_components], repeated=True)

归一化函数

def normalize(s):
    return unicodedata.normalize('NFKD', s.decode("utf-8").lower()).encode('ASCII', 'ignore')

address_components 字段的示例:

[u'114B', u'Drottninggatan', u'Norrmalm', u'Stockholm', u'Stockholm', u'Stockholms l\xe4n', u'Sverige']

address_components_ascii 字段,在第二个 put() 之后:

[u'114b', u'drottninggatan', u'norrmalm', u'stockholm', u'stockholm', u'stockholms lan', u'sverige']

最佳答案

真正的问题似乎是 GAE 在 StructuredProperty 上调用 _prepare_for_put() 相对于调用 _pre_put_hook() 的顺序周围的 Model

我正在 Item._pre_put_hook() 中写入 address_components。我假设 GAE 在调用 Item 上的 _pre_put_hook() 之前计算了 StructuredPropertyComputedProperty。从 ComputedProperty 读取会导致重新计算其值。

我将其添加到 _pre_put_hook() 的末尾:

# quick-fix: ComputedProperty not getting generated properly
# read from all ComputedProperties, to compute them again before put
_ = self.address_components_ascii

我将返回值保存到虚拟变量以避免 IDE 警告。

关于python - ComputedProperty 仅在第二次 put() 时更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30266237/

相关文章:

python - 一行异常处理

Python:如何解释 np.argmax() 的结果?

email - 通过 Google Cloud Platform 从 Firebase 发送自动电子邮件(无第三方)

java - 谷歌 App 引擎错误 : No matching index found. (Java)

java - 在哪里可以找到 Google 数据存储区的连接 URL?

django - Google App Engine 教程问题 - 新数据存储模型

python - 使用 Django 对 SQLite 执行原始 SQL 结果为 `DatabaseError: near "?": syntax error`

python - 在 NumPy 中使用两个 bool 数组进行索引

python - threading.local() 是在 Google AppEngine 中为单个请求存储变量的安全方法吗?

java - Google AppEngine (Java) 中的复杂类层次结构