Flask – 靜態檔案



Web 應用程式通常需要靜態檔案,例如支援網頁顯示的 javascript 檔案或 CSS 檔案。Web 伺服器通常配置為你提供服務,但在開發過程中,這些檔案會從包中的 static 資料夾提供,或從模組旁邊提供,且應用程式的 /static 地址將可用。

一個特殊的端點 ‘static’ 用於生成靜態檔案的 URL。

在以下示例中,OnClick 事件中呼叫的 javascript 函式定義在 hello.js 中,而 HTML 按鈕在 index.html 中呈現,它在 Flask 應用程式的 ‘/’ URL 上呈現。

from flask import Flask, render_template
app = Flask(__name__)

@app.route("/")
def index():
   return render_template("index.html")

if __name__ == '__main__':
   app.run(debug = True)

index.html 的 HTML 指令碼如下所示。

<html>
   <head>
      <script type = "text/javascript" 
         src = "{{ url_for('static', filename = 'hello.js') }}" ></script>
   </head>
   
   <body>
      <input type = "button" onclick = "sayHello()" value = "Say Hello" />
   </body>
</html>

hello.js 包含 sayHello() 函式。

function sayHello() {
   alert("Hello World")
}
廣告
© . All rights reserved.