How to use Flask assets to set cache for static files

2.2k Views Asked by At

I used Flask assets in my project to combine all js and css files. Its working perfectly.

assets = Environment(app)
js = Bundle('js/jquery/jquery.js','js/owl.carousel.min.js',output='gen/packed.js')

assets.register('js_all', js)

css = Bundle('css/bootstrap.css','css/font-awesome.css','css/color.css',output='gen/packed.css')
assets.register('css_all', css)

Now i want to set expire days on static files. I checked the URL expiry part in doc. But i am confused. I want to set 30 days as expire. How can i achieve that goal using flask assets.

1

There are 1 best solutions below

2
On

There is no way to do this with Flask assets directly. It is just an asset bundler and does not control serving the final files.

However I am presuming you are running your app behind a web server like Nginx or Apache (if you're not - you should be).

Setting the expiry time with one of these is simple in the config.

Nginx

location ~* \.(?:ico|css|js|gif|jpe?g|png)$ {
    expires 30d;
    add_header Pragma public;
    add_header Cache-Control "public";
}

Apache (taken from this answer)

# enable the directives - assuming they're not enabled globally
ExpiresActive on

# send an Expires: header for each of these mimetypes (as defined by server)
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"

# css may change a bit sometimes, so define shorter expiration
ExpiresByType text/css "access plus 1 days"