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>
Tornado引入静态css、js文件的更多相关文章
- JQMobile引入外部CSS,JS文件
使用CDN <!DOCTYPE html> <html> <head> <title>html5</title> <meta name ...
- django 静态css js文件配置
参考:http://blog.csdn.net/liqiancao/article/details/66151287
- js活jQuery实现动态添加、移除css/js文件
下面是在项目中用到的,直接封装好的函数,拿去在js中直接调用就可以实现css.js文件的动态引入与删除.代码如下 动态加载,移除,替换css/js文件 // 动态添加css文件 function ad ...
- Django使用本地css/js文件
Django使用本地css/js文件 在manager.py同层级下创建static文件夹, 里面放上css , js, images等文件或者文件夹 我的文件夹层级 然后只需在settings.py ...
- 在桌面右键创建html,css,js文件
1.在开始里面输入regedit,进入注册表编辑器. 2.打开HKEY_CLASSES_ROOT项. 3.打开.html/.css/.js项. 4.右键新建项,起名ShellNew. 5.新建字符串值 ...
- jsp 引用css/js文件返回html网页问题
我的问题: 我直接在web.xml中匹配了 “/” ,以为能默认使用 “localhost:8080/news/” 这种方式,直接进入首页. 但是这样会匹配所有url 因此请求的 ***.js/*** ...
- 同一页面引入多个JS文件的编码问题
原来只是觉得IE解析HTML文件的时候,需要知道其传输编码,才能正确处理,而从来没有在意过JavaScript文件的编码问题.结果今天发现同一页面中的多个JavaScript文件如果保存编码不同,也会 ...
- flask-bootstrap 模版中所需的CSS/JS文件实现本地引入
Flask-Bootstrap默认是加载CDN的css与js文件,每次刷新页面都要访问到外网的cdn来获取css与js文件; 模版扩展来自于bootstrap/base.html,就以bootstra ...
- springMVC 引入静态资源Js的方式
前两天项目出现了Js无法引入的情况,本篇博客先总结分析+批判自己犯的低级错,再说说几种访问静态资源的方式! 首先,由于在web.xml里面的servlet拦截匹配为<url-pattern> ...
随机推荐
- NYOJ 题目42 一笔画问题(欧拉图)
一笔画问题 时间限制:3000 ms | 内存限制:65535 KB 难度:4 描写叙述 zyc从小就比較喜欢玩一些小游戏.当中就包含画一笔画.他想请你帮他写一个程序.推断一个图是否可以用一笔画下 ...
- Apple Swift编程语言新手教程
文件夹 1 简单介绍 2 Swift入门 3 简单值 4 控制流 5 函数与闭包 6 对象与类 7 枚举与结构 1 简单介绍 今天凌晨Apple刚刚公布了Swift编程 ...
- 制作NGUI动态字体
在ngui中有两种制做字体的方式.一种是bmfont等工具制作字体图集的方法,这样的方法呢是动态的.生成的图集有多个字就是多少个字,要多加一 个字要又一次用工具做一次,非常是麻烦. 而汉字有太多,我们 ...
- field load respone data
问题: AJAX 使用谷歌浏览器 POST 请求报如下错误 field load respone data 使用 火狐 浏览器就正常 调试1: 发现其实我请求的回调函数能打印出来数据,但是,在netw ...
- MySQL-插入数据(INSERT)
Insert语句可将一行或多行插入到表中. INSERT语法: INSERT INTO table(column1,column2...) VALUES (value1,value2,...); 首先 ...
- HDU 4850 Wow! Such String!
链接:http://acm.hdu.edu.cn/showproblem.php?pid=4850 题意:给定一个N(1 ≤ N ≤ 500000),构造一个长度为N的小写字母字符串,要求所有长度大于 ...
- BZOJ_1692_[Usaco2007 Dec]队列变换_后缀数组
BZOJ_1692_[Usaco2007 Dec]队列变换_后缀数组 Description FJ打算带他的N(1 <= N <= 30,000)头奶牛去参加一年一度的“全美农场主大奖赛” ...
- 【POJ 1330】 Nearest Common Ancestors
[题目链接] 点击打开链接 [算法] 倍增法求最近公共祖先 [代码] #include <algorithm> #include <bitset> #include <c ...
- 洛谷P1719 最大加权矩形
题目描述 为了更好的备战NOIP2013,电脑组的几个女孩子LYQ,ZSC,ZHQ认为,我们不光需要机房,我们还需要运动,于是就决定找校长申请一块电脑组的课余运动场地,听说她们都是电脑组的高手,校长没 ...
- gitlab调试
Bundle complete! 104 Gemfile dependencies, 161 gems now installed.Gems in the groups development, te ...