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> ...
随机推荐
- [Jest] Automate your migration to Jest using codemods
Jest is a fantastic testing library, but maybe you've been putting off the switch because migrating ...
- myEclipse怎样将程序部署到tomcat(附录MyEclipse调试快捷键)
部署 1.选中你要部署的项目,在工具栏找到 Deploy MyEclipse J2EE Project to Server 2.单击Add,即出现例如以下界面.选择对应的Server,要和你在配置to ...
- react 项目实战(一)创建项目 及 服务端搭建
1.安装 React社区提供了众多的脚手架,这里我们使用官方推荐的create-react-app. //安装脚手架 npm install -g create-react-app //生成并运行项目 ...
- 【前端】JavaScript继承实现的四种方式
转载请注明出处:http://www.cnblogs.com/shamoyuu/p/4770235.html 一.继承的实现方法 1.原型链继承 这个继承最为简单,它的实现原理是,每一个AO对象都有一 ...
- (工具类)Linux笔记之终端日志记录工具script
在学习Linux时,有时候终端的打印消息对于我们很重要,可是终端显示也是有一定的缓冲空间的.当信息打印许多时,前面的信息就会被覆盖掉.所以这里网上搜索了一下这方面的介绍.现总结例如以下: script ...
- HFile存储格式
Table of Contents HFile存储格式 Block块结构 HFile存储格式 HFile是參照谷歌的SSTable存储格式进行设计的.全部的数据记录都是通过它来完毕持久化,其内部主要採 ...
- Cocos2d-X开发中国象棋《四》设计游戏场景
设计完開始界面后就要设计游戏界面了 为了理清设计思路先看一张游戏界面效果图 游戏界面设计思路: 1.在窗体上放一张桌子 2.在桌子上放一个棋盘 3.在棋盘右边加入新局button,暂不实现详细的功能 ...
- c# GDI+绘制不同字体的字符串
一段字符串中可能既有汉字又有字母,对于汉字和字母分别采用不同的字体进行绘制直接po代码了 Bitmap bmp = new Bitmap(iWidth, iHeight); Graphics g = ...
- 2015ACM/ICPC Asia Regional Changchun Online /HDU 5438 图
Ponds Time Limit: 1500/1000 MS (Java/Others) Memory Limit: 1310 ...
- dubbo作者讲编码原则
刚看到梁飞谈到dubbo为保证代码质量开发人员必须要注意的,其实也是开发人员应该做的. 1. 防止空指针和下标越界 这是我最不喜欢看到的异常,尤其在核心框架中,我更愿看到信息详细的参数不合法异常, 这 ...