最近要用python来做一个WEB服务器,找来找去,感觉tornado上手比较简单,这里简单笔记下使用要点。
CONTENTS
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 -*-
import sys
import os
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.template import Template
def handler_list():
return [ (r"/hello_tornado", hello_tornado_handler_main) ,
]
class hello_tornado_handler_main(tornado.web.RequestHandler):
def get(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内容返回即可。
class hello_tornado_handler_main(tornado.web.RequestHandler):
def get(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文件,内容如下:
<!DOCTYPE html>
<html>
<body>hello,{{name1}} and {{name2}}</body>
</html>
python代码为:
class hello_tornado_handler_main(tornado.web.RequestHandler):
def get(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内容:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="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>
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">children table</div>
<table class="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 -*-
import sys
import os
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.template import Template
def handler_list():
return [ (r"/hello_tornado", hello_tornado_handler_main) ,
]
class hello_tornado_handler_main(tornado.web.RequestHandler):
def get(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
显示如下:

发表评论