python-3.xtornadotornado-motor

Tornado + motor, according to the motor document example, even an error


I used the motor library to query mongodb in the tornado project. According to the example of the official document, I was given an error. Who can help me with the code, thank you very much.

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)

when I run the code, exceptions happened:

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 version:3.7
tornado version:6.0.2
motor: 2.0.0


Solution

  • MotorClient gives you a client object, not a database object. This is what your code should look like:

    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(...)