Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 72 ยท Templates with Jinja

Static Files and Assets

Serve CSS, JavaScript and images from Flask's static folder, build URLs with url_for, understand caching headers, add cache busting and use send_from_directory.

A web page is more than HTML. The browser also needs stylesheets, scripts, images and fonts. These files do not change per request, so they are called static files. Flask serves them for you from a folder named static, and the template function url_for("static", filename=...) builds their URLs. This lesson shows how that works, how browsers cache the files, how to force a refresh when a file changes, and how to send files that are not public assets with send_from_directory.

A word on the examples: a real app keeps a static/ folder in its project, as described in project layout. The runnable editors here have no project folder, so each example creates a temporary one at run time and points Flask at it. Everything else is exactly what you would write at home.

The static folder

For app = Flask(__name__), Flask looks for a static folder next to the Python file that created the app, and it registers a route called static for it:

TEXT
myapp/
  app.py
  static/
    css/site.css
    js/app.js
    img/logo.svg
  templates/
    base.html

A request for /static/css/site.css returns that file. The route takes a <path:filename> converter (see URL variables and converters), so subfolders work. You can change the folder and the URL prefix when you create the app:

Python
app = Flask(__name__, static_folder="assets", static_url_path="/files")

If you give static_folder and leave out static_url_path, Flask uses the last part of the folder name as the URL prefix. The examples below set static_url_path explicitly because their folders are temporary directories with random names.

Python Serving a static file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The Content-Type is guessed from the file extension. The old URL /static/... now gives 404, because the folder is mounted at /assets. The last line lists the routes: Flask added a rule for the static folder, and its endpoint name is always static.

Flask's static route is perfect for development and small sites. In production, a front-end web server such as nginx or a CDN usually serves /static/ directly, which is faster and keeps Python free for dynamic requests. See deployment.

Linking assets with url_for

Never hard-code /static/css/site.css in a template. If you later move the folder, add a URL prefix or mount the app under a sub-path, every hard-coded link breaks. Ask Flask to build the URL instead, as covered in building URLs with url_for:

HTML
<link rel="stylesheet" href="{{ url_for('static', filename='css/site.css') }}">
<script src="{{ url_for('static', filename='js/app.js') }}" defer></script>
<img src="{{ url_for('static', filename='img/logo.svg') }}" alt="Logo">

The first argument is the endpoint name, static. The filename keyword is the path inside the static folder, always with forward slashes.

Python url_for with the static endpoint

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Extra keyword arguments that are not part of the route become the query string, so v=3 produced ?v=3. That tiny detail is the basis of cache busting, below.

How browsers cache static files

Fetching the same logo on every page would waste time and bandwidth, so browsers keep copies. Flask controls this with response headers. In Flask 3 the default is deliberately cautious: SEND_FILE_MAX_AGE_DEFAULT is None, which means the response has Cache-Control: no-cache, plus an ETag and a Last-Modified date. no-cache does not mean "do not store"; it means "store, but ask the server before reusing". The browser sends the ETag back in If-None-Match, and Flask answers 304 Not Modified with no body if the file is unchanged.

sequenceDiagram
    participant B as Browser
    participant F as Flask
    B->>F: GET /static/site.css
    F-->>B: 200, body, ETag "abc"
    Note over B: Stores the file with its ETag
    B->>F: GET /static/site.css<br/>If-None-Match "abc"
    F-->>B: 304 Not Modified (no body)
    Note over B: Reuses its stored copy

Revalidation saves bandwidth, but the browser still makes one round trip per file.

Python Conditional requests and 304

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The second request sent the saved ETag and got 304 with an empty body. After setting SEND_FILE_MAX_AGE_DEFAULT (a number of seconds, or a timedelta), the header becomes public, max-age=3600, so the browser reuses the file for an hour without asking at all. That is fast, but it creates a new problem.

Cache busting

With a one-hour lifetime, a visitor who loaded your CSS ten minutes ago will keep the old copy after you deploy a new one. The fix is cache busting: change the URL whenever the content changes. A browser treats site.css?v=abc123 and site.css?v=def456 as different resources. The best version string is a hash of the file's content, because it only changes when the file does.

You can add this to every url_for("static", ...) call by overriding the behavior with a context processor that supplies your own helper, or by using the built-in hook app.url_defaults. The clearest approach is a small helper function:

Python A content-hash helper for cache busting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The version in the URL changed when the content changed and returned to the first value when we restored the original text. With such URLs you can safely set a very long max-age (a year is common), because a changed file always gets a new URL. In a larger project, a frontend build tool (Vite, webpack, esbuild) usually writes hashed file names for you, and you read them from a manifest. The idea is the same.

In a real app you would compute the hash once per file and cache it, rather than reading the file on every render.

Serving images, audio and video

Media files are static files too: put them in static/ (for example static/media/) and point the HTML elements at them with url_for('static', filename=...). Nothing else is needed on the Flask side.

Python Image, audio and video from the static folder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Four details are worth knowing:

  • Seeking works out of the box. Flask's static route answers Range requests with 206 Partial Content, which is how a browser jumps to the middle of a video without downloading all of it. The output above shows Accept-Ranges: bytes and the Content-Range header.
  • Give the browser the type. The type attribute of <source> lets it skip formats it cannot play. Flask sets the Content-Type header from the file extension (video/mp4, audio/mpeg, image/svg+xml).
  • Always add alt text to images and consider captions for video (Video and Audio shows the HTML side).
  • Large media does not belong in the Flask process in production. Let nginx, a CDN or object storage serve the files, and keep Flask for the pages. For files uploaded by users use send_from_directory below and file uploads.

send_from_directory: files that are not public assets

The static route exposes every file in the folder to everyone. For other files, such as user uploads, generated reports or downloads that need a login first, write your own view and use send_from_directory(directory, filename). It joins the two safely: if the filename tries to escape the directory (../secret.txt), it raises a 404 instead of leaking the file.

Python Safe downloads with send_from_directory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

as_attachment=True adds Content-Disposition: attachment, which makes the browser save the file instead of displaying it, and download_name sets the file name the user sees. Do not build paths yourself with os.path.join(folder, name) and open; send_from_directory includes the traversal check for you. For uploaded files, also see file uploads.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where does Flask look for static files by default?

    Flask(name) registers a static route that serves files from a folder named static beside your application module.
  2. 2. Which call builds the URL of css/site.css in a template?

    static is the endpoint name and filename is the path inside the static folder. Extra keywords become the query string.
  3. 3. With the default settings in Flask 3, what does Cache-Control say for a static file?

    SEND_FILE_MAX_AGE_DEFAULT is None, so Flask sends no-cache together with an ETag and Last-Modified. The browser revalidates and gets 304 when nothing changed.
  4. 4. Why add ?v=<hash> to a stylesheet URL?

    Browsers cache by URL. When the hash changes with the content, the old cached copy is simply never requested again.
  5. 5. Why use send_from_directory instead of open(os.path.join(folder, name))?

    It rejects paths such as ../secret.txt with a 404 and sets Content-Type, caching and optional attachment headers.

Summary

  • Flask serves a static folder at /static/ through an endpoint named static; change it with static_folder and static_url_path.
  • Build asset links with url_for('static', filename='...'), never by typing the path.
  • By default Flask 3 sends no-cache, an ETag and Last-Modified, so unchanged files return 304.
  • Set SEND_FILE_MAX_AGE_DEFAULT for longer caching, and add a content hash to URLs (cache busting) so updates still reach users.
  • Use send_from_directory for downloads and non-public files; it blocks path traversal.
  • In production, let nginx or a CDN serve static files directly.

Next: let visitors send data to your app with handling HTML forms.