Tornado Framework Tutorial for Beginners

Facebooktwitterredditpinterestlinkedinmailby feather

Introduction to Python Tornado Framework

Tornado is a Python web framework which provides asynchronous networking library, originally developed at FriendFeed. Tornado is specifically built for applications that require open connections and interaction in both directions. Tornado is different from most Python web frameworks because it is not based on WSGI, and it typically runs with only one thread per process.

The Tornado can scale to tens of thousands of open connections by using the non-blocking network I/O thus; make it ideal for long polling, WebSockets, and other applications that require a long-lived connection to each user.

tornado-framework

Unlike Python’s similar web frameworks, the strength of Tornado is that it very fast, light and simple which means it feels like you’re building something you can control just the way you like it.

Components of Tornado

The tornado can be roughly divided into four major components:

  • A web framework: Web Framework includesRequestHandler which is subclassed to create web applications and various other supporting classes.
  • Client- and server: Client and server-side implementations of HTTP generally includesHTTPServer and AsyncHTTPClient for communicating.
  • Networking Library: An asynchronous networking library, including the classes IOStream and IOLoopserving as the building blocks for the HTTP components. Networking Library is also used to implement other protocols.
  • Coroutine library: A coroutine library (tornado.gen) allows an asynchronous code which is written in a more straightforward way other than chaining callbacks. This is similar to the built-incoroutine feature introduced in Python 3.5. Native coroutines are recommended in place of the Tornado.gen module when available because of their smooth implementation.

The Tornado framework and HTTP server together support a full-stack alternative to WSGI. While it is promising to use the Tornado HTTP server as a container for other WSGI frameworks (WSGIContainer), this combination has several limitations but to take complete advantage of Tornadothe developer will need to use Tornado’s web framework and HTTP server together.

Advantages of Tornado

  • Tornado is a very small framework which allows the user to read the source code easily and understand what’s going on.
  • Because of its smallness, it is more aligned with the Pythonic culture. The developers are encouraged to build a small library code as opposed to building a monolithic structure inside Django.
  • This framework is ideal for building HTTP+JSON service.
  • Tornado runs on Python 3 or PyPy. You gain roughly 2.5X performance running Tornado under PyPy .
  • It doesn’t have an opinion about ORM.
  • This framework supports Event-based paradigm, via IOLoop, is so useful for any networking programming. For example, I can record various statistics outside request life-cycle using tornado.ioloop.IOLoop.instance().add_callback().Another good use for this is to expire cache.
  • The IOLoop also provides a cron-like feature via Tornado .ioloop.PeriodicCallback. This allows you to test cron-like logic as part of development mode instead of asking System Administrator to do it for you in production mode.
  • It provides is far more flexible and faster Template for the templating system.
  • The HTTPServer it provides is incredibly fast, especially considering that it is mostly written in Python. It can deal with 2000 requests per minute easily.

Disadvantages of Tornado:

The disadvantages of Tornado framework are as the following:

  • The non-blocking paradigm is not intuitive to common Pythonista. It requires discipline always to remember not to block the IOLoop.
  • Most Python libraries are blocking, so you have to be creative in making sure IOLoop isn’t blocked. E.g., put non-important stuff inside Tornado .ioloop.IOLoop.instance().add_callback().
  • Most database drivers in Python are blocking even if it’s just a little bit. To alleviate blocking risk, it’s recommended to run multiple Tornado processes proxied behind Nginx (You have to do that anyway in production mode).
  • To take advantage of all Tornado features, you cannot run it on WSGI mode.
  • Tornado stores full uploaded file in memory as opposed to using a temporary file.
  • Tornado community is small, so it’s challenging to find code examples for Tornado.

Tornado- Asynchronous and non-blocking

Tornado uses a single-threaded event loop to minimize the cost of concurrent connections. It means, all application code aims to be non-blocking and asynchronous because only one operation can be achieved at a time. The terms asynchronous and non-blocking are related and are even used interchangeably, but they are different.

Blocking

A function is usually blocked when it waits for something to happen before returning. A function may be blocked for many reasons i.e. disk I/O, mutexes, network I/O, etc. Every function is blocked at least a bit, while it is running and using the CPU. In the context of Tornado, we generally assume blocking only in the area of network I/O, though all kinds of blocking are needed to be minimized.

Asynchronous

An asynchronous function is returned before it is finished and usually causes some work to happen in the background before starting some future action in the application. Asynchronous operations in Tornado usually return placeholder objects, except for some low-level components like the IOLoop that uses callbacks.

Difference between Tornado & Django

Tornado and Django both are frameworks of Python but both have different uses and applications. 

Tornado

Django

The Tornado can scale around thousands of open connections. Thus, making it ideal for long polling, WebSockets, and other applications that require a long-lived connection to each end-user.

Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design.

Tornado is more flexible, and supports web socket, TCP and other communication protocols.

Django supports self-ORM, automatic generation of routing, self-management background, etc.,

Tornado is an asynchronous and non-blocking web framework.

In Django, asynchronous tasks can be achieved through celery, asyncio and aiohttp. 

The applications which support Tornado are Facebook, Keen, Lensley, Indico, Zalando, etc.

The applications which supports Django are Instagram, Pinterest, Udemy, Bitbucket, Zapier, etc.

Templates in Tornado

Tornado provides simple, fast, and flexible templating language. A Tornado template is nothing but just HTML tags (or any other text-based format) with Python control sequences and expressions embedded within the markup language. When you are building a real application, you will use all of the features of Tornado templates, especially template inheritance.

UI Modules

Tornado supports UI modules to make it implementation easy and also to help the standard, reusable UI widgets across your application. UI modules are like particular function which calls to render the components of your page, and they come packaged with their CSS and JavaScript interfaces.

Authentication and Security

Cookies are not secure and can be easily modified by users. If you need to set cookies even to identify the currently logged in user, you need to sign your cookies to prevent forgery. Tornado supports signed cookies with the get_secure_cookie  andset_secure_cookie methods. To use these methods, you need to specify a secret cookie key named cookie_secret when you create your application.

Tornado’s secure cookies application only guarantees integrity but not its confidentiality.The cookie cannot be modified, but the client has access to see its contents. By default, Tornado’s secure cookies expire after every 30 days. Tornado supports multiple signing keys to enable the signing key rotation feature.

Facebooktwitterredditpinterestlinkedinmailby feather