简单表单和模板:
1 import os.path 2 3 import tornado.httpserver 4 import tornado.ioloop 5 import tornado.options 6 import tornado.web 7 8 from tornado.options import define, options 9 define("port", default=8000, help="run on the given port", type=int) 10 11 class IndexHandler(tornado.web.RequestHandler): 12 def get(self): 13 self.render('index.html') 14 15 class PoemPageHandler(tornado.web.RequestHandler): 16 def post(self): 17 noun1 = self.get_argument('noun1') 18 noun2 = self.get_argument('noun2') 19 verb = self.get_argument('verb') 20 noun3 = self.get_argument('noun3') 21 self.render('poem.html', roads=noun1, wood=noun2, made=verb, 22 difference=noun3) 23 24 if __name__ == '__main__': 25 tornado.options.parse_command_line() 26 app = tornado.web.Application( 27 handlers=[(r'/', IndexHandler), (r'/poem', PoemPageHandler)], 28 template_path=os.path.join(os.path.dirname(__file__), "templates") 29 ) 30 http_server = tornado.httpserver.HTTPServer(app) 31 http_server.listen(options.port) 32 tornado.ioloop.IOLoop.instance().start()
输入页面:
1 <!DOCTYPE html> 2 <html> 3 <head><title>Poem Maker Pro</title></head> 4 <body> 5 <h1>Enter terms below.</h1> 6 <form method="post" action="/poem"> 7 <p>Plural noun<br><input type="text" name="noun1"></p> 8 <p>Singular noun<br><input type="text" name="noun2"></p> 9 <p>Verb (past tense)<br><input type="text" name="verb"></p> 10 <p>Noun<br><input type="text" name="noun3"></p> 11 <input type="submit"> 12 </form> 13 </body> 14 </html>
输出页面:
1 <!DOCTYPE html> 2 <html> 3 <head><title>Poem Maker Pro</title></head> 4 <body> 5 <h1>Your poem</h1> 6 <p>Two {{roads}} diverged in a {{wood}}, and I—<br> 7 I took the one less travelled by,<br> 8 And that has {{made}} all the {{difference}}.</p> 9 </body> 10 </html>