[Bottle] static_file 說明

BottlePy : Python Web Framework 眾所皆知是一個輕量化的框架,非常適合拿來練功.

在現在的網頁框架中,動態路由(dynamic-routes) 是基本的功能,而Bottle dynamic-routes也透過了Python decorator實作

而有些靜態檔案,例如 js / css / image等檔案,又是怎麼處理的呢?

BottlePy提供了static_file的功能

靜態檔案的部分.原廠有兩個地方說明....

1. http://bottlepy.org/docs/dev/tutorial.html#tutorial-static-files

2. http://bottlepy.org/docs/dev/tutorial.html#static-files

很簡短扼要,不過我也是摸索了一下才搞懂>_<

先看一下,我的設定

@route("/static/<filename:path>")
def serve_static(filename):
    return static_file( filename, root = os.path.join(os.path.dirname(__file__),'static'))

這邊我先逐航解釋一下

@route("/static/<filename:path>")

<filename:path> : 這是BottlePy的Wildcard filters,所以filename是變數來承接符合 :path 這個規則的內容

 瀏覽http://web.site/static/path/file 時,就會套用這個route規則,所以filename = "path/file"

def server_static(filename): 記住這時候filename內容,等同於瀏覽網址/static/目錄後面的字串

然後透過原廠的static_file函式,去取得真正的檔案內容 static_file( filename , root = static所在的目錄 (包含static) )

以下是我測試出來,有些可行,但有情境會失效(error 404)

@route("/static/<path>/<filename>") 這樣的設定.如果是 /static/file 會吐404,也就是path match不到

@route("/static/<filename>") 當你static內還有一層目錄,例如bootstrap就有css,js,fonts目錄,會找不到目標檔案,而產生404錯誤

希望有幫助到大家.