Web應(yīng)用程序通常需要一個靜態(tài)文件,例如支持顯示網(wǎng)頁的JavaScript文件或CSS文件。 通常,可以通過配置Web服務(wù)器提供這些服務(wù),但在開發(fā)過程中,這些文件將從包中的靜態(tài)文件夾或模塊旁邊提供,它將在應(yīng)用程序的/static上提供。
使用特殊的端點“靜態(tài)”來為靜態(tài)文件生成URL。
在以下示例中,index.html中的HTML按鈕的OnClick事件調(diào)用hello.js中定義的javascript函數(shù),該函數(shù)在Flask應(yīng)用程序的URL => / 中呈現(xiàn)。
# Filename : example.py
# Copyright : 2020 By Nhooo
# Author by : www.jixiangtaizi.com.cn
# Date : 2020-08-08
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腳本如下所示。
# Filename : example.py
# Copyright : 2020 By Nhooo
# Author by : www.jixiangtaizi.com.cn
# Date : 2020-08-08
<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() 函數(shù)。
# Filename : example.py
# Copyright : 2020 By Nhooo
# Author by : www.jixiangtaizi.com.cn
# Date : 2020-08-08
function sayHello() {
alert("Hello World")
}