具有多个嵌套函数的ndb.Tasklet和Sync Tasklet

时间:2013-01-25 17:20:30

标签: python google-app-engine asynchronous app-engine-ndb

所以我试图有效地调用tasklet和subtasklets:

@ndb.tasklet
def getBeds(bed_key):
    bed = yield bed_key.get_asyn()
    bed_info = {}
    ......
    raise ndb.Return(bed_info)

@ndb.tasklet
def getRoom(room_key):
    room = yield room_key.get_async()
    room_info = {}
    ..........
    beds_in_room = map(getBeds,room.beds)
    room_info["beds"] = beds_in_room
    raise ndb.Return(room_info)

@ndb.tasklet
def getBuilding(build_key):
    build = yield build_key.get_async()
    build_info = {}
    ...........
    rooms_in_build = map(getRoom,build.rooms)
    build_info["rooms"] = rooms_in_build

@ndb.toplevel
def getHotel(hotel_obj)
    hotel_inf = {}
    .........
    buildings_in_hotel = map(getBuilding,hotel_obj.buildings)
    hotel_inf["buildings"] = buildings_in_hotel
    return hotel_inf

由于某种原因,我虽然@ ndb.toplevel会暂停getHotel,直到一切都完成。不幸的是,buildings_in_hotel正在返回一份期货清单......

我如何完成它?

谢谢! 乔恩

1 个答案:

答案 0 :(得分:3)

你屈服!

调用tasklet时总是会得到一个未来,然后屈服以获得结果。还有并行yield,您可以在其中生成元组或tasklet列表(有时称为barrier)。

beds_in_room = yield map(getBeds,room.beds)

rooms_in_build = yield map(getRoom,build.rooms)

buildings_in_hotel = yield map(getBuilding,hotel_obj.buildings)