MongoDB的异步Python驱动:Motor
jopen
11年前
Motor是一个适用于PythonTornado 应用,功能完整,非阻塞的 MongoDB 驱动器。Motor 封装自 PyMongo。
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()