Motor 为 Tornado 提供了一个基于回调和 Future 机制的非堵塞的 MongoDB 驱动程序。Motor 封装了 PyMongo
安装:$ pip install motor
示例代码:
from tornado import gen class NewMessageHandler(tornado.web.RequestHandler): @tornado.web.asynchronous @gen.coroutine def post(self): """Insert a message.""" msg = self.get_argument('msg') db = self.settings['db'] # insert() returns a Future. Yield the Future to get the result. result = yield db.messages.insert({'msg': msg}) # Success self.redirect('/') class MessagesHandler(tornado.web.RequestHandler): @tornado.web.asynchronous @gen.coroutine def get(self): """Display all messages.""" self.write('<a href="/compose">Compose a message</a><br>') self.write('<ul>') db = self.settings['db'] cursor = db.messages.find().sort([('_id', -1)]) while (yield cursor.fetch_next): message = cursor.next_object() self.write('<li>%s</li>' % message['msg']) # Iteration complete self.write('</ul>') self.finish()
Motor API
MotorClient – Connection to MongoDB
MotorClient
MotorReplicaSetClient – Connection to MongoDB replica set
MotorReplicaSetClient
MotorDatabase
MotorCollection
MotorCursor
Motor GridFS Classes
motor.web