tornado一起来-模版渲染
好吧,表示单单输出一句话,好像没什么难度,并且显示也很丑。
那就使用模版吧。一听模版是不是瞬间感觉高大上了。(偷笑中)
主要内容参考《Introduction to Tornado》中文翻译
现在开始!
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') noun3 = self.get_argument('noun3') self.render('poem.html', roads=noun1, wood=noun2, made=verb, difference=noun3) if __name__ == '__main__': tornado.options.parse_command_line() app = tornado.web.Application( handlers=[(r'/', IndexHandler), (r'/poem', PoemPageHandler)], template_path=os.path.join(os.path.dirname(__file__), "templates") ) http_server = tornado.httpserver.HTTPServer(app) http_server.listen(options.port) tornado.ioloop.IOLoop.instance().start()
再来一个模版index.html
<!DOCTYPE html> <html> <head><title>Poem Maker Pro</title></head> <body> <h1>Enter terms below.</h1> <form method="post" action="/poem"> <p>Plural noun<br><input type="text" name="noun1"></p> <p>Singular noun<br><input type="text" name="noun2"></p> <p>Verb (past tense)<br><input type="text" name="verb"></p> <p>Noun<br><input type="text" name="noun3"></p> <input type="submit"> </form> </body> </html>
poem.html
<!DOCTYPE html> <html> <head><title>Poem Maker Pro</title></head> <body> <h1>Your poem</h1> <p>Two {{roads}} diverged in a {{wood}}, and I—<br> I took the one less travelled by,<br> And that has {{made}} all the {{difference}}.</p> </body> </html>
看到这样子,表示运气真好。