Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask static file Cache-Control

I'm trying to set a reasonable cache expiry for my JS files while in development. I have the standard setup, where HTML, CSS and JS are living under the static directory.

The docs do mention this, but for the life of me I cannot get this to work. I've tried both methods implied, first

class MyFlask(flask.Flask):
    def get_send_file_max_age(self, name):
        if name.lower().endswith('.js'):
            return 60
        return flask.Flask.get_send_file_max_age(self, name)

app = MyFlask(__name__)

and

app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 60

Both have had no effect, my JS files under /static are still coming back with the default cache timeout,

Cache-Control: public, max-age=43200

Any pointers appreciated.

like image 998
markdsievers Avatar asked Jul 06 '12 05:07

markdsievers


2 Answers

You may want to look at webassets to manage the cache expiry. It works in both development and production environment.

like image 83
hllau Avatar answered Oct 18 '22 02:10

hllau


I had this problem and couldn't find an answer online that worked for me.

Then I realised that my static files are not being served from Flask at all! Flask only generates my HTML. The static files are served directly by my web server (Apache in my case, yours might be Nginx or something else).

Here are the instructions for Apache.

First install the mod_expires module:

sudo a2enmod expires

Then add something like this to your .htaccess file:

ExpiresByType text/css "access plus 1 year"
ExpiresByType application/javascript "access plus 1 year"
ExpiresByType image/* "access plus 1 year"

More details on how to configure it in the Apache manual.

like image 25
brianc Avatar answered Oct 18 '22 01:10

brianc