Flask - 静态文件

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

特殊端点'static'用于生成静态文件的URL.

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