新手到Python 3.5以及新的async
和await
功能
以下代码仅返回将来的对象。如何从数据库中获取实际的书籍项目并将其写入json?什么是使用异步等待和电机龙卷风的最佳做法?
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
答案 0 :(得分:2)
不需要"结果()"。因为你的"得到"方法是一个本地协程(它用" 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