4.1 静态文件
现在有一个预先写好的静态页面文件 (下载静态文件资源), 我们来看下如何用 tornado 提供静态文件.
static_path
我们可以通过向 web.Application 类的构造函数传递一个名为 static_path 的参数来告诉 Tornado 从文件系统的一个特定位置提供静态文件, 如:
- App = tornado.Web.Application(
- [(r'/', IndexHandler)],
- static_path=os.path.join(os.path.dirname(__file__), "static"),
- )
在这里, 我们设置了一个当前应用目录下名为 statics 的子目录作为 static_path 的参数. 现在应用将以读取 statics 目录下的 filename.ext 来响应诸如 / static/filename.ext 的请求, 并在响应的主体中返回.
对于静态文件目录的命名, 为了便于部署, 建议使用 static
对于我们提供的静态文件资源, 可以通过 http://127.0.0.1/static/html/index.html 来访问. 而且在 index.HTML 中引用的静态资源文件, 我们给定的路径也符合 / static/... 的格式, 故页面可以正常浏览.
- <link href="/static/plugins/bootstrap/CSS/bootstrap.min.css" rel="stylesheet">
- <link href="/static/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet">
- <link href="/static/css/reset.css" rel="stylesheet">
- <link href="/static/css/main.css" rel="stylesheet">
- <link href="/static/css/index.css" rel="stylesheet">
- <script src="/static/js/jquery.min.js">
- </script>
- <script src="/static/plugins/bootstrap/js/bootstrap.min.js">
- </script>
- <script src="/static/js/index.js">
- </script>
- StaticFileHandler
我们再看刚刚访问页面时使用的路径 http://127.0.0.1/static/html/index.html, 这中 url 显然对用户是不友好的, 访问很不方便. 我们可以通过 tornado.Web.StaticFileHandler 来自由映射静态文件与其访问路径 url.
tornado.Web.StaticFileHandler 是 tornado 预置的用来提供静态资源文件的 handler.
- # -*- coding: utf-8 -*-
- # __auther__ = 'lewen'
- import os
- import tornado.Web
- import tornado.ioloop
- import tornado.httpserver
- from tornado.Web import RequestHandler, url, StaticFileHandler
- from tornado.options import options, define
- define("port", default=8000, type=int, help="run the server on the port")
- class IndexHandler(RequestHandler):
- def get(self, *args, **kwargs):
- pass
- if __name__ == "__main__":
- tornado.options.parse_command_line()
- current_path = os.path.dirname(__file__)
- App = tornado.Web.Application([
- (r'/(.*)', StaticFileHandler,
- {"path": os.path.join(current_path, "static/html"), "default_filename": "index.html"}),
- # (r'^/view/(.*)$', StaticFileHandler, {"path": os.path.join(current_path, "static/html")}),
- ],
- debug=True,
- # static_path=os.path.join(os.path.dirname(__file__), "static"),
- )
- http_server = tornado.httpserver.HTTPServer(App)
- http_server.listen(options.port)
- tornado.ioloop.IOLoop.current().start()
path 用来指明提供静态文件的根路径, 并在此目录中寻找在路由中用正则表达式提取的文件名.
default_filename 用来指定访问路由中未指明文件名时, 默认提供的文件.
现在, 对于静态文件 statics/HTML/index.HTML, 可以通过三种方式进行访问:
- http://127.0.0.1/static/html/index.html
- http://127.0.0.1/
- http://127.0.0.1/view/index.html
statics 静态文件夹跟 http://127.0.0.1:8000/static/html/index.html# 中的 static(默认访问路径) 不一样
访问 http://127.0.0.1:8000/static 时 tornado 会转换去对应的设置文件夹去找
部署时, 将静态文件放到 nginx 上为了方便查找及引用, 改为 static
- App = tornado.Web.Application(
- [(r'/', IndexHandler)],
- static_path=os.path.join(os.path.dirname(__file__), "static"),
- template_path=os.path.join(os.path.dirname(__file__), "template"),
- )
class IndexHandler(RequestHandler): def get(self): self.render("index.html") # 渲染主页模板, 并返回给客户端. current_path = os.path.dirname(__file__) App = tornado.Web.Application( [ (r'^/$', IndexHandler), (r'^/view/(.*)$', StaticFileHandler, {"path":os.path.join(current_path, "statics/html")}), ], static_path=os.path.join(current_path, "statics"), template_path=os.path.join(os.path.dirname(__file__), "templates"), )
<li class="house-item"> <a href=""><img src="/static/images/home01.jpg"></a> <div class="house-desc"> <div class="landlord-pic"><img src="/static/images/landlord01.jpg"></div> <div class="house-price">¥<span>398</span>/ 晚</div> <div class="house-intro"> <span class="house-title">宽窄巷子 + 160 平大空间 + 文化保护区双地铁</span> <em > 整套出租 - 5 分 / 6 点评 - 北京市丰台区六里桥地铁</em> </div> </div> </li>
<li class="house-item"> <a href=""><img src="/static/images/home01.jpg"></a> <div class="house-desc"> <div class="landlord-pic"><img src="/static/images/landlord01.jpg"></div> <div class="house-price">¥<span>{{price}}</span>/ 晚</div> <div class="house-intro"> <span class="house-title">{{title}}</span> <em > 整套出租 - {{score}}分 /{{comments}}点评 - {{position}}</em> </div> </div> </li>
class IndexHandler(RequestHandler): def get(self): house_info = { "price": 398, "title": "宽窄巷子 + 160 平大空间 + 文化保护区双地铁", "score": 5, "comments": 6, "position": "北京市丰台区六里桥地铁" } self.render("index.html", **house_info)
<li class="house-item"> <a href=""><img src="/static/images/home01.jpg"></a> <div class="house-desc"> <div class="landlord-pic"><img src="/static/images/landlord01.jpg"></div> <div class="house-price">¥<span>{{p1 + p2}}</span>/ 晚</div> <div class="house-intro"> <span class="house-title">{{"+".join(titles)}}</span> <em > 整套出租 - {{score}}分 /{{comments}}点评 - {{position}}</em> </div> </div> </li> class IndexHandler(RequestHandler): def get(self): house_info = { "p1": 198, "p2": 200, "titles": ["宽窄巷子", "160 平大空间", "文化保护区双地铁"], "score": 5, "comments": 6, "position": "北京市丰台区六里桥地铁" } self.render("index.html", **house_info)
{ % if ... % } ... { % elif ... % } ... { % else ... % } ... { % end % } { % for ... in ... % } ... { % end % } { % while ... % } ... { % end % }
<ul class="house-list"> {% if len(houses)> 0 %} {% for house in houses %} <li class="house-item"> <a href=""><img src="/static/images/home01.jpg"></a> <div class="house-desc"> <div class="landlord-pic"><img src="/static/images/landlord01.jpg"></div> <div class="house-price">¥<span>{{house["price"]}}</span>/ 晚</div> <div class="house-intro"> <span class="house-title">{{house["title"]}}</span> <em > 整套出租 - {{house["score"]}}分 /{{house["comments"]}}点评 - {{house["position"]}}</em> </div> </div> </li> {% end %} {% else %}
{ % end % } </ul> View Code
class IndexHandler(RequestHandler): def get(self): houses = [ { "price": 398, "title": "宽窄巷子 + 160 平大空间 + 文化保护区双地铁", "score": 5, "comments": 6, "position": "北京市丰台区六里桥地铁" }, { "price": 398, "title": "宽窄巷子 + 160 平大空间 + 文化保护区双地铁", "score": 5, "comments": 6, "position": "北京市丰台区六里桥地铁" }, { "price": 398, "title": "宽窄巷子 + 160 平大空间 + 文化保护区双地铁", "score": 5, "comments": 6, "position": "北京市丰台区六里桥地铁" }, { "price": 398, "title": "宽窄巷子 + 160 平大空间 + 文化保护区双地铁", "score": 5, "comments": 6, "position": "北京市丰台区六里桥地铁" }, { "price": 398, "title": "宽窄巷子 + 160 平大空间 + 文化保护区双地铁", "score": 5, "comments": 6, "position": "北京市丰台区六里桥地铁" }] self.render("index.html", houses=houses) View Code
<!DOCTYPE HTML> <HTML> <head> <title> 新建房源 </title> </head> <body> <form method="post"> <textarea name="text"> </textarea> <input type="submit" value="提交"> </form> {{text}} </body> </HTML>
class NewHandler(RequestHandler): def get(self): self.render("new.html", text="") def post(self): text = self.get_argument("text", "") print text self.render("new.html", text=text)
{ % autoescape None % } escape()
def house_title_join(titles): return "+".join(titles) class IndexHandler(RequestHandler): def get(self): house_list = [ { "price": 398, "titles": ["宽窄巷子", "160 平大空间", "文化保护区双地铁"], "score": 5, "comments": 6, "position": "北京市丰台区六里桥地铁" }, { "price": 398, "titles": ["宽窄巷子", "160 平大空间", "文化保护区双地铁"], "score": 5, "comments": 6, "position": "北京市丰台区六里桥地铁" }] self.render("index.html", houses=house_list, title_join = house_title_join)
<ul class="house-list"> {% if len(houses)> 0 %} {% for house in houses %} <li class="house-item"> <a href=""><img src="/static/images/home01.jpg"></a> <div class="house-desc"> <div class="landlord-pic"><img src="/static/images/landlord01.jpg"></div> <div class="house-price">¥<span>{{house["price"]}}</span>/ 晚</div> <div class="house-intro"> <span class="house-title">{{title_join(house["titles"])}}</span> <em > 整套出租 - {{house["score"]}}分 /{{house["comments"]}}点评 - {{house["position"]}}</em> </div> </div> </li> {% end %} {% else %}
{ % end % } </ul> View Code
<!DOCTYPE HTML> <HTML> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> {% block page_title %}{% end %} <link href="{{static_url('plugins/bootstrap/css/bootstrap.min.css')}}" rel="stylesheet"> <link href="{{static_url('plugins/font-awesome/css/font-awesome.min.css')}}" rel="stylesheet"> <link href="{{static_url('css/reset.css')}}" rel="stylesheet"> <link href="{{static_url('css/main.css')}}" rel="stylesheet"> {% block css_files %}{% end %} </head> <body> <div class="container"> <div class="top-bar"> {% block header %}{% end %} </div> {% block body %}{% end %} <div class="footer"> {% block footer %}{% end %} </div> </div> <script src="{{static_url('js/jquery.min.js')}}"> </script> <script src="{{static_url('plugins/bootstrap/js/bootstrap.min.js')}}"> </script> {% block js_files %}{% end %} </body> </HTML>
{% extends "base.html" %} {% block page_title %} <title > 爱家 - 房源</title> {% end %} {% block css_files %} <link href="{{static_url('css/index.css')}}" rel="stylesheet"> {% end %} {% block js_files %} <script src="{{static_url('js/index.js')}}"></script> {% end %} {% block header %} <div class="nav-bar"> <h3 class="page-title">房 源</h3> </div> {% end %} {% block body %} <ul class="house-list"> {% if len(houses)> 0 %} {% for house in houses %} <li class="house-item"> <a href=""><img src="/static/images/home01.jpg"></a> <div class="house-desc"> <div class="landlord-pic"><img src="/static/images/landlord01.jpg"></div> <div class="house-price">¥<span>{{house["price"]}}</span>/ 晚</div> <div class="house-intro"> <span class="house-title">{{title_join(house["titles"])}}</span> <em > 整套出租 - {{house["score"]}}分 /{{house["comments"]}}点评 - {{house["position"]}}</em> </div> </div> </li> {% end %} {% else %}
{% end %} </ul> {% end %} {% block footer %} <p><span><i class="fa fa-copyright"></i></span > 爱家租房 & nbsp; 享受家的温馨</p> {% end %} View Code
来源: http://www.bubuko.com/infodetail-2946775.html