【问题标题】:Use async with tornado and motor对龙卷风和电机使用异步
【发布时间】:2017-04-15 14:22:01
【问题描述】:

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

【问题讨论】:

    标签: python mongodb asynchronous tornado tornado-motor


    【解决方案1】:

    不需要“结果()”。由于你的“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
    

    【讨论】:

    • 嗨戴维斯。我尝试了上面的代码但得到了错误:Object of type 'Future' is not JSON serializable
    • 哦,我错过了 get_book 中的一步。我已经更新了我的答案。
    猜你喜欢
    • 2018-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多