In the last tutorial, we learned about rendering HTML in Flask. Continuing the series, in this tutorial we are going to learn how to serve static files such as images, files etc in Flask.
We are going to use url_for() function to serve static content.
About url_for() function
url_for() function in Flask allows us to create a absolute URL of resources. It takes two parameters:
This will generate the path by using the file name present in the static folder.
Here is the sample code to serve the static file using the url_for() function in Flask.
Note: You should have a file present in the folder called static.
Here is the Flask Server code.
app = Flask(__name__)
if __name__ == '__main__':
Now, run the Flask.
Navigate your browser to localhost:5000 to view the static file.
You can use the same code to serve CSS files like this:
In the next tutorial, we will learn about dynamic templating in Flask.