Examples With Callbacks And Coroutines ====================================== Programming with Motor is far easier with Tornado coroutines than with raw callbacks. Here's an example that shows the difference. With callbacks -------------- An application that can create and display short messages: .. code-block:: python import tornado.web, tornado.ioloop import motor class NewMessageHandler(tornado.web.RequestHandler): def get(self): """Show a 'compose message' form.""" self.write('''
''') # Method exits before the HTTP request completes, thus "asynchronous" @tornado.web.asynchronous def post(self): """Insert a message.""" msg = self.get_argument('msg') # Async insert; callback is executed when insert completes self.settings['db'].messages.insert( {'msg': msg}, callback=self._on_response) def _on_response(self, result, error): if error: raise tornado.web.HTTPError(500, error) else: self.redirect('/') class MessagesHandler(tornado.web.RequestHandler): @tornado.web.asynchronous def get(self): """Display all messages.""" self.write('Compose a message
') self.write('') self.finish() db = motor.MotorClient().open_sync().test application = tornado.web.Application( [ (r'/compose', NewMessageHandler), (r'/', MessagesHandler) ], db=db ) print 'Listening on http://localhost:8888' application.listen(8888) tornado.ioloop.IOLoop.instance().start() The call to :meth:`~motor.MotorCursor.each` could be replaced with :meth:`~motor.MotorCursor.to_list`, which is easier to use with templates because the callback receives the entire result at once: .. code-block:: python from tornado import template messages_template = template.Template('''''') class MessagesHandler(tornado.web.RequestHandler): @tornado.web.asynchronous def get(self): """Display all messages """ self.write('Compose a message
') self.write('