Complete Example: The Alpha Munger
In Example 2-4, we’ll put together everything we talked about in this chapter. The application described is called The Alpha Munger. The user inputs two texts: a “source” text and a “replacement” text. The application then returns a copy of the “replacement” text in which each word has been replaced by a word from the source text beginning with the same letter. Figure 2-3 shows the form filled out and Figure 2-4 shows the resulting text.
This application consists of four files: main.py (the Tornado program), style.css (a CSS stylesheet file), index.html, and munged.html (Tornado templates). Let’s look at the code:
Example 2-4. Complete forms and templates: main.py
import os.path import random 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 MungedPageHandler(tornado.web.RequestHandler): def map_by_first_letter(self, text): mapped = dict() for line in text.split('\r\n'): for word in [x for x in line.split(' ') if len(x) > 0]: if word[0] not in mapped: mapped[word[0]] = [] mapped[word[0]].append(word) return mapped def post(self): source_text = self.get_argument('source') text_to_change = self.get_argument('change') source_map = self.map_by_first_letter(source_text) change_lines = text_to_change.split('\r\n') ...
Get Introduction to Tornado now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.