【2019-05-29】tornado简单使用笔记

📅 2026/7/21 23:44:30 👁️ 阅读次数 📝 编程学习
【2019-05-29】tornado简单使用笔记

[历史归档]本文原发布于 cstriker1407.info 个人博客,内容为历史存档,仅供参考。
发布时间:2019-05-29| 标题:tornado简单使用笔记分类:编程 / web / tornado |标签:python && jython·bootstrap·tornado


tornado简单使用笔记

    • tornado是什么
    • 安装方法
    • tornado简单DEMO
    • html页面输出方法
      • 使用python代码返回静态html页面
      • 使用python代码返回定制html页面
      • 使用tornado的render功能返回html页面
      • 和bootstrap一起使用

最近要用python来做一个WEB服务器,找来找去,感觉tornado上手比较简单,这里简单笔记下使用要点。

tornado是什么

Tornado是使用Python编写的一个强大的、可扩展的Web服务器。
入门文档:【http://shouce.jb51.net/tornado/index.html 】
官方文档:【 https://tornado-zh.readthedocs.io/zh/latest/index.html 】

安装方法

tornado是一个python组件,因此最简单方式就是pip安装。

#pip3 install tornado

tornado简单DEMO

根据入门文档,我们可以非常快速的实现一个WEB服务器,新建hello_tornado.py代码如下:

#!/usr/bin/python3# -*- coding: UTF-8 -*-importsysimportosimporttornado.httpserverimporttornado.ioloopimporttornado.optionsimporttornado.webfromtornado.templateimportTemplatedefhandler_list():return[(r"/hello_tornado",hello_tornado_handler_main),]classhello_tornado_handler_main(tornado.web.RequestHandler):defget(self):self.write("Rev Get Request:{}".format(self.request))if__name__=="__main__":app=tornado.web.Application(handlers=handler_list(),debug=True)http_server=tornado.httpserver.HTTPServer(app)http_server.listen(8000)tornado.ioloop.IOLoop.instance().start()

然后执行命令:

#python3 hello_tornado.py

我们访问http://127.0.0.1:8000/hello_tornado可以看到结果:

html页面输出方法

tornado有好几种方式可以输出html页面,这里简单笔记下。

使用python代码返回静态html页面

这种方式很简单,直接把html内容返回即可。

classhello_tornado_handler_main(tornado.web.RequestHandler):defget(self):self.write(""" <!DOCTYPE html> <html> <body>Hello world</body> </html> """)

显示如下:

使用python代码返回定制html页面

这种方式是利用tornado的template功能,来替换html中的字符串。

class hello_tornado_handler_main(tornado.web.RequestHandler): def get(self): content=Template("""<!DOCTYPE html><html><body>hello,{{name1}}and{{name2}}</body></html>""")self.write(content.generate(name1="LiLei",name2="HanMM"))

显示如下:

这两种方式都不是太友好,因为将html写入到代码中会耦合显示与业务,所以我们一般使用下面的这种方式。

使用tornado的render功能返回html页面

新建一个hello_tornado.html文件,内容如下:

<!DOCTYPEhtml><html><body>hello,{{name1}} and {{name2}}</body></html>

python代码为:

classhello_tornado_handler_main(tornado.web.RequestHandler):defget(self):self.render("htmls/hello_tornado.html",name1="LiLei",name2="HanMM")

文件结构:

├── hello_tornado.py ├── htmls │ ├── hello_tornado.html

显示如下:

和bootstrap一起使用

如果要和bootstrap同时使用,可以设置 static_path 变量。
hello_tornado.html内容:

<!DOCTYPEhtml><htmllang="zh-CN"><head><metacharset="utf-8"><metahttp-equiv="X-UA-Compatible"content="IE=edge"><metaname="viewport"content="width=device-width, initial-scale=1"><!-- Bootstrap --><link href="{{ static_url("bootstrap-3.3.7-dist/css/bootstrap.min.css") }}" rel="stylesheet"> <link href="{{ static_url("custom_css/ie10-viewport-bug-workaround.css") }}" rel="stylesheet"> <link href="{{ static_url("custom_css/navbar-fixed-top.css") }}" rel="stylesheet"></head><body><divclass="container"><divclass="panel panel-default"><divclass="panel-heading">children table</div><tableclass="table table-bordered"><tbody><tr><th>name</th><th>info</th></tr>{% for child_info in children_infos %}<tr><td>{{child_info[0]}}</td><td>{{child_info[1]}}</td></tr>{% end %}</tbody></table></div></div><script src="{{ static_url("jquery/1.12.4/jquery.min.js") }}"></script><script src="{{ static_url("bootstrap-3.3.7-dist/js/bootstrap.min.js") }}"></script></body></html>

hello_tornado.py完整内容:

#!/usr/bin/python3# -*- coding: UTF-8 -*-importsysimportosimporttornado.httpserverimporttornado.ioloopimporttornado.optionsimporttornado.webfromtornado.templateimportTemplatedefhandler_list():return[(r"/hello_tornado",hello_tornado_handler_main),]classhello_tornado_handler_main(tornado.web.RequestHandler):defget(self):self.render("htmls/hello_tornado.html",children_infos=(("LiLei","boy"),("HanMM","girl")))if__name__=="__main__":app=tornado.web.Application(handlers=handler_list(),static_path=os.path.join(os.path.dirname(__file__),"htmls"),debug=True)http_server=tornado.httpserver.HTTPServer(app)http_server.listen(8000)tornado.ioloop.IOLoop.instance().start()

文件结构:

├── hello_tornado.py ├── htmls │ ├── bootstrap-3.3.7-dist │ │ ├── css │ │ │ ├── bootstrap.css │ │ │ ├── bootstrap.css.map │ │ │ ├── bootstrap.min.css │ │ │ ├── bootstrap.min.css.map │ │ │ ├── bootstrap-theme.css │ │ │ ├── bootstrap-theme.css.map │ │ │ ├── bootstrap-theme.min.css │ │ │ └── bootstrap-theme.min.css.map │ │ ├── fonts │ │ │ ├── glyphicons-halflings-regular.eot │ │ │ ├── glyphicons-halflings-regular.svg │ │ │ ├── glyphicons-halflings-regular.ttf │ │ │ ├── glyphicons-halflings-regular.woff │ │ │ └── glyphicons-halflings-regular.woff2 │ │ └── js │ │ ├── bootstrap.js │ │ ├── bootstrap.min.js │ │ └── npm.js │ ├── custom_css │ │ ├── ie10-viewport-bug-workaround.css │ │ └── navbar-fixed-top.css │ ├── hello_tornado.html │ ├── jquery └── 1.12.4 └── jquery.min.js

显示如下: