DEV Community

Cover image for Python Web Programming with Tornado
petercour
petercour

Posted on

2

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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more