Implementing the Tornado web server

Tornado has several classes and functions that allow you to create different types of network elements, both synchronous and asynchronous. In this particular case, we will focus on the module that allows for the creation of servers and web applications with Tornado. This will be useful to perform proof of concept and understand the operation of certain features in web environments.

The following script will allow for the creation of a basic web server using Tornado, which will accept normal HTTP connections if the user requests the '/' resource.

You can find the following code in the tornado_web_server.py file:

#!/usr/bin/python3

import tornado.ioloop
import tornado.web
from tornado.options import define, options

class MyHandler(tornado.web.RequestHandler):
def get(self):
self.render("index.html")

if __name__ == '__main__':
define("port", default=8080, help="run on the given port", type=int)
app = tornado.web.Application([('/', MyHandler)])
app.listen(options.port)
print("Tornado web server listening on port 8080");
tornado.ioloop.IOLoop.instance().start()

The tornado.web.Application object is responsible for defining the URIs that are available to the web server. In this specific case, it has been defined that the user will be able to access the path '/'. If the user requests the resource '/', the server will be responsible for executing the MyHandler handler.

The MyHandler class inherits from the tornado.web.RequestHandler class, which is responsible for processing HTTP requests that are made by clients that use the GET method. In this case, the class is simply responsible for responding to the client with the index.html page.

Finally, the actual definition of the web server is given by an instance of the tornado.ioloop.IOLoop class which is responsible for creating a thread that will run indefinitely and use the options per line of commands that have been defined by means of the tornado.options.define function.

With all of the preceding information under our belt, it is now possible to run the web server with the following command: 

$ python tornado_web_server.py

When you execute the preceding command, you will see the following message on your console: 

Tornado web server listening on port 8080

If the user requests the resource '/', the server will respond with the index.html page, as shown in the following screenshot:

In this section, we have analyzed how to create our own server with Tornado using the event loop that's provided by the tornado.ioloop package.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset