browser caching static files in flask?

  • Last Update :
  • Techknowledgy :

First install relevant modules

sudo a2enmod expires
sudo a2enmod headers

Then add something like this to your .htaccess file:

# Expire headers
<ifModule mod_expires.c>
   ExpiresActive On
   ExpiresByType image/jpeg "access plus 1 month"
   ExpiresByType image/png "access plus 1 month"
   ExpiresByType image/gif "access plus 1 month"
   ExpiresByType text/css "access plus 1 month"
   ExpiresByType text/javascript "access plus 1 month"
   ExpiresByType application/javascript "access plus 1 month"

# Cache-Control Headers
<ifModule mod_headers.c>

   <filesMatch "\.(ico|jpe?g|png|gif)$">
      Header set Cache-Control "max-age=2592000, public"

   <filesMatch "\.(css|js)$">
      Header set Cache-Control "max-age=2592000, public"

# END Cache-Control Headers

Suggestion : 2

This tutorial details how to manage static files with Flask and WhiteNoise. We'll also configure Amazon CloudFront to get the best possible performance.,The official WhiteNoise documentation -- Using WhiteNoise with Flask -- is, as of writing, outdated and inaccurate.,There are no tutorials on using Flask with WhiteNoise and CloudFront.,You can now use the provided CloudFront domain in the Flask app to handle static file requests:

import os

from flask
import Flask, jsonify
from whitenoise
import WhiteNoise

def create_app(script_info = None):

   app = Flask(__name__, static_folder = "staticfiles")

if not app.config["DEBUG"]
else 0

# configure WhiteNoise
app.wsgi_app = WhiteNoise(
   root = os.path.join(os.path.dirname(__file__), "staticfiles"),
   prefix = "assets/",
   max_age = WHITENOISE_MAX_AGE,

def hello_world():
   return jsonify(hello = "world")

return app
├──├── static│└── bootstrap.css└── staticfiles
import os
import gzip

INPUT_PATH = os.path.join(os.path.dirname(__file__), "static")
OUTPUT_PATH = os.path.join(os.path.dirname(__file__), "staticfiles")
   # Images ".jpg",
   # Compressed files ".zip",
   # Flash ".swf",
   # Fonts ".woff",

def remove_files(path):
   print(f "Removing files from {path}")
for filename in os.listdir(path):
   file_path = os.path.join(path, filename)
if os.path.isfile(file_path):
except Exception as e:

def main():
   # remove all files from "staticfiles"

for dirpath, dirs, files in os.walk(INPUT_PATH):
   for filename in files:
   input_file = os.path.join(dirpath, filename)
with open(input_file, "rb") as f:
   data =
# compress
if file extension is not part of SKIP_COMPRESS_EXTENSIONS
name, ext = os.path.splitext(filename)
   # save compressed file to the "staticfiles"
compressed_output_file = os.path.join(OUTPUT_PATH, f "{filename}.gz")
print(f "\nCompressing {filename}")
print(f "Saving {filename}.gz")
output =, "wb")
   print(f "\nSkipping compression of {filename}")
# save original file to the "staticfiles"
output_file = os.path.join(OUTPUT_PATH, filename)
print(f "Saving {filename}")
with open(output_file, "wb") as f:

if __name__ == "__main__":
$ pip install whitenoise
$ touch static / test.png
$ python
Removing files from staticfiles

Compressing bootstrap.css
Saving bootstrap.css.gz
Saving bootstrap.css

Skipping compression of test.png
Saving test.png

Suggestion : 3

But all the static files still have max-age=0. I read about Webassets on Python Flask, but I am not sure how to use it, since I didn't find a tutorial to make all the static files have the same cache-control. How can I continue to make the same as I did for the page?,I had a low score due to Leverage browser caching since I hadn't added any max-age on headers response and it was 0. Now I have this in Python Flask:,I am doing a few tests about my website health in Google Developers site

I had a low score due to Leverage browser caching since I hadn't added any max-age on headers response and it was 0. Now I have this in Python Flask:

def add_header(response):
   response.cache_control.max_age = 86400
return response

The header response for the website:

Cache - Control max - age = 86400