在《Tornado - 基于Python的Web服务器框架》讲到一个性能很不错的python的web服务器框架tornado,现在就使用它在树莓派开发板上搭建一个简单地监控开发板状态网站。
这里先给出这个小项目的文件目录总体结构:
hardware文件夹是对开发板进行操作的硬件层
static是项目中用到的静态文件,如这里用到了bootstrap和echarts框架等
templates是html模板页,用于编写页面
项目根目录下的index.py是对应于templates/index.html文件的脚本,用于执行动态操作。
-----------------------------------------------------------------------------------------------------------------------------
1. 项目开始,先建立index.py文件和相关目录文件:
index.py文件内容如下:
#!/usr/bin/env python
# coding=utf-8
import os.path
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from hardware import board_ctrl
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', cpu_temperature="%s°C" % board_ctrl.get_cpu_temp())
def post(self):
board_ctrl.init_gpio()
arg = self.get_argument('k')
if (arg == 'w'):
print 'press w'
if (arg == 'o'):
board_ctrl.open_light()
self.write(arg)
if (arg == 'c'):
board_ctrl.close_light()
self.write(arg)
if (arg == 't'):
board_ctrl.get_cpu_temperature()
self.write(arg)
if (arg == 'p'):
self.write(str(board_ctrl.get_cpu_temp()))
if __name__ == "__main__":
tornado.options.parse_command_line()
app = tornado.web.Application(
handlers=[(r'/', IndexHandler)],
template_path=os.path.join(os.path.dirname(__file__), "templates"),
static_path=os.path.join(os.path.dirname(__file__), "static"),
debug=True
)
http_server = tornado.httpserver.HTTPServer(app)
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start(