What is Tornado? Tornado is a popular event-loop based web framework.
Most people who talk about Tornado usually mentioned how fast it is when hitting “Hello World” using Apache Benchmark. This post is not about that.
In most web application request cycle, it’s common for the request handler (or controller) to perform various tasks that are less important than page delivery (and sometimes expensive). Tasks like recording analytic, updating counts, processing uploaded files, etc.
Django applications solve this problem by creating jobs on Celery or Gearman.
Rails applications solve this problem by creating jobs on Resque or various AMQP solutions.
Tornado applications solve this problem through IOLoop.add_callback() within itself, without any external daemons:
pass # your expensive work
Web applications sometimes need to perform routine work. Many people solve this problem using cron. Some people try to reinvent cron through scheduler daemon.
Meanwhile, Tornado have built-in solution to this problem:
def run_me_everyday_callback(): pass
tornado.ioloop.PeriodicCallback(run_me_everyday_callback, 24 * 60 * 60 * 1000).start()
- node.js also have the same benefit through setInterval()
- It’s true that the interval doesn’t use system clock, but that’s solvable by running the callback every X seconds, but check the system clock first.
Tornado has 0 external dependencies. It has its own HTTP parser, epoll.c, template engine, and even web server. It used to depend on curl strictly, but now Tornado shipped SimpleAsyncHTTPClient that’s 100% Python.
Having minimal dependencies is very nice. When I encountered any bugs, I can file them under GitHub issue tracking or mentioned them on the mailing list. The core developers can basically fix everything inside Tornado.
Its fast web server also makes deployment simpler. You typically only need nginx/haproxy in front of Tornado instances.
It’s a micro framework
Besides having zero external dependencies, Tornado is also small in terms of LoC. Because of its simplicity:
- Tornado can run under PyPy.
- Tornado applications can use cream of the crop Python modules (e.g. SQLAlchemy).
- It’s very easy to add/extends any parts of Tornado.
- With a careful planning, your Tornado application can use very little memory per instance. Less memory means you can spawn more instances per box.
It supports OAuth authentication to famous social networks
Thanks to the various mixins that Tornado provides, your application can connect to Google, Twitter, or Facebook in no time.
It has global Application object
Unlike Django and very similar to the design of Flask, CherryPy, web.py, or Sinatra+Rack. With this design, it’s very easy to instantiate multiple Tornado apps inside one Python runtime. It makes interactive debugging easier.
It has a familiar template engine
Tornado’s template engine is very similar to Django template or Jinja2, developers won’t have much trouble getting up to speed in it.