- Flask 教程
- Flask - 首頁
- Flask - 概覽
- Flask - 環境
- Flask - 應用程式
- Flask - 路由
- Flask - 變數規則
- Flask - URL 構建
- Flask - HTTP 方法
- Flask - 模板
- Flask - 靜態檔案
- Flask - 請求物件
- 向模板傳送表單資料
- Flask - Cookie
- Flask - 會話
- Flask - 重定向和錯誤
- Flask - 顯示訊息
- Flask - 檔案上傳
- Flask - 擴充套件
- Flask - 郵件
- Flask - WTF
- Flask - SQLite
- Flask - SQLAlchemy
- Flask - Sijax
- Flask - 部署
- Flask - FastCGI
- Flask 有用資源
- Flask - 快速指南
- Flask - 有用資源
- Flask - 討論
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")
}
廣告
