Skip to main content
 首页 » 编程设计

python之覆盖 ndb 属性的默认 _get_for_dict()

2025年04月02日16shihaiming

我很难更改默认的 _get_for_dict() 方法。 这是我的代码目前的样子:

class ImageProperty(ndb.BlobKeyProperty): 
 
    def _get_for_dict(self, entity): 
        value = super(ImageProperty, self)._get_for_dict(entity) 
        if value: 
            return images.get_serving_url(value) 
        else: 
            return None 

我不太了解覆盖方法的概念,也不太了解 ndb 自己的问题...... 基本上我想做的是:将我的数据存储 key 存储为 BlobKeyProperty,但是当将其作为字典检索时,我想获取图像服务 url。

非常感谢

请您参考如下方法:

我还没有尝试过,但我认为作为_from_base_type 钩子(Hook)会更好:

class ImageProperty(ndb.BlobKeyProperty): 
    def _from_base_type(self, value): 
        return images.get_serving_url(value) 

如果我理解documentation正确地,此 API“堆栈”,因此您无需在父类(super class) (BlobKeyProperty) 上调用 _from_base_type。我猜 ndb handles that for you .就我个人而言,我认为当 super 似乎可以正常工作时,这对于 API 来说有点奇怪……但是……我猜就是这样。