DEV Community

Cover image for Python Web Programming with Tornado
petercour
petercour

Posted on

Python Web Programming with Tornado

There are many modules to create web apps. Django and Flask are the most popular ones. But there are others, like Tornado.

How does Tornado work? It's actually quite simple. A single one page app is:

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import tornado.ioloop   
import tornado.web

class HomeHandler(tornado.web.RequestHandler): 
    def get(self):
        self.write("hello, world")

app = tornado.web.Application([ (r"/", HomeHandler), ])
app.listen(8000)
tornado.ioloop.IOLoop.instance().start()

Open localhost port 8000 on your web browser to see the hello world message. The script itself does not output anything in the terminal.

You can create different routes when initializing the tornado.Web.Application() call. Each route is a class.

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import tornado.ioloop 
import tornado.web

class HomeHandler(tornado.web.RequestHandler): 
    def get(self):
        self.write("hello, world")

class AboutHandler(tornado.web.RequestHandler): 
    def get(self):
        self.write("Mr President")


app = tornado.web.Application([
    (r"/", HomeHandler), 
    (r"/about", AboutHandler)
])
app.listen(8000)
tornado.ioloop.IOLoop.instance().start()

Then you can open the / route or the /about route.

Related links:

Top comments (0)