Tornado引入静态css、js文件

一、静态路径

template_path=os.path.join(os.path.dirname(__file__), "templates")

 这里是设置了模板的路径,放置模板的目录名称是 templates 。类似的方法,我们也可以设置好静态文件的路径。

static_path=os.path.join(os.path.dirname(__file__), "static")

这里的设置,就是将所有的静态文件,放在了 static 目录中。

这样就设置了静态路径。

#! /usr/bin/env python
#-*- coding:utf-8 -*-

import os.path
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.options

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):
		lst = ["python","www.itdiffer.com","qiwsir@gmail.com"]
		self.render("index.html", info=lst)

handlers = [(r"/", IndexHandler),]

template_path = os.path.join(os.path.dirname(__file__), "temploop")
static_path = os.path.join(os.paht.dirname(__file__), "static")	#这里增加设置了静态路径

if __name__ == "__main__":
	tornado.options.parse_command_line()
	app = tornado.web.Application(handlers, template_path, static_path, debug=True)   #这里也多了点
	http_server = tornado.httpserver.HTTPServer(app)
	http_server.listen(options.port)
	tornado.ioloop.IOLoop.instance().start()

   一处是定义了静态文件路径 static_path ,在这里将存储静态文件的目录命名为 static 。另外一个修改就是在实例化 tornado.web.Application() 的时候,在参数中,出了有静态路径参数 static_path ,还有一个参数设置 debug=True ,这个参数设置的含义是当前的tornado服务器可以不用重启,就能够体现已经修改的代码功能。回想一下,在前面进行调试的时候,是不是每次如果修改了代码,就得重启tornado服务器,才能看到修改效果。用了这个参数就不用这么麻烦了。

#!/usr/bin/python
#coding: utf8
import RPi.GPIO as GPIO
import time
import sys
import threading
import tornado.ioloop
import tornado.web
import tornado.httpserver
import tornado.options
import json
import os.path
import subprocess
 
tornado.options.define("port",default=8003,type=int)
 
IN1 = 11
IN2 = 12
IN3 = 16
IN4 = 18
 
 
stop_status = 0
last_key = ""
last_request_time = 0
 
 
def init():
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(IN1,GPIO.OUT)
    GPIO.setup(IN2,GPIO.OUT)
    GPIO.setup(IN3,GPIO.OUT)
    GPIO.setup(IN4,GPIO.OUT)
 
# 前进
def forward():
    global stop_status
    GPIO.output(IN1,GPIO.HIGH)
    GPIO.output(IN2,GPIO.LOW)
    GPIO.output(IN3,GPIO.HIGH)
    GPIO.output(IN4,GPIO.LOW)
    # print "forward"
    # time.sleep(0.1)
 
# 后退
def reverse():
    global stop_status
    GPIO.output(IN1,GPIO.LOW)
    GPIO.output(IN2,GPIO.HIGH)
    GPIO.output(IN3,GPIO.LOW)
    GPIO.output(IN4,GPIO.HIGH)
 
 
# 左转弯
def left():
    global stop_status
    GPIO.output(IN1,GPIO.LOW)
 
 
# 右转弯
def right():
    global stop_status
    GPIO.output(IN1,GPIO.HIGH)
 
#停止
def stop_car():
    GPIO.output(IN1,False)
    GPIO.output(IN2,False)
    GPIO.output(IN3,False)
    GPIO.output(IN4,False)
    global stop_status
    stop_status = 1
 
#关闭GPIO接口
def close_car():
    global stop_status
    stop_status = 1
    GPIO.cleanup()

class IndexHandler(tornado.web.RequestHandler):
    def set_default_headers(self):
        self.set_header('Access-Control-Allow-Origin', '*')
        self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
        self.set_header('Access-Control-Allow-Headers', '*')
    def get(self):
        self.render("iat.html")
    def post(self):
        global stop_status
        global last_key
        global last_request_time
        old_request_time = last_request_time
        init()
        sleep_time = 10
        try:
            arg = self.get_argument('k')
            new_request_time = self.get_argument('time')
            print 'get last time',new_request_time
        except Exception, e:
            arg = json.loads(self.request.body)['k']
            new_request_time = json.loads(self.request.body)['time']
            print 'json last time', new_request_time
 
        print "==new time ==", new_request_time
        print "==old time ==", old_request_time
        if(arg=='g' and last_key!='g' and new_request_time >= old_request_time):
            print "WARNING_ON"
            stop_status = 0
	    pname = ("/root/data/smoke/warning")
	    result = subprocess.Popen(pname,stdin=subprocess.PIPE,stdout=subprocess.PIPE)
            last_key = 'g'
        elif(arg=='n' and last_key!='n' and new_request_time >= old_request_time):
            print "WARNING_OFF"
            stop_status = 0
	    qname = ("/root/data/smoke/cpwm")
            rresult = subprocess.Popen(qname,stdin=subprocess.PIPE,stdout=subprocess.PIPE)
            last_key = 'n'
	    rresult.kill()
        elif(arg=='t' and last_key!='t' and new_request_time >= old_request_time):
            print "LIGHT_ON"
            stop_status = 0
            autoThread = threading.Thread(target = right)
            autoThread.start()
            last_key = 't'
        elif(arg=='h' and last_key!='h' and new_request_time >= old_request_time):
            print "LIGHT_OFF"
            stop_status = 0
            autoThread = threading.Thread(target = left)
            autoThread.start()
            last_key = 'h'
	elif(arg=='r' and last_key!='r' and new_request_time >= old_request_time):
	    print "WATER_ON"
	    stop_status = 0
	    execfile('/root/data/mada/water.py')
	    last_key = 'r'
	elif(arg=='e' and last_key!='e' and new_request_time >= old_request_time):
	    print "WATER_OFF"
	    stop_status = 0
	    execfile('/root/data/mada/close.py')
	    last_key = 'e'
        elif(arg=='stop' and new_request_time >= old_request_time):
            print "stop"
            last_key = "stop"
            time.sleep(0.3)
            stop_status = 1
        else:
            print "error"
        last_request_time = new_request_time
        self.write(arg)
    def options(self):
            pass
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(tornado.options.options.port)
    tornado.ioloop.IOLoop.instance().start()

二、编写模版文件

我们设置静态路径的目的就是要在模板中引入css和js等类型的文件以及图片等等。那么如何引入呢,下面以css为例说明。

<link href="/static/style.css" rel="stylesheet">

但是,这里往往会有一个不方便的地方,如果我手闲着无聊,或者因为别的充足理由,将存储静态文件的目录static换成了sta,并且假设我已经在好几个模板中都已经写了上面的代码。接下来我就要把这些文件全打开,一个一个更改 <link> 里面的地址。

请牢记,凡是遇到重复的事情,一定要找一个函数方法解决。tornado就提供了这么一个: static_url() ,把上面的代码写成:

<link href="{{ static_url("style.css") }}" rel="stylesheet" >

这样,就不管你如何修改静态路径,模板中的设置可以不用变。

按照这个引入再修改相应的模板文件。

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0">
    <meta http-equiv="Content-Type" content="text/html; charset=utf8" />
    <title>花园Mini</title>
    <meta name="keywords" content="free mobile website templates, free mobile website template, free iphone template, free android template, free high end touch mobile templates, free high end touch mobile template" />
    <meta name="description" content="Get free mobile website templates for Iphone , Android and High end touch mobile devices" />
    <link href="{{static_url("css/style.css")}}" rel="stylesheet" type="text/css" />
    <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
</head>

<body>
	<div id="header">
        <div class="nav">
        	<ul>
                <li><a href="#">花园Mini</a></li>
            </ul>
        </div>
        <div class="logo"></div>
    </div>
    <div class="clear"></div>
    <h2 id='iat_result'>请输入语音指令</h2>
    <ul class="helper">
        <li>请确认麦克风可以正常使用</li>
        <li>请保持网络接入畅通、稳定</li>
        <li>在安静环境下使用效果更佳</li>
    </ul>

	<div style="position:relative">

		<div id='a'>点击开始录音</div>
        <div id="canvas_wrapper" style="display:none">
            <div style="display: inline">♠</div>
            <canvas id="volume" height="4"></canvas>
        </div>
	</div>
    <script>
        onerror=function(a,b,c){
            alert(a+b+c);
        }
    </script>
	<script type="text/javascript" src="{{static_url("js/fingerprint2.min.js")}}"></script>
	<script type="text/javascript" src="{{static_url("js/iat.all.js")}}"></script>
	<script type="text/javascript" src="{{static_url("js/demo.js")}}"></script>
<script>
        function go(k){
                var requestTime= new Date().getTime();
                $.post('/',{k:k,time:requestTime},function(){},"json");
        }
        var tValue=document.getElementById("iat_result").innerHTML;
 setInterval(function(event){
       if(tValue !=document.getElementById("iat_result").innerHTML){

         //这里写自己的业务逻辑代码
         tValue =document.getElementById("iat_result").innerHTML;
         // alert(tValue);
         if (tValue == "开启报警装置" || tValue == "开启报警装置。") {
            go('g');
	    // alert("I am here");
         } else if (tValue == "关闭报警装置" || tValue == "关闭报警装置。") {
            go('n');
         } else if (tValue == "开启照明装置" || tValue == "开启照明装置。") {
            go('t');
         } else if (tValue == "关闭照明装置" || tValue == "关闭照明装置。") {
            go('h');
         } else if (tValue == "开启浇灌装置" || tValue == "开启浇灌装置。") {
            go('r');
         } else if (tValue == "关闭浇灌装置" || tValue == "关闭浇灌装置。") {
            go('e');
         } else if (tValue == "关闭交换装置" || tValue == "关闭交换装置。") {
            go('e');
	 } 
       }
  },100);
        

        

    </script>
</body>
</html>
原文地址:https://www.cnblogs.com/sirius-swu/p/6830985.html