简体   繁体   中英

How to use Flask assets to set cache for static files

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.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM