[Flask] Flask static files

Flask static files

My understanding: there is no need to interact with the backend to generate data, which is what you can see directly when you open the page. (Please correct me if there is a mistake in understanding, while studying)

Web applications usually require static files, such as javascript files or CSS files that support web page display . Usually, you configure a web server and provide you with these services, but during the development process, these files are provided from the static folder next to your package or module , and it will be provided in the /static of the application .

The special endpoint'static' is used to generate static file URLs.

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

Create test_static.py file as follows

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)

Create an HTML script of templates/index.html in the same directory as test_static.py as follows:

<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>

Create a new static/hello.js in the same level directory of test_static.py to include the sayHello() function.

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

 

Guess you like

Origin blog.csdn.net/u013066730/article/details/108357350