How Do We Serve Static Files?
In this lesson, we will study how we can host the static files present in our Flask application.
What are static files?
Static files, or assets, are the files that the server sends to the clients “as-it-is”, i.e., without any intervention. For example, any CSS
files, background images, or JavaScript
files that we might have on our website are sent to the client without modification.
Steps to Serve Static Files
The following steps need to be taken to host a static asset.
Create a \static
directory
First, similar to the templates, we need to create a directory called \static
in our project for Flask
to recognize it. The same file structure strategies that apply to the templates will also apply here.
Create a URL for static files
In the case of a template, we create the URL
through the views and the routes associated with them. However, we do not use views for static files. So, to create a separate URL
for them, we use the url_for()
function.
url_for()
function
The url_for()
function is used to build a URL
for a certain endpoint. We can use it to build URL
s for view functions as well. It takes the name of the endpoint and any associated variables as arguments.
For example:
The following line will generate the URL
for the defined view.
url_for('view_function_name', variable_name = 'value_of_variable')
💡 Why do we need to use
url_for()
when we can hardcode theURL
?
- The
url_for()
function always returns the absoluteURL
for the endpoint. Thus, we call it anywhere in the project, and we will not have issues with relative paths.- If we end up changing the path for an endpoint or the route for a view, we do not have to change the hardcoded
URL
in the whole project.
The URL
for a static file can be created using the static
endpoint as following:
url_for('static', filename = 'name_of_file')
Example application
Get hands-on with 1400+ tech skills courses.