与龙卷风和电机一起使用异步

Use async with tornado and motor

Python 3.5 和新 asyncawait 功能的新手

下面的代码只returns一个future对象。如何从数据库中获取实际的图书项目并将其写入 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

不需要"result()"。由于您的 "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")

但是您还必须 "await" "get_book" 的未来,以便在返回之前解决它:

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