Flask Static Files
Implementation of Static Files in Python Flask. This article will teach you simple ways to use python flask for creating static files and running the codes successfully.
Importance of Static files in the Python flask
Ever visited an impressive website with a great number of images, beautiful bg colors, and other beautiful tools. Static files are generally responsible for the awesome appearance of these web pages.
A single static file contains several CSS, JS files, and images embedded in it. A collection of static files are stored in a distinct folder saved as static alongside the major flask app.
That is the basic understanding of Static files. What is next is to learn how to apply them.
Related course: Create Web Apps with Python Flask
Flask Static Files
Here is how you can program a cool static file image in the background of our webpage with the flask method.
Creating the main application The code can look like this
from flask import Flask,render_template
app = Flask(__name__)
@app.route('/blog')
def blog():
return render_template('blog.html')
app.run(host='localhost', port=5000)
We used the render_template function to run the HTML file. In case, you do not get the syntax of the flask method, kindly read our article on the introduction to the Flask.
Creating a template At this juncture, we code a special URL attribute in the program to identify the Static File location.
<img src = "{{ url_for('static',filename="<filename>") }}>
The url_for function shows the file location of the template in the static folder. The image to be used in the code can be downloaded and stored in the static folder. Imagine the image titled “blog.jpg” Therefore create a template file “blog.html” and add the following codes to it.
<html>
<body>
<img src= "{{ url_for('static',filename='blog.jpg') }}">
<h2>This is a blog website</h2>
</body>
</html>
If you have no idea how to render templates in the flask, read our previous article titled Flask Templates.
Running the code Now let us test the code and view the web page. Slick!!
Conclusion
We've come to the end of this tutorial. You have all you need to run a static file on the flask. I hope you have learned something from this piece. To learn more about templates, consider reading our article on Flask templates.