Flask静态文件


Web应用程序通常需要一个静态文件,例如支持显示网页的 JavaScript 文件或 CSS 文件。通常,Web服务器被配置为为您提供服务,但在开发过程中,这些文件将从您包中的 静态 文件夹或您的模块旁边提供,它将在应用程序的 / static 上提供。

使用特殊的端点“静态”来为静态文件生成URL。

在以下示例中, index.html 中的HTML按钮的 OnClick 事件调用 hello.js中 定义的 javascript 函数,该函数在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")
}