【问题标题】:Can a @classmethod modify the record it creates in GAE?@classmethod 可以修改它在 GAE 中创建的记录吗?
【发布时间】:2014-10-04 14:09:32
【问题描述】:

@classmethod 中创建实体的更新不会可靠地保存在数据存储中。

我的创建方法如下。参数是要持久化的对象。

@classmethod
    def create(cls, obj):
        """Factory method for a new system entity using an System instance. Returns a System object (representation) including the meta_key."""        
        if isinstance(obj, System):
            pass
        else:
            raise Exception('Object is not of type System.')

        #check for duplicates
        q = dbSystem.all(keys_only=True)
        q.filter('meta_guid = ', obj.meta_guid)
        if q.get(): #match exists already
            raise Exception('dbSystem with this meta_guid already exists.  Cannot create.')                    


        # store stub so we can get the key
        act = cls(
                meta_status = obj.meta_status,
                meta_type = obj.meta_type,
                meta_guid = obj.meta_guid,
                json = None, 
                lastupdated=datetime.datetime.now())              
        act.put()

        # get the key for the datastore entity and add it to the representation
        newkey = str(act.key())

        # update our representation
        obj.meta_key = newkey

        # store the representation
        act.json = jsonpickle.encode(obj)
        act.put()

        return(obj)  #return the representation

我的单元测试确认返回的对象有一个 meta_key,并且关联实体的 json 不是无:

self.assertIsNotNone(systemmodel.dbSystem().get(s.meta_key).json) #json is not empty

但是,当在开发服务器上运行我的应用程序时,我发现稍后检索此实体时,json 字段间歇性地为 NULL。

我花了一些时间研究数据存储模型,试图找到可以解释不一致结果的东西,但没有运气。我在 Google 代码上找到的两个关键来源是 model class 和一个非常好的 overview of the App Engine datastore。

任何人都可以确认对创建它的@classmethod 中的实体的更新是否应该被认为是可靠的?有没有更好的方法来持久化对象的表示?

【问题讨论】:

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


    【解决方案1】:

    问题可能出在这一行:

    q = dbSystem.all(keys_only=True)
    

    您还没有说dbSystem 是什么,但如果它执行应用引擎查询,则不能保证您获得对象的最新版本,您可能会获得旧版本。

    相反,您应该通过它的键获取对象,这将保证您获得最新版本。像这样的:

    q = dbSystem.get(obj.key())
    

    查看应用引擎文档以通过键获取对象。

    【讨论】:

    • Kekito - 感谢您的回复。在该方法中,我还不知道密钥,因为尚未创建对象。无论如何,重复检查似乎工作正常。似乎问题出在第二个“act.put()”上;它并不总是保存实体...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-20
    • 2017-02-03
    • 1970-01-01
    相关资源
    最近更新 更多