天天看點

10 Tornado - 靜态檔案

現在有一個預先寫好的靜态頁面檔案 (下載下傳靜态檔案資源), 我們來看下如何用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/…的格式,故頁面可以正常浏覽。

<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

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 用來指定通路路由中未指明檔案名時,預設提供的檔案。
  • http://127.0.0.1/static/html/index.html
  • http://127.0.0.1/
  • http://127.0.0.1/view/index.html

繼續閱讀