使用 google-cloud-datastore 子类实体

问题描述

我已将第一代 GAE Python 2 应用程序迁移到第二代 GAE Python 3。这并不容易,但似乎一切正常。

我现在想从 google-cloud-ndb 迁移到 google-cloud-datastore。使用 google-cloud-datastore,是否可以以类似于子类化 Entity 的方式子类化 ndb.Model(这是一个 dict 子类)?

例如 google-cloud-ndb 代码如下所示:

from google.cloud import ndb

class Foo(ndb.Model):
    x = ndb.StringProperty(default='42')

    def do_something(self):
        pass

这是将上述内容迁移到 google-cloud-datastore 的正确方法吗?:

from google.cloud.datastore.entity import Entity

class Foo(Entity):

    def __init__(self):
        super().__init__()
        self['x'] = '42'

    def do_something(self):
        pass

我还没有看到任何这样的示例代码,所以我想确认这是一个很好的做法,尤其是在覆盖 __init__ 的情况下。

更好的是,有没有一种方法可以将 Entity 子类化,以便我可以将数据作为对象属性 (foo.x) 而不是字典 (foo['x']) 访问?这将使迁移更加容易。

解决方法

我怀疑我的问题中的解决方案不是一个好的解决方案,这样的解决方案会更好:

from google.cloud.datastore.entity import Entity

class Foo():

    x: str

    def __init__(self):
        super().__init__()
        self.x = '42'

    def do_something(self):
        pass

    def to_dict(self):
        return {'x': self.x}

    @staticmethod
    def from_dict(self,data):
        f = Foo()
        f.x = data['x']
        return f

能从已经经历过这件事的人那里得到反馈会很棒。