Flask static file Cache-Control

2019-02-11 18:45发布

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.

2条回答
冷血范
2楼-- · 2019-02-11 19:00

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

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-02-11 19:01

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.

查看更多
登录 后发表回答