0

Python 3.5 的新手和asyncawait特性

以下代码仅返回一个未来对象。如何从数据库中获取实际的图书项目并将其写入 json?将 async await 与 motor-tornado 一起使用的最佳实践是什么?

async def get(self, book_id=None):
    if book_id:
        book = await self.get_book(book_id)
        self.write(json_util.dumps(book.result()))
    else:
        self.write("Need a book id")

async def get_book(self, book_id):
    book = self.db.books.find_one({"_id":ObjectId(book_id)})
    return book
4

1 回答 1

2

不需要“结果()”。由于您的“get”方法是本机协程(它是用“async def”定义的),因此将它与“await”一起使用意味着结果已经返回给您:

async def get(self, book_id=None):
    if book_id:
        # Correct: "await" resolves the Future.
        book = await self.get_book(book_id)
        # No resolve(): "book" is already resolved to a dict.
        self.write(json_util.dumps(book))
    else:
        self.write("Need a book id")

但是,您还必须在“get_book”中“等待”未来,以便在返回之前解决它:

async def get_book(self, book_id):
    book = await self.db.books.find_one({"_id":ObjectId(book_id)})
    return book
于 2017-04-15T20:07:38.417 回答