Skip to main content

Creating your first Tornado application

Introduction

Tornado is a powerful Python web framework and asynchronous networking library. It's particularly beneficial for web applications that require real-time updates or long polling. In this tutorial, we will create a very basic web application using Tornado.

Prerequisites

  1. Basic knowledge of Python
  2. Python installed on your local machine (Python 3.6 or above is recommended)
  3. An Integrated Development Environment (IDE), like PyCharm or Visual Studio Code

Installation

Before we begin, we need to install Tornado. Open your terminal or command prompt and type the following command:

pip install tornado

Creating a Simple Tornado Application

Let's build a basic "Hello, World!" application.

First, create a new Python file and name it app.py. In this file, we will write our Tornado application code.

import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, World!")

def make_app():
return tornado.web.Application([
(r"/", MainHandler),
])

if __name__ == "__main__":
app = make_app()
app.listen(8888)
tornado.ioloop.IOLoop.current().start()

Understanding the Code

  • The MainHandler class is a subclass of tornado.web.RequestHandler which defines a method get(). This method is called when a GET HTTP request is received. The self.write() function sends a string to the client as a response.

  • The make_app() function creates an instance of tornado.web.Application, the main class for Tornado applications. It takes a list of tuples, each containing a URL pattern and a corresponding RequestHandler subclass.

  • The last block of code is the server code. app.listen(8888) makes the application listen on port 8888. tornado.ioloop.IOLoop.current().start() starts the I/O loop, which waits for requests and handles them when they arrive.

Running the Application

To run the application, navigate to the directory where your app.py file is located and run the following command:

python app.py

Then, open your web browser and navigate to http://localhost:8888. You should see "Hello, World!" displayed on the page.

Conclusion

Congratulations! You have just created your first Tornado application. This tutorial only scratches the surface of what you can do with Tornado. You can create more complex applications with templates, user authentication, databases, and more. Keep practicing and exploring Tornado's capabilities to build robust web applications.