Static files in Flask explained and Why are they important?

In this tutorial, we are going to discuss static files in Flask in detail. We will also discuss the importance of using static files in flask.

Static files – Flask

We use static files such as a javascript or CSS file in a webpage as the static files support the display of the webpage. Usually, we configure the web server to serve the static files for you. But at the time of development, we serve these files from the ‘static’ folder from the package or next to your module, and can be found at ‘/static’ inside your application.

‘static’ endpoint is used URL referring to static files using the url_for() function.




Now write the following piece of code in your text editor to understand more about the usage of static files in flask and save it as hello.py:-

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)

Write the following code and save it as index.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>

Now write the following piece of code in javascript and save it as world.js.

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

The above javascript code contains the sayHello() function. The sayHello() function contains an alert() method. So what the alert() method will do is that it will display an alert method when the sayHello() function is being called upon. And in our case, when the sayHello() is called the alert() method will display “Hello World” on our screens.

See that in our index.html file, inside the “<script>” tag we have declared the type as “text/javascript“. This declaration is important for the index.html to know that we are binding a javascript file, else it will give an error.

We have used the static’ endpoint, which is a special type of endpoint used to tell the url_for() function that we are referring to a static file.

In the above index.html, the javascript function in world.js is called upon when the onclick event and is rendered upon the ‘/‘ URL of our flask web application.

Then we will get “Hello World” printed on our screen when we run all the above pieces of code on python shell.

Also read:


Leave a Reply

Your email address will not be published. Required fields are marked *