Using Mako with Tornado Web Server
January 1, 2010 | In: development, python, real time, tornado
So at work we have been focusing on real time web services a lot lately. Due to this I’ve been getting a chance to play with some awesome new technologies that really lend themselves to the real time web. One of these new technologies is the Tornado Web Server.
“Tornado is an open source version of the scalable, non-blocking web server and tools that power FriendFeed”
We’re using Mako to handle our templates (vs the template module that comes with Tornado). It’s super fast and feature rich and has good documentation. Bellow is a base class I wrote that illustrates how to render Mako templates from a Tornado RequestHandler class. It takes care of setting your template directory, template cache directory and your output encoding (utf-8).
Note: This example assumes that you have your template settings defined as tornado options but they could be very easily just hard coded in.
from tornado.web import RequestHandler
from mako.template import Template
from mako.lookup import TemplateLookup
from tornado.options import options
class BaseRequest(RequestHandler):
def __init__(self, application, request, transforms=None):
RequestHandler.__init__(self, application, request, transforms)
self.lookup = TemplateLookup(directories=[options.template_dir], module_directory=options.mako_modules_dir, output_encoding='utf-8', encoding_errors='replace')
def render_template(self,template_name, **kwargs):
new_template = self.lookup.get_template(template_name)
self.write(new_template.render(**kwargs))
Basically you would just derive your handlers from BaseRequest vs from RequestHandler and you will then be able to render your Mako templates via the render_template method.
Here is an example:
class ExampleHandler(BaseRequest):
def get(self):
self.render_template('example.html')
Shoot me a comment and let me know if you have any questions.










