现在有一个预先写好的静态页面文件 (下载静态文件资源), 我们来看下如何用tornado提供静态文件。
static_path我们可以通过向web.Application类的构造函数传递一个名为static_path
的参数来告诉Tornado从文件系统的一个特定位置提供静态文件,如:
app = tornado.web.Application(
[(r'/', IndexHandler)],
static_path=os.path.join(os.path.dirname(__file__), "statics"),
)
在这里,我们设置了一个当前应用目录下名为statics的子目录作为static_path的参数。现在应用将以读取statics目录下的filename.ext来响应诸如/static/filename.ext的请求,并在响应的主体中返回。
对于静态文件目录的命名,为了便于部署,建议使用static。
对于我们提供的静态文件资源,可以通过http://127.0.0.1/static/html/index.html来访问。而且在index.html中引用的静态资源文件,我们给定的路径也符合/static/…的格式,故页面可以正常浏览。
StaticFileHandler
我们再看刚刚访问页面时使用的路径http://127.0.0.1/static/html/index.html,这中url显然对用户是不友好的,访问很不方便。我们可以通过tornado.web.StaticFileHandler来自由映射静态文件与其访问路径url。
tornado.web.StaticFileHandler是tornado预置的用来提供静态资源文件的handler。
import os
current_path = os.path.dirname(__file__)
app = tornado.web.Application(
[
(r'^/()$', StaticFileHandler, {"path":os.path.join(current_path, "statics/html"), "default_filename":"index.html"}),
(r'^/view/(.*)$', StaticFileHandler, {"path":os.path.join(current_path, "statics/html")}),
],
static_path=os.path.join(current_path, "statics"),
)
- 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