O'Reilly logo

Introduction to Tornado by Brendan Berg, Allison Parrish, Michael Dory

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 2. Forms and Templates

In Chapter 1, we looked at the basics of setting up a web application with Tornado. We covered handlers, HTTP methods, and the overall structure of the Tornado framework. In this chapter, we’re going to take a look at some of the more powerful features that you’re likely to use when building web applications.

As with most web frameworks, one of the primary goals of Tornado is to help you write your applications faster, reusing as much of your code as cleanly as possible. While Tornado is flexible enough to allow you to use nearly any template language supported by Python, it contains a lightweight, fast, and flexible templating language within the tornado.template module.

Simple Example: Poem Maker Pro

Let’s get started with a simple example called Poem Maker Pro. Poem Maker Pro is a web application that presents an HTML form for the user to fill out, and then processes the results of that form. See Example 2-1 for the Python code.

Example 2-1. Simple forms and templates: poemmaker.py
import os.path import tornado.httpserver import tornado.ioloop import tornado.options import tornado.web from tornado.options import define, options define("port", default=8000, help="run on the given port", type=int) class IndexHandler(tornado.web.RequestHandler): def get(self): self.render('index.html') class PoemPageHandler(tornado.web.RequestHandler): def post(self): noun1 = self.get_argument('noun1') noun2 = self.get_argument('noun2') verb = self.get_argument('verb') ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required