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> ...
随机推荐
- springboot整体介绍
1.springboot:快速开发,强大的运维能力.(监控,服务发现,并打) 2.微服务,将一个大系统分解成很多独立的小服务,这些服务能随时发布. 3.2004年第一版spring 1.0,rod j ...
- CF # 369 D2 D、E
D,只要抓住每个点只有一个出度,那么图就能分成几个部分,而且可以发现,一个部分最多一个环. #include <iostream> #include <cstdio> #inc ...
- Linux学习系列之MySQL备份
MySQL排除表备份 #!/bin/bash #created by 90root #date: 20160809 date_y=$(date +%Y) date_m=$(date +%m) time ...
- 【转】Golang 关于通道 Chan 详解
原文:http://blog.csdn.net/netdxy/article/details/54564436 在用 chan 类型时,发生死锁的错误,表面上看不出什么问题 ------------- ...
- UVa 1531 - Problem Bee
题目:如图所看到的的蜂巢型的图中.蜜蜂想从A点飞到B点,假设A与B不在同一个正六边形中, 则它先飞到A的中心.每次飞到相邻格子的中心,最后飞到B的中心,再飞到B点: 假设在一个格子中.直接飞过去就可以 ...
- Python全栈
Python基础 Python基础01 Hello World! Python基础02 基本数据类型 Python基础03 序列 Python基础04 运算 Python基础05 缩进和选择 Pyth ...
- MySQL系列:innodb源代码分析之内存管理
在innodb中实现了自己的内存池系统和内存堆分配系统,在innodb的内存管理系统中,大致分为三个部分:基础的内存块分配管理.内存伙伴分配器和内存堆分配器.innodb定义和实现内存池的主要目的是提 ...
- 20160225.CCPP体系具体解释(0035天)
程序片段(01):CircleList.h+CircleList.c+main.c 内容概要:环形链表 ///CircleList.h #pragma once #include <stdio. ...
- linux redis tmp redis 安装
Redis https://redis.io/download yum install make gcc gcc-c++ openssl-devel zlib-devel -y; wget tar - ...
- 【LIS】Luogu P1020 导弹拦截
昨天晚上看蓝书,看到了LIS问题的优化解法. 是比O(n方)更快的解法,实际上是一个常数优化. 先讲一下朴素的解法: 一个集合a,a[i]是第i个元素.设dp[i]为以编号为i的元素结尾的最长不上升子 ...