一、静态路径

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

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

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

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

这样就设置了静态路径。

  1. #! /usr/bin/env python
  2. #-*- coding:utf-8 -*-
  3.  
  4. import os.path
  5. import tornado.httpserver
  6. import tornado.ioloop
  7. import tornado.web
  8. import tornado.options
  9.  
  10. from tornado.options import define, options
  11. define("port", default=8000, help="run on the given port", type=int)
  12.  
  13. class IndexHandler(tornado.web.RequestHandler):
  14. def get(self):
  15. lst = ["python","www.itdiffer.com","qiwsir@gmail.com"]
  16. self.render("index.html", info=lst)
  17.  
  18. handlers = [(r"/", IndexHandler),]
  19.  
  20. template_path = os.path.join(os.path.dirname(__file__), "temploop")
  21. static_path = os.path.join(os.paht.dirname(__file__), "static") #这里增加设置了静态路径
  22.  
  23. if __name__ == "__main__":
  24. tornado.options.parse_command_line()
  25. app = tornado.web.Application(handlers, template_path, static_path, debug=True) #这里也多了点
  26. http_server = tornado.httpserver.HTTPServer(app)
  27. http_server.listen(options.port)
  28. tornado.ioloop.IOLoop.instance().start()

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

  1. #!/usr/bin/python
  2. #coding: utf8
  3. import RPi.GPIO as GPIO
  4. import time
  5. import sys
  6. import threading
  7. import tornado.ioloop
  8. import tornado.web
  9. import tornado.httpserver
  10. import tornado.options
  11. import json
  12. import os.path
  13. import subprocess
  14.  
  15. tornado.options.define("port",default=8003,type=int)
  16.  
  17. IN1 = 11
  18. IN2 = 12
  19. IN3 = 16
  20. IN4 = 18
  21.  
  22. stop_status = 0
  23. last_key = ""
  24. last_request_time = 0
  25.  
  26. def init():
  27. GPIO.setmode(GPIO.BOARD)
  28. GPIO.setup(IN1,GPIO.OUT)
  29. GPIO.setup(IN2,GPIO.OUT)
  30. GPIO.setup(IN3,GPIO.OUT)
  31. GPIO.setup(IN4,GPIO.OUT)
  32.  
  33. # 前进
  34. def forward():
  35. global stop_status
  36. GPIO.output(IN1,GPIO.HIGH)
  37. GPIO.output(IN2,GPIO.LOW)
  38. GPIO.output(IN3,GPIO.HIGH)
  39. GPIO.output(IN4,GPIO.LOW)
  40. # print "forward"
  41. # time.sleep(0.1)
  42.  
  43. # 后退
  44. def reverse():
  45. global stop_status
  46. GPIO.output(IN1,GPIO.LOW)
  47. GPIO.output(IN2,GPIO.HIGH)
  48. GPIO.output(IN3,GPIO.LOW)
  49. GPIO.output(IN4,GPIO.HIGH)
  50.  
  51. # 左转弯
  52. def left():
  53. global stop_status
  54. GPIO.output(IN1,GPIO.LOW)
  55.  
  56. # 右转弯
  57. def right():
  58. global stop_status
  59. GPIO.output(IN1,GPIO.HIGH)
  60.  
  61. #停止
  62. def stop_car():
  63. GPIO.output(IN1,False)
  64. GPIO.output(IN2,False)
  65. GPIO.output(IN3,False)
  66. GPIO.output(IN4,False)
  67. global stop_status
  68. stop_status = 1
  69.  
  70. #关闭GPIO接口
  71. def close_car():
  72. global stop_status
  73. stop_status = 1
  74. GPIO.cleanup()
  75.  
  76. class IndexHandler(tornado.web.RequestHandler):
  77. def set_default_headers(self):
  78. self.set_header('Access-Control-Allow-Origin', '*')
  79. self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
  80. self.set_header('Access-Control-Allow-Headers', '*')
  81. def get(self):
  82. self.render("iat.html")
  83. def post(self):
  84. global stop_status
  85. global last_key
  86. global last_request_time
  87. old_request_time = last_request_time
  88. init()
  89. sleep_time = 10
  90. try:
  91. arg = self.get_argument('k')
  92. new_request_time = self.get_argument('time')
  93. print 'get last time',new_request_time
  94. except Exception, e:
  95. arg = json.loads(self.request.body)['k']
  96. new_request_time = json.loads(self.request.body)['time']
  97. print 'json last time', new_request_time
  98.  
  99. print "==new time ==", new_request_time
  100. print "==old time ==", old_request_time
  101. if(arg=='g' and last_key!='g' and new_request_time >= old_request_time):
  102. print "WARNING_ON"
  103. stop_status = 0
  104. pname = ("/root/data/smoke/warning")
  105. result = subprocess.Popen(pname,stdin=subprocess.PIPE,stdout=subprocess.PIPE)
  106. last_key = 'g'
  107. elif(arg=='n' and last_key!='n' and new_request_time >= old_request_time):
  108. print "WARNING_OFF"
  109. stop_status = 0
  110. qname = ("/root/data/smoke/cpwm")
  111. rresult = subprocess.Popen(qname,stdin=subprocess.PIPE,stdout=subprocess.PIPE)
  112. last_key = 'n'
  113. rresult.kill()
  114. elif(arg=='t' and last_key!='t' and new_request_time >= old_request_time):
  115. print "LIGHT_ON"
  116. stop_status = 0
  117. autoThread = threading.Thread(target = right)
  118. autoThread.start()
  119. last_key = 't'
  120. elif(arg=='h' and last_key!='h' and new_request_time >= old_request_time):
  121. print "LIGHT_OFF"
  122. stop_status = 0
  123. autoThread = threading.Thread(target = left)
  124. autoThread.start()
  125. last_key = 'h'
  126. elif(arg=='r' and last_key!='r' and new_request_time >= old_request_time):
  127. print "WATER_ON"
  128. stop_status = 0
  129. execfile('/root/data/mada/water.py')
  130. last_key = 'r'
  131. elif(arg=='e' and last_key!='e' and new_request_time >= old_request_time):
  132. print "WATER_OFF"
  133. stop_status = 0
  134. execfile('/root/data/mada/close.py')
  135. last_key = 'e'
  136. elif(arg=='stop' and new_request_time >= old_request_time):
  137. print "stop"
  138. last_key = "stop"
  139. time.sleep(0.3)
  140. stop_status = 1
  141. else:
  142. print "error"
  143. last_request_time = new_request_time
  144. self.write(arg)
  145. def options(self):
  146. pass
  147. if __name__ == '__main__':
  148. tornado.options.parse_command_line()
  149. app = tornado.web.Application(handlers=[(r"/",IndexHandler)],
  150. template_path=os.path.join(os.path.dirname(__file__),"templates"),
  151. static_path=os.path.join(os.path.dirname(__file__),"static"),
  152. debug=True)
  153. http_server = tornado.httpserver.HTTPServer(app)
  154. http_server.listen(tornado.options.options.port)
  155. tornado.ioloop.IOLoop.instance().start()

二、编写模版文件

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

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

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

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

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

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

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

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0">
  5. <meta http-equiv="Content-Type" content="text/html; charset=utf8" />
  6. <title>花园Mini</title>
  7. <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" />
  8. <meta name="description" content="Get free mobile website templates for Iphone , Android and High end touch mobile devices" />
  9. <link href="{{static_url("css/style.css")}}" rel="stylesheet" type="text/css" />
  10. <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
  11. </head>
  12.  
  13. <body>
  14. <div id="header">
  15. <div class="nav">
  16. <ul>
  17. <li><a href="#">花园Mini</a></li>
  18. </ul>
  19. </div>
  20. <div class="logo"></div>
  21. </div>
  22. <div class="clear"></div>
  23. <h2 id='iat_result'>请输入语音指令</h2>
  24. <ul class="helper">
  25. <li>请确认麦克风可以正常使用</li>
  26. <li>请保持网络接入畅通、稳定</li>
  27. <li>在安静环境下使用效果更佳</li>
  28. </ul>
  29.  
  30. <div style="position:relative">
  31.  
  32. <div id='a'>点击开始录音</div>
  33. <div id="canvas_wrapper" style="display:none">
  34. <div style="display: inline"></div>
  35. <canvas id="volume" height="4"></canvas>
  36. </div>
  37. </div>
  38. <script>
  39. onerror=function(a,b,c){
  40. alert(a+b+c);
  41. }
  42. </script>
  43. <script type="text/javascript" src="{{static_url("js/fingerprint2.min.js")}}"></script>
  44. <script type="text/javascript" src="{{static_url("js/iat.all.js")}}"></script>
  45. <script type="text/javascript" src="{{static_url("js/demo.js")}}"></script>
  46. <script>
  47. function go(k){
  48. var requestTime= new Date().getTime();
  49. $.post('/',{k:k,time:requestTime},function(){},"json");
  50. }
  51. var tValue=document.getElementById("iat_result").innerHTML;
  52. setInterval(function(event){
  53. if(tValue !=document.getElementById("iat_result").innerHTML){
  54.  
  55. //这里写自己的业务逻辑代码
  56. tValue =document.getElementById("iat_result").innerHTML;
  57. // alert(tValue);
  58. if (tValue == "开启报警装置" || tValue == "开启报警装置。") {
  59. go('g');
  60. // alert("I am here");
  61. } else if (tValue == "关闭报警装置" || tValue == "关闭报警装置。") {
  62. go('n');
  63. } else if (tValue == "开启照明装置" || tValue == "开启照明装置。") {
  64. go('t');
  65. } else if (tValue == "关闭照明装置" || tValue == "关闭照明装置。") {
  66. go('h');
  67. } else if (tValue == "开启浇灌装置" || tValue == "开启浇灌装置。") {
  68. go('r');
  69. } else if (tValue == "关闭浇灌装置" || tValue == "关闭浇灌装置。") {
  70. go('e');
  71. } else if (tValue == "关闭交换装置" || tValue == "关闭交换装置。") {
  72. go('e');
  73. }
  74. }
  75. },100);
  76.  
  77. </script>
  78. </body>
  79. </html>

Tornado引入静态css、js文件的更多相关文章

  1. JQMobile引入外部CSS,JS文件

    使用CDN <!DOCTYPE html> <html> <head> <title>html5</title> <meta name ...

  2. django 静态css js文件配置

    参考:http://blog.csdn.net/liqiancao/article/details/66151287

  3. js活jQuery实现动态添加、移除css/js文件

    下面是在项目中用到的,直接封装好的函数,拿去在js中直接调用就可以实现css.js文件的动态引入与删除.代码如下 动态加载,移除,替换css/js文件 // 动态添加css文件 function ad ...

  4. Django使用本地css/js文件

    Django使用本地css/js文件 在manager.py同层级下创建static文件夹, 里面放上css , js, images等文件或者文件夹 我的文件夹层级 然后只需在settings.py ...

  5. 在桌面右键创建html,css,js文件

    1.在开始里面输入regedit,进入注册表编辑器. 2.打开HKEY_CLASSES_ROOT项. 3.打开.html/.css/.js项. 4.右键新建项,起名ShellNew. 5.新建字符串值 ...

  6. jsp 引用css/js文件返回html网页问题

    我的问题: 我直接在web.xml中匹配了 “/” ,以为能默认使用 “localhost:8080/news/” 这种方式,直接进入首页. 但是这样会匹配所有url 因此请求的 ***.js/*** ...

  7. 同一页面引入多个JS文件的编码问题

    原来只是觉得IE解析HTML文件的时候,需要知道其传输编码,才能正确处理,而从来没有在意过JavaScript文件的编码问题.结果今天发现同一页面中的多个JavaScript文件如果保存编码不同,也会 ...

  8. flask-bootstrap 模版中所需的CSS/JS文件实现本地引入

    Flask-Bootstrap默认是加载CDN的css与js文件,每次刷新页面都要访问到外网的cdn来获取css与js文件; 模版扩展来自于bootstrap/base.html,就以bootstra ...

  9. springMVC 引入静态资源Js的方式

    前两天项目出现了Js无法引入的情况,本篇博客先总结分析+批判自己犯的低级错,再说说几种访问静态资源的方式! 首先,由于在web.xml里面的servlet拦截匹配为<url-pattern> ...

随机推荐

  1. [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 ...

  2. myEclipse怎样将程序部署到tomcat(附录MyEclipse调试快捷键)

    部署 1.选中你要部署的项目,在工具栏找到 Deploy MyEclipse J2EE Project to Server 2.单击Add,即出现例如以下界面.选择对应的Server,要和你在配置to ...

  3. react 项目实战(一)创建项目 及 服务端搭建

    1.安装 React社区提供了众多的脚手架,这里我们使用官方推荐的create-react-app. //安装脚手架 npm install -g create-react-app //生成并运行项目 ...

  4. 【前端】JavaScript继承实现的四种方式

    转载请注明出处:http://www.cnblogs.com/shamoyuu/p/4770235.html 一.继承的实现方法 1.原型链继承 这个继承最为简单,它的实现原理是,每一个AO对象都有一 ...

  5. (工具类)Linux笔记之终端日志记录工具script

    在学习Linux时,有时候终端的打印消息对于我们很重要,可是终端显示也是有一定的缓冲空间的.当信息打印许多时,前面的信息就会被覆盖掉.所以这里网上搜索了一下这方面的介绍.现总结例如以下: script ...

  6. HFile存储格式

    Table of Contents HFile存储格式 Block块结构 HFile存储格式 HFile是參照谷歌的SSTable存储格式进行设计的.全部的数据记录都是通过它来完毕持久化,其内部主要採 ...

  7. Cocos2d-X开发中国象棋《四》设计游戏场景

    设计完開始界面后就要设计游戏界面了 为了理清设计思路先看一张游戏界面效果图 游戏界面设计思路: 1.在窗体上放一张桌子 2.在桌子上放一个棋盘 3.在棋盘右边加入新局button,暂不实现详细的功能 ...

  8. c# GDI+绘制不同字体的字符串

    一段字符串中可能既有汉字又有字母,对于汉字和字母分别采用不同的字体进行绘制直接po代码了 Bitmap bmp = new Bitmap(iWidth, iHeight); Graphics g = ...

  9. 2015ACM/ICPC Asia Regional Changchun Online /HDU 5438 图

    Ponds                                   Time Limit: 1500/1000 MS (Java/Others)    Memory Limit: 1310 ...

  10. dubbo作者讲编码原则

    刚看到梁飞谈到dubbo为保证代码质量开发人员必须要注意的,其实也是开发人员应该做的. 1. 防止空指针和下标越界 这是我最不喜欢看到的异常,尤其在核心框架中,我更愿看到信息详细的参数不合法异常, 这 ...