2015年8月17日

Tornado 教學 (4) - 使用靜態資源 ( Use static resources with Tornado Web Framework )

在上一篇中介紹了怎麼在 Tornado 中使用 Template 引擎,但只使用 Template 絕對不夠製作一個好的 Web 應用。因此,本篇文章要介紹如何在 Tornado Web Application 中處理態檔案請求,例如:.css、.js、.png 等等。( 其他 Tornado 相關教學可以參考本篇整理 )



建立靜態資源資料夾
首先在專案內建立靜態資源的資料夾,本範例使用 static/,專案架構參考如下:
├── TornadoSandbox
    ├── index.html
    ├── server.py
    └── static
        ├── css
        ├── img
        └── js
            └── jquery-1.11.3.min.js


設定靜態資源 Handler
我們繼續利用上一篇中的 server.py,內容參考如下:
import os
import tornado.ioloop
import tornado.web

class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        messages = ["One", "Two", "Three", "Four"]
        self.render("index.html", messages=messages)

# 方法一:
# 設定靜態資源路徑與其他參數,之後加入 application 中
settings = {
    "static_path": os.path.join(os.path.dirname(__file__), "static"),
    "autoreload": True
}

if __name__ == "__main__":
    application = tornado.web.Application([
        (r"/", IndexHandler),
        # 方法二:
        # 使用 StaticFileHandler 來處理靜態資源的請求
        #(r"/static/(.*)", tornado.web.StaticFileHandler, \
        #        dict(path=settings['static_path']))
    ], **settings)
    application.listen(8888)
    tornado.ioloop.IOLoop.current().start()
另外,html 檔案沒有什麼太大改變,只需要將靜態資源的檔案加入,內容如下:
<script src="/static/js/jquery-1.11.3.min.js"></script>
基本處理靜態資源請求的設定與方式就介紹到此。


Environment :
  ・ Arch Linux
  ・ Python 2.7

Reference :
  ・ Tornado