Flask 简明教程

Flask – Static Files

Web 应用程序通常需要一个静态文件,如 javascript 文件或 CSS 文件支持 Web 页面的显示。通常,Web 服务器被配置为为您提供它们,但在开发期间,这些文件是从包中的静态文件夹或模块旁边提供,并且可以在应用程序的 /static 上使用。

A web application often requires a static file such as a javascript file or a CSS file supporting the display of a web page. Usually, the web server is configured to serve them for you, but during the development, these files are served from static folder in your package or next to your module and it will be available at /static on the application.

一个特殊的端点“static”用于生成静态文件的 URL。

A special endpoint ‘static’ is used to generate URL for static files.

在以下示例中,在 hello.js 中定义的 javascript 函数在 index.html 中的 HTML 按钮的 OnClick 事件上调用,该按钮在 ‘/’ Flask 应用程序的 URL 上呈现。

In the following example, a javascript function defined in hello.js is called on OnClick event of HTML button in index.html, which is rendered on ‘/’ URL of the Flask application.

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 脚本如下所示。

The HTML script of index.html is given below.

<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() 函数。

hello.js contains sayHello() function.

function sayHello() {
   alert("Hello World")
}