Search⌘ K
AI Features

How Do We Serve Static Files?

Understand how to properly serve static files such as CSS stylesheets and images in Flask by organizing them in a dedicated static directory. Learn to dynamically link these assets in templates using the url_for() function, ensuring paths adapt correctly in different deployment environments.

While our dynamic templates generate structured HTML responses based on varying Python data, a complete web application also relies on external visual and functional resources. To build a complete interface, we must instruct our Flask server how to locate and deliver these standard front-end assets directly to the browser. We accomplish this by establishing an explicit directory mapping for uncompiled files.

What are static files?

Static files, or assets, are the files that the server sends to the clients exactly as they exist on disk, without any server-side intervention or logic processing. Common examples of static assets include standard CSS stylesheets, background images, logos, and client-side JavaScript files.

Because these files do not contain Python logic or Jinja template syntax, we do not pass them through the render_template() rendering engine. Instead, Flask requires a specific operational structure to host and map these unmodified assets.

To successfully serve these assets, we execute a brief two-step setup process.

Steps to serve static files

First, similar to how we configured our templates, we must create a dedicated directory called static/ at the root of our project for the framework to ...