Tornado is a free, non-blocking web server and a simple micro-web framework in Python. Its development began at FriendFeed, after Facebook acquired FriendFeed, Tornado was published under an open-source license. The Tornado web server uses wait times, for example when receiving data, by turning to other tasks (on Linux with epoll, under BSD with kqueue). This non-blocking behaviour allows a very large number of requests to be handled simultaneously. The development was carried out with the background of the C10K problem and measurements yield over 8,000 processed requests per second. Tornado provides mixins for the OpenID and OAuth authentication systems, with simplified connectivity to The authentication interfaces of Google, Facebook Connect, and Twitter.
Asynchronous processing of requests has been a core element of Tornado from the outset. Since Python 3.5, the Python language elements async def and await are used instead of a separate module. A sample application shows how to use it in the FriendFeeds chat system. In addition, the common components of a micro-web framework are available:
- Management of cookies (with possibility to sign them to verify their authenticity) and sessions
- Template system
- Cross-site scripting protection
- Support for multilingualism
Tornado is not like most Python frameworks. It is not based on WSGI, but it supports some features of WSGI. The Tornado can be installed via pip :
pip install tornado
We need to create our first app for Tornado with the below snippet :
return tornado.web.Application([ (r"/", MainHandler), ]) # URL Mapping
if __name__ == "__main__":
app = make_app()
app.listen(8888) # Port Number
This App can run by typing
python3 hello_server.py and can be accessed by going to
127.0.0.1:8888 from the browser. The server will return “Hello World”. This is how the basic thing works. Various HTML templates are distributed as examples.
A commonly asked question is how to use PHP. PHP can be executed from the shell via
php script_name.php using PHP CLI package. It is possible to call system commands from python and read their output using the subprocess module:
Another question is about choosing Tornado over Django. If you do not need real-time updates and do
not plan to have a site with thousands of users holding a constant HTTP connection, using Tornado probably meaningless because Django is more matured. Tornado is an ideal framework for real-time web services such as distributed chat, trading platforms, electronics (Raspberry Pi and Arduino), audio/video streaming and so on.