22

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.

Paco
  • 4,520
  • 3
  • 29
  • 53
markdsievers
  • 7,151
  • 11
  • 51
  • 83
  • 5
    1. Do you use the flask dev server or a http proxy like nginx? 2. You should use ``return super(MyFlask, self).get_send_file_max_age(name)`` instead of ``return flask.Flask.get_send_file_max_age(self, name)``. – Jarus Jul 24 '12 at 10:01
  • The above class works for me, using the defualt flask development server. – i_4_got Nov 28 '12 at 20:17
  • For these and performance reasons i (and from what i've heard many others) let my static files be directly served by whatever webserver (nginx/apache) i am using. – Markus Unterwaditzer Jun 21 '13 at 13:30
  • @Jarus Sorry for the slow reply (2 years). This was the dev server only. I don't think I ever resolved this, and shortly afterward stopped using Flask (unrelated reasons). Thanks for your input all the same. – markdsievers Aug 02 '14 at 09:30
  • for those arriving here later... this [answer](https://stackoverflow.com/a/23115561/5512900) to a related question may help. You can modify the cache control headers sent by Flask using the "cache_control" collection on the Response object. See the documentation [here](https://werkzeug.palletsprojects.com/en/1.0.x/datastructures/#werkzeug.datastructures.RequestCacheControl) – MNB May 10 '20 at 17:39

2 Answers2

1

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

hllau
  • 9,879
  • 7
  • 30
  • 35
1

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.

brianc
  • 273
  • 3
  • 8