Motor为Tornado提供了一个基于回调和Future机制的非堵塞的MongoDB驱动程序。Motor封装了PyMongo
安装:$pipinstallmotor
示例代码:
from tornado import genclass 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()MotorAPI
MotorClient–ConnectiontoMongoDB
MotorReplicaSetClient–ConnectiontoMongoDBreplicaset
MotorDatabase
MotorCollection
MotorCursor
MotorGridFSClasses
motor.web
评论