Tornado框架中视图模板Template的使用
2015-03-19 00:00
471 查看
上文的程序中有这样一段:
当收到GET请求时,返回一段HTML表单。
上面的这种写法,将html写在python代码中,灵活性差,而且view代码与controller代码混合在一块,不符合MVC的原则。
所以我们采用Tornado中的模板。
新建form.html:
然后将上面的python代码修改为:
这样代码简洁了很多。
完整的代码是:
class MessageHandler(tornado.web.RequestHandler): def get(self): self.write(''' <html> <head> <title>Please Input Message</title> </head> <body> <form action="/message" method="post"> <input type="text" name="message"><br> <input type="submit" value="submit"> </form> </body> </html>''' ) def post(self): #self.set_header("Content-Type", "text/plain") self.write("You wrote <h1>" + self.get_argument("message") + "</h1>")
当收到GET请求时,返回一段HTML表单。
上面的这种写法,将html写在python代码中,灵活性差,而且view代码与controller代码混合在一块,不符合MVC的原则。
所以我们采用Tornado中的模板。
新建form.html:
<html> <head> <title>{{title}}</title> </head> <body> <form action="/message" method="post"> <input type="text" name="message" value="please input."> <input type="submit" value="submit"> </form> </body> </html>
然后将上面的python代码修改为:
class MessageHandler(tornado.web.RequestHandler): def get(self): self.render("form.html", title="Input Message") def post(self): #self.set_header("Content-Type", "text/plain") self.write("You wrote <h1>" + self.get_argument("message") + "</h1>")
这样代码简洁了很多。
完整的代码是:
import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): self.write("<h1>This is Home Page!</h1>") class StoryHandler(tornado.web.RequestHandler): def get(self, story_id): self.write("You request the story <h1>" + story_id + "</h1>") class MessageHandler(tornado.web.RequestHandler): def get(self): self.render("form.html", title="Input Message") def post(self): #self.set_header("Content-Type", "text/plain") self.write("You wrote <h1>" + self.get_argument("message") + "</h1>") application = tornado.web.Application([ (r"/", MainHandler), (r"/story/([0-9]+)", StoryHandler), (r"/message", MessageHandler), ]) if __name__ == '__main__': application.listen(8888) tornado.ioloop.IOLoop.instance().start()
相关文章推荐
- Tornado框架中视图模板Template的使用
- CodeIgniter 视图使用两种模板Template布局的方式
- tornado 学习笔记9 Tornado web 框架---模板(template)功能分析
- ASP.NET MVC 使用AderTemplate模板引擎进行视图显示
- 为Python的Tornado框架配置使用Jinja2模板引擎的方法
- 为Python的Tornado框架配置使用Jinja2模板引擎的方法
- django template 基础(二)(在视图中使用模板)
- VTemplate模板引擎的使用 - MasterPage篇
- 动态模板类使用 ITemplate 接口 GridView动态模板
- VS2008使用问题,打开套用模板页后设计视图无内容显示但调试就有内容(已解决)
- MFC应用程序中指针的使用 视图 框架 文档 状态栏 菜单栏
- 使用SpringMVC框架生成XLS和PDF格式的WEB应用视图
- MFC应用程序中指针的使用 视图 框架 文档 状态栏 菜单栏
- ASP.NET MVC Tip #19 – 使用 nVelocity 视图模板引擎
- python下的web开发框架-Django,django模板的使用
- eclipse myeclipse 下使用模板 Template
- VTemplate模板引擎的使用--进阶篇
- 动态模板类使用 ITemplate 接口 GridView动态模板
- VTemplate模板引擎的使用--高级篇
- VTemplate模板引擎的使用--进阶篇