在ndb gae中使用始终异步ndb操作

时间:2014-05-29 10:35:37

标签: google-app-engine asynchronous google-cloud-datastore app-engine-ndb tasklet

我正在使用gae和ndb进行开发,我发现我必须为ndb获取和查询编写大量代码。有时我需要两个版本(有时3个或更多)。

假设我内部有以下模型和功能:

class MainEnt(ndb.Model):
    """Main entity. The parent is the user_key"""
    name = ndb.StringProperty()
    child = ndb.KeyProperty()

    def get_created_by(self, user_id):
        """Get the MainEnt's created by user_id"""
        # stuff... getting the query and returning the results

    def get_created_by_async(self, user_id):
        """Get async the MainEnt's created by user_id"""
        # stuff... getting the query async and returning a future

    @ndb.tasklet
    def get_childs_async_tasklet(self, mainent_key):
        """Get async the childs of a MainEnt"""
        # stuff... yielding the query async. and raise ndb.Return()...

    @ndb.tasklet
    def get_created_by_async_tasklet(self, user_id):
        """Get async the MainEnt's created by user_id"""
        # stuff... yielding the query async. and raise ndb.Return()...

    @ndb.tasklet
    def get_created_by_async_tasklet_with_childs(self, user_id):
        """Get async the MainEnt's created by user_id and its childs"""
        # stuff... yielding the query async. calling get_childs.. and raise ndb.Return()...

    @ndb.tasklet
    def get_voted_by_async_tasklet(self, user_id):
        """Get async the MainEnt's voted by user_id"""
        # stuff... yielding the query async raise ndb.Return()...

    @ndb.tasklet
    def get_voted_by_async_tasklet_with_childs(self, user_id):
        """Get async the MainEnt's voted by user_id and it's childs"""
        # stuff... yielding the query async, calling get_childs.. and raise ndb.Return()...

    @ndb.tasklet
    def get_created_and_voted_by_async_tasklet(self, user_id):
        """yield get_created_by_async_tasklet and get_voted_by_async_tasklet in parallel"""
        # stuff... yielding the other two functions and return results...

class ChildEnt(ndb.Model):
    name = ndb.StringProperty()

如您所见,MainEnt有三种方法可以返回“相同”(有时更多)的结果,但会在不同的上下文中使用。

1)同步功能仅在我需要获取结果并获得结果时才使用,是唯一的“ndb操作”。

2)async函数仅在我需要获取结果时使用,但我还执行了一些我想要重叠的其他ndb查询。

3)tasklet异步函数仅在我需要获取结果时使用,获取此结果的子实体,也可能还执行其他一些ndb操作。

因为我发现编写了太多的函数...只编写一个异步的tasklet函数是正确的,这个函数将在以前的每个情况中被调用?

我的意思是即使我只需要结果同步,我也会调用get_created_by_async_tasklet,然后在函数返回的未来调用get_results。

在执行此操作时,是否会对性能,容易出错等造成任何不便? 我发现每个查询,get等等总是使用ndb异步tasklet更简单...如果我也需要调用它的结果,或者执行更多的异步操作,然后调用get_results。

希望这个解释得很好......

提前致谢!

1 个答案:

答案 0 :(得分:3)

仅使用异步调用没有任何问题,如果您希望同步结果,则立即使用get_result。这正是ndb同步函数的作用:

Here is an example from ndb.Key

def get(self, **ctx_options):
    """Synchronously get the entity for this Key.

    Return None if there is no such entity.
    """
    return self.get_async(**ctx_options).get_result()