DEV Community

loading...
Cover image for Python Web Programming with Tornado

Python Web Programming with Tornado

petercour profile image petercour ・1 min read

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:

Discussion (0)

Forem Open with the Forem app