【问题标题】:BadYieldError when using find() Motor [MongoDB + Tornado]使用 find() 电机时出现 BadYieldError [MongoDB + Tornado]
【发布时间】:2015-10-03 23:29:00
【问题描述】:

我是 python tornado 框架的新手。我在 MongoDB 中有一小部分数据。我在我的 python 文件中使用了一个简单的 get 函数。使用db.collection.find() 选项时,我得到BadYieldError。但是db.collection.find_one() 工作正常,但它只显示一条记录。

import tornado
import bson
from bson import json_util
from bson.json_util import dumps
class TypeList(APIHandler):
@gen.coroutine
def get(self):
    doc = yield db.vtype.find()
    self.write(json_util.dumps(doc))

错误是:

tornado.gen.BadYieldError: 产生未知对象 MotorCursor()

【问题讨论】:

    标签: python json mongodb tornado-motor


    【解决方案1】:

    find 返回一个MotorCursor。让光标的fetch_next 属性使光标前进并调用next_object() 来检索当前文档:

    @gen.coroutine
    def do_find():
        cursor = db.test_collection.find({'i': {'$lt': 5}})
        while (yield cursor.fetch_next):
            document = cursor.next_object()
            print document
    

    有关使用 Motor 的 find 和 MotorCursor 的说明,请参阅教程部分 Querying for More Than One Document。

    【讨论】:

    • 你能告诉我如何将值返回给浏览器吗?因为当我 return document 而不是 print document 它给我 TypeError: Expected none got.... 而当我使用 self.write(document) 它给我TypeError: ObjectId('55a5e988545779f35d3ecdf4') is not JSON serializable
    • RequestHandlers 使用 self.write 向用户发送字节。 Python 模块顶部的“from bson import json_util”,然后是(未经测试的)docs = yield cursor.to_list(None); self.write(json_util.dumps({'docs': docs}).encode())。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多