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
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') ...