【问题标题】:Tornado + motor, according to the motor document example, even an errorTornado + motor,根据电机文档示例,甚至出现错误
【发布时间】:2019-04-20 10:52:01
【问题描述】:

我在tornado项目中使用motor库查询mongodb。按照官方文档的例子,报错了。哪位大侠能帮我看看代码,非常感谢。

from tornado.ioloop import IOLoop
import motor


async def do_insert():
    db = motor.motor_tornado.MotorClient('mongodb://localhost:27017')
    document = {'key': 'value'}
    result = await db.books.insert_one(document)
    print(result)


if __name__ == "__main__":
    IOLoop.instance().run_sync(do_insert)

当我运行代码时,发生了异常:

Traceback (most recent call last):
  File "/Users/msean/python_project/amazon-riskhelper/test/test_db.py", line 13, in <module>
      IOLoop.instance().run_sync(do_insert)
  File "/Users/msean/.virtualenvs/amazon- 
  riskhelper/lib/python3.7/site-packages/tornado/ioloop.py", line 532, in run_sync
      return future_cell[0].result()
  File "/Users/msean/python_project/amazon-riskhelper/test/test_db.py", line 8, in do_insert
      result = await db.books.insert_one(document)
  File "/Users/msean/.virtualenvs/amazon-riskhelper/lib/python3.7/site-packages/motor/core.py", line 554, in __call__
self.delegate.name)
  TypeError: MotorCollection object is not callable. If you meant to call the 'insert_one' method on a MotorCollection object it is failing because no such method exists.

python 版本:3.7
tornado 版本:6.0.2
电机:2.0.0

【问题讨论】:

    标签: python-3.x tornado tornado-motor


    【解决方案1】:

    MotorClient 为您提供客户端对象,而不是数据库对象。你的代码应该是这样的:

    client = motor.motor_tornado.MotorClient('mongodb://localhost:27017')
    
    db = client.db_name # replace `db_name` with actual name of the db
    
    ...
    
    result = await db.books.insert_one(...)
    

    【讨论】:

      猜你喜欢
      • 2017-07-09
      • 2015-10-03
      • 2015-04-11
      • 2017-11-20
      • 2017-03-05
      • 2011-01-29
      • 1970-01-01
      • 2021-09-11
      • 2020-08-10
      相关资源
      最近更新 更多